Beispiel #1
0
 def configure(self):
     """Pops up the GUI control widget."""
     if self.ui is None:
         self._show_glyphs()
         view = View(Group(Item(name='light_mode'),
                           Item(name='number_of_lights'),
                           label='LightManager'),
                     Group(Item(name='lights', style='custom'),
                           label='Lights',
                           selected=True,
                           show_labels=False),
                     resizable=True,
                     buttons=['OK'],
                     handler=CloseHandler())
         self.ui = view.ui(self)
     else:
         try:
             self.ui.control.Raise()
         except AttributeError:
             pass
Beispiel #2
0
class AnimatedGIFDemo(HasTraits):

    # The animated GIF file to display:
    gif_file = File(files[0])

    # Is the animation playing or not?
    playing = Bool(True)

    # The traits view:
    view = View(VGroup(
        HGroup(
            Item('gif_file',
                 editor=AnimatedGIFEditor(playing='playing'),
                 show_label=False),
            Item('playing'),
        ), '_',
        Item('gif_file', label='GIF File', editor=EnumEditor(values=files))),
                title='Animated GIF Demo',
                resizable=True,
                buttons=['OK'])
class BeamAnalysisPreferencesPage(PreferencesPage):
    """ The preferences page for the RadPy workbench. """

    #### 'PreferencesPage' interface ##########################################

    # The page's category (e.g. 'General/Appearance'). The empty string means
    # that this is a top-level page.
    category = 'General'

    # The page's help identifier (optional). If a help Id *is* provided then
    # there will be a 'Help' button shown on the preference page.
    help_id = ''
    
    # The page name (this is what is shown in the preferences dialog.
    name = 'Beam Analysis'

    # The path to the preference node that contains the preferences.
    preferences_path = 'radpy.plugins.BeamAnalysis'

    #### Preferences ##########################################################

#    # Width.
#    width = Int(100)
#
#    # Height.
#    height = Int(200)
#
#    # Ratio.
#    ratio = Float(0.1)
#    
#    # Background color.
#    bgcolor = Color('red')
#
#    # Text font.
#    font = Font('helvetica')
    
    match_traits = List(['Energy','Scan Type','Field Size'])
    choices_dict = {'Energy':'BeamDetails_Energy',
                   'Field Size':'field_size',
                   'Scan Type':'scan_type',
                   'SSD':'BeamDetails_SSD',
                   'Wedge Angle':'BeamDetails_Wedge_Angle',
                   'Applicator':'BeamDetails_Applicator',
                   'Linac Model':'BeamDetails_RadiationDevice_Model',
                   'Depth': 'depth'}
    
    choices = choices_dict.keys()
    #### Traits UI views ######################################################

    trait_view = View(Group(Item('match_traits',editor=SetEditor(name='choices',
                    can_move_all=True, ordered=False, 
                    left_column_title = 'Beam Parameters',
                    right_column_title = 'Parameters to Match'),show_label=False),
                    label='Default Parameters a Reference Beam Must Match'))
Beispiel #4
0
class Partner(HasTraits):
    name = Str('<unknown>')
    company = Instance(Company)

    view = View(Item(name='company', editor=tree_editor, show_label=False),
                title='Company Structure',
                buttons=['OK'],
                resizable=True,
                style='custom',
                width=.3,
                height=.3)
Beispiel #5
0
    def default_traits_view(self):
        """Returns the default traits view for this object."""
        if self._show_enabled:
            view = View(Group(Group(Item(name='enabled',
                                         label=self.label_text)),
                            Group(Item(name='filter', 
                                       style='custom',
                                       enabled_when='enabled',
                                       resizable=True),
                                  show_labels=False)),
                        resizable=True)
        else:
            view = View(Group(Item(name='filter', 
                                   style='custom',
                                   enabled_when='enabled',
                                   resizable=True),
                              show_labels=False),
                        resizable=True)

        return view
class Team(HasStrictTraits):

    # Trait definitions:
    players = List(Player)

    # Trait view definitions:
    traits_view = View(Item('players', show_label=False, editor=player_editor),
                       title='Baseball Team Roster Demo',
                       width=0.5,
                       height=0.5,
                       resizable=True)
class Triangle(Shape):
    a = Instance(Point, ()) 
    b = Instance(Point, ())
    c = Instance(Point, ())
    
    view = View(
        VGroup(
            Item("a", style="custom"), 
            Item("b", style="custom"),
            Item("c", style="custom"),
        )
    )
    
    @on_trait_change("a.[x,y],b.[x,y],c.[x,y]")
    def set_info(self):
        a,b,c = self.a, self.b, self.c
        l1 = ((a.x-b.x)**2+(a.y-b.y)**2)**0.5
        l2 = ((c.x-b.x)**2+(c.y-b.y)**2)**0.5
        l3 = ((a.x-c.x)**2+(a.y-c.y)**2)**0.5
        self.info = "edge length: %f, %f, %f" % (l1,l2,l3)
Beispiel #8
0
class FilterDemo(HasTraits):
    kernel = Array(shape=(3, 3), dtype=np.float)
    scale = Float

    view = View(Item("kernel", label="卷积核"),
                Item("scale", label="乘积因子"),
                title="Filter Demo控制面板")

    def __init__(self, *args, **kwargs):
        super(FilterDemo, self).__init__(*args, **kwargs)
        self.kernel = np.ones((3, 3))
        self.img = cv.imread("lena.jpg")
        self.on_trait_change(self.redraw, "kernel,scale")
        self.scale = 1.0 / 9.0

    def redraw(self):
        img2 = cv.Mat()
        kernel = cv.asMat(self.kernel * self.scale, force_single_channel=True)
        cv.filter2D(self.img, img2, -1, kernel)
        cv.imshow("Filter Demo", img2)
Beispiel #9
0
class Report(HasTraits):

    people = List(Person)

    view = View(Group(Item('people', id='table', editor=tabular_editor),
                      show_labels=False),
                title='Tabular Editor Demo',
                id='enthought.traits.ui.demo.Applications.tabular_editor_demo',
                width=0.60,
                height=0.75,
                resizable=True)
Beispiel #10
0
class Department(HasStrictTraits):
    employees = List(Employee)
    traits_view = View(Group(Item('employees', editor=table_editor),
                             show_border=True,
                             show_labels=False),
                       title='Department Personnel',
                       width=.4,
                       height=.4,
                       resizable=True,
                       buttons=['OK', 'Cancel', 'Undo'],
                       kind='live')
Beispiel #11
0
class HistDemo(HasTraits):
    plot = Instance(Plot)
    timer = Instance(Timer)
    need_update = Bool(False)
    view = View(Item("plot", editor=ComponentEditor(), show_label=False),
                resizable=True,
                width=500,
                height=250,
                title="Hist Demo")

    def __init__(self, **traits):
        super(HistDemo, self).__init__(**traits)
        img = cv.imread("lena.jpg")
        gray_img = cv.Mat()
        cv.cvtColor(img, gray_img, cv.CV_BGR2GRAY)
        self.img = gray_img
        self.img2 = self.img.clone()
        result = cv.MatND()

        r = cv.vector_float32([0, 256])
        ranges = cv.vector_vector_float32([r, r])

        cv.calcHist(cv.vector_Mat([self.img]),
                    channels=cv.vector_int([0, 1]),
                    mask=cv.Mat(),
                    hist=result,
                    histSize=cv.vector_int([256]),
                    ranges=ranges)

        data = ArrayPlotData(x=np.arange(0, len(result[:])), y=result[:])
        self.plot = Plot(data, padding=10)
        line = self.plot.plot(("x", "y"))[0]
        self.select_tool = RangeSelection(line, left_button_selects=True)
        line.tools.append(self.select_tool)
        self.select_tool.on_trait_change(self._selection_changed, "selection")
        line.overlays.append(RangeSelectionOverlay(component=line))

        cv.imshow("Hist Demo", self.img)

        self.timer = Timer(50, self.on_timer)

    def _selection_changed(self):
        if self.select_tool.selection != None:
            self.need_update = True

    def on_timer(self):
        if self.need_update:
            x0, x1 = self.select_tool.selection
            self.img2[:] = self.img[:]
            np.clip(self.img2[:], x0, x1, out=self.img2[:])
            self.img2[:] -= x0
            self.img2[:] *= 256.0 / (x1 - x0)
            cv.imshow("Hist Demo", self.img2)
            self.need_update = False
Beispiel #12
0
class ModuleFilterAdderNode(AdderNode):
    """ Tree node that presents a view to the user to add filter and
        modules.
    """

    # The string to display on the icon in the TreeEditor.
    label = 'Add module or filter'

    # An adder node for modules
    modules = Instance(ModuleAdderNode, ())

    # An adder node for filters
    filters = Instance(FilterAdderNode, ())

    def _object_changed(self):
        """ Propagate the object to the sub nodes.
        """
        self.filters.object = self.object
        self.modules.object = self.object

    # Trait view to show in the Mayavi current object panel.
    view = View(
        Group(Item(
            'modules',
            style='custom',
            springy=True,
            resizable=True,
            height=1.,
        ),
              show_labels=False,
              label='Visualization modules'),
        Group(Item(
            'filters',
            style='custom',
            springy=True,
            resizable=True,
            height=1.,
        ),
              show_labels=False,
              label='Processing filters'),
    )
Beispiel #13
0
    def default_traits_view(self):
        nodes = [
            TreeNode(
                node_for=[AdderNode],
                label='name',
                copy=False,
                delete=False,
                rename=False,
                children='items_list',
            ),
            TreeNode(
                node_for=[DocumentedItem],
                label='name',
                copy=False,
                delete=False,
                rename=False,
                icon_item=self.icon_name,
            ),
        ]

        tree_editor = TreeEditor(
            editable=False,
            hide_root=True,
            orientation='vertical',
            selected='object.selected_item',
            nodes=nodes,
            on_dclick='object._on_tree_dclick',
        )

        view = View(Item('self',
                         show_label=False,
                         editor=tree_editor,
                         resizable=True,
                         springy=True,
                         height=0.5),
                    Item('selected_item',
                         style='custom',
                         show_label=False,
                         height=0.5),
                    resizable=True)
        return view
Beispiel #14
0
class ControlPanel(HasStrictTraits):

    data_source = Instance(BaseDataSource)
    data_viewer = Instance(BaseDataViewer)
    has_data = DelegatesTo('data_source')
    kind = DelegatesTo('data_source')
    selected_channel = DelegatesTo('data_source')
    memusage = DelegatesTo('data_viewer')
    status = DelegatesTo('data_viewer')
    statusbar = Str

    @on_trait_change('data_viewer.memusage, data_viewer.status')
    def update_statusbar(self):
        if hasattr(self, 'memusage'):
            memusage = bytes2str(self.memusage)
            status = self.status
            if status:
                self.statusbar = 'MEMUSAGE=%s | STATUS: %s' % (memusage,
                                                               status)
            else:
                self.statusbar = 'MEMUSAGE=%s' % (memusage)

    traits_view = View(
        Tabbed(
            Item("data_source",
                 style='custom',
                 show_label=False,
                 resizable=True),
            Item('data_viewer',
                 style='custom',
                 resizable=True,
                 show_label=False),
            show_border=True,
        ),
        buttons=['OK'],
        resizable=True,
        handler=ViewHandler(),
        height=800,
        width=1000,
        statusbar='statusbar',
    )
Beispiel #15
0
class ScatterPlotTraits(HasTraits):

    plot = Instance(Plot)
    color = ColorTrait("blue")
    marker = marker_trait
    marker_size = Int(4)
    x = Array()
    y = Array()

    traits_view = View(Group(Item('color', label="Color", style="custom"),
                             Item('marker', label="Marker"),
                             Item('marker_size', label="Size"),
                             Item('plot',
                                  editor=ComponentEditor(),
                                  show_label=False),
                             orientation="vertical"),
                       width=800,
                       height=600,
                       resizable=True,
                       title="Chaco Plot")

    def __init__(self):
        super(ScatterPlotTraits, self).__init__()
        x = linspace(-14, 14, 10)
        y = sin(x) * x**3
        plotdata = ArrayPlotData(x=x, y=y)
        plot = Plot(plotdata)
        self.x = x
        self.y = y

        self.renderer = plot.plot(("x", "y"), type="scatter", color="blue")[0]
        self.plot = plot

    def _color_changed(self):
        self.renderer.color = self.color

    def _marker_changed(self):
        self.renderer.marker = self.marker

    def _marker_size_changed(self):
        self.renderer.marker_size = self.marker_size
Beispiel #16
0
class TrimCase(HasTraits):
    # Instance(RunCase)
    runcase = Any()
    type = Trait('horizontal flight', {'horizontal flight':'c1',
                  'looping flight':'c2'})
    parameters = Dict(String, Instance(Parameter))
    parameter_view = List(Parameter, [])
    traits_view = View(Group(Item('type')),
                       Group(Item('parameter_view', editor=Parameter.editor, show_label=False), label='Parameters'),
                        Item(), # so that groups are not tabbed
                        kind='livemodal',
                        buttons=['OK']
                       )
    
    #@on_trait_change('type,parameters.value')
    def update_parameters_from_avl(self):
        #print 'in update_parameters_from_avl'
        avl = self.runcase.avl
        avl.sendline('oper')
        avl.expect(AVL.patterns['/oper'])
        avl.sendline(self.type_)
        avl.expect(AVL.patterns['/oper/m'])
        
        constraint_lines = [line.strip() for line in avl.before.splitlines()]
        i1 = constraint_lines.index('=================================================')
        constraint_lines = constraint_lines[i1:]
        #print constraint_lines
        groups = [re.search(RunCase.patterns['parameter'], line) for line in constraint_lines]
        params = {}
        for group in groups:
            if group is not None:
                group = group.groupdict()
                pattern = group['pattern']
                name = pattern
                unit = group.get('unit', '')
                unit = unit if unit is not None else ''
                params[name] = Parameter(name=name, pattern=pattern, cmd=group['cmd'], unit=unit, value=float(group['val']))
        AVL.goto_state(avl)
        self.parameters = params
        self.parameter_view = sorted(params.values(), key=lambda x:x.name.upper())
        return self
Beispiel #17
0
class ExamplesPreferencesPage(HelpPreferencesPage):
    """ Page for the "Examples" preferences tree node.
    """
    name = 'Examples'
    preferences_path = PKG + '.Examples'

    #### Preferences ###########################################################

    editor = Str

    traits_view = View(
        Item(name='editor', label='Command for external editor'), )
Beispiel #18
0
class KBCodeExample(HasPrivateTraits):

    code = Code
    status = Str
    kb = Button(label='Edit Key Bindings')

    view = View(Group(
        Item('code', style='custom', resizable=True),
        Item('status', style='readonly'),
        'kb',
        orientation='vertical',
        show_labels=False,
    ),
                id='KBCodeExample',
                key_bindings=key_bindings,
                title='Code Editor With Key Bindings',
                resizable=True,
                handler=CodeHandler())

    def _kb_fired(self, event):
        key_bindings.edit_traits()
class ShapeSelector(HasTraits):
    select = Enum(*[cls.__name__ for cls in Shape.__subclasses__()]) 
    shape = Instance(Shape) 
    
    view = View(
        VGroup(
            Item("select"),
            Item("shape", style="custom"), 
            Item("object.shape.info", style="custom"), 
            show_labels = False
        ),
        width = 350, height = 300, resizable = True
    )
    
    def __init__(self, **traits):
        super(ShapeSelector, self).__init__(**traits)
        self._select_changed()
    
    def _select_changed(self):
        klass =  [c for c in Shape.__subclasses__() if c.__name__ == self.select][0]
        self.shape = klass()    
class Demo(HasTraits):
    plot = Instance(Component)

    traits_view = View(Group(Item('plot',
                                  editor=ComponentEditor(size=size),
                                  show_label=False),
                             orientation="vertical"),
                       resizable=True,
                       title=title)

    def _plot_default(self):
        return _create_plot_component()
Beispiel #21
0
 def _dialog_box(self, title, msg):
     self.dialog_msg = msg
     view = \
         View(
             Group(
                 Item(name='dialog_msg', style='readonly'),
                 show_labels=False
             ),
             title=title,
             buttons=[OKButton],
         )
     self.edit_traits(view, kind='livemodal')
 class Test(HasTraits):
     figure = Instance(Figure, ())
     view = View(
         Item("figure", editor=MPLFigureEditor(), show_label=False),
         width = 400,
         height = 300,
         resizable = True)
     def __init__(self):
         super(Test, self).__init__()
         axes = self.figure.add_subplot(111)
         t = linspace(0, 2*pi, 200)
         axes.plot(sin(t))
Beispiel #23
0
class FigText(HasStrictTraits):
    """Defines figure settable text attributes
    """
    #: text that is displayed
    text = Str('')
    #: position of the text, shoud be a tuple (0.2,0.2) by default
    position = Tuple((0.2, 0.2))

    view = View(Item('text', style='custom'),
                'position',
                resizable=True,
                width=200)
Beispiel #24
0
class Cutter(Component):
    # The version of this class.  Used for persistence.
    __version__ = 0

    # The mapper.
    cutter = Instance(tvtk.Cutter, args=())

    # The cut function.  This should be a delegate but due to a bug in
    # traits that does not work.
    cut_function = Property

    ########################################
    # View related traits.

    view = View(Group(Item(name='cutter', style='custom', resizable=True),
                      show_labels=False),
                resizable=True)

    ######################################################################
    # `Component` interface
    ######################################################################
    def update_pipeline(self):
        """Override this method so that it *updates* the tvtk pipeline
        when data upstream is known to have changed.

        This method is invoked (automatically) when the input fires a
        `pipeline_changed` event.
        """
        if (len(self.inputs) == 0) or (len(self.inputs[0].outputs) == 0):
            return
        c = self.cutter
        c.input = self.inputs[0].outputs[0]
        self.outputs = [c.output]

    def update_data(self):
        """Override this method to do what is necessary when upstream
        data changes.

        This method is invoked (automatically) when any of the inputs
        sends a `data_changed` event.
        """
        self.data_changed = True

    ######################################################################
    # `Cutter` interface
    ######################################################################
    def _get_cut_function(self):
        return self.cutter.cut_function

    def _set_cut_function(self, val):
        old = self.cutter.cut_function
        self.cutter.cut_function = val
        self.trait_property_changed('cut_function', old, val)
Beispiel #25
0
class _ChangePassword(HasTraits):
    """This represents the change password data and view."""

    #### '_ChangePassword' interface ##########################################

    # The user name.
    name = Unicode

    # The new user password.
    new_password = Password

    # The confirmed new user password.
    confirm_new_password = Password

    # The default view.
    traits_view = View(Item(name='name', style='readonly'),
                       Item(name='new_password'),
                       Item(name='confirm_new_password'),
                       title="Change password",
                       kind='modal',
                       buttons=OKCancelButtons)
Beispiel #26
0
class OCCModel(HasTraits):
    shapes = List
    
    shape_list = Instance(ShapeList)

    traits_view=View(HSplit(
                    Item('shape_list', editor=occ_tree, show_label=False,
                         width=-300),
                    Item('shape_list', editor=CustomEditor(MakeCanvas),
                            show_label=False, resizable=True),
                        id="occ.traits.test_feature_model_layout",
                        dock="fixed"
                        ),
                    resizable=True,
                    width=1000,
                    height=800,
                    id="occ.traits.test_feature_model"
                    )
                    
    def _shapes_changed(self, vnew):
        self.shape_list = ShapeList(shapes=vnew)
Beispiel #27
0
class FigureWindow(HasTraits):
    figure = Instance(Figure, ())

    view = View(Item('figure', editor=MPLFigureEditor(), show_label=False),
                width=400,
                height=300,
                resizable=True)

    def _figure_default(self):
        figure = Figure()
        ax = figure.add_subplot(111)
        return figure
Beispiel #28
0
class BaseSetup(HasTraits):
    """Base station setup at the origin of a survey."""
    id = String
    x = Float
    y = Float
    z = Float
    z_offset = Float
    horizontal_angle_offset = Instance(AngleDMS, kw={'degrees': 0,
                                                     'minutes': 0,
                                                     'seconds': 0})
    view = View(Group(HGroup(Item('x',
                                  springy = True),
                            Item('y',
                                 springy = True),
                            Item('z',
                                 springy = True)),
                      HGroup(Item('z_offset')),
                      Item('horizontal_angle_offset', style='custom'),
                      label='Base station setup',
                      show_border=True)
    )
Beispiel #29
0
class IMUGloveDisplay(HasTraits):
    plot = Instance(HPlotContainer)
    traits_view = View(Item('plot', editor=ComponentEditor(),
                            show_label=False),
                       width=1000,
                       height=600,
                       resizable=True,
                       title="IMU Glove Display")

    def __init__(self):
        super(IMUGloveDisplay, self).__init__()
        x = linspace(-14, 14, 100)
        y = sin(x) * x**3
        plotdata = ArrayPlotData(x=x, y=y)
        scatter = Plot(plotdata)
        scatter.plot(("x", "y"), type="scatter", color="blue")
        line = Plot(plotdata)
        line.plot(("x", "y"), type="line", color="blue")
        container = HPlotContainer(scatter, line)
        #scatter.title = "sin(x) * x^3"
        #line.title = 'line plot'
        self.plot = container
        self.InitGlove()

    def InitGlove(self):
        self.api = GloveAPI()
        self.api.initHardware()
        self.api.debug(False)
        self.api.configimu()

    def ReadData(self, numToRead):
        ''' Start streaming data '''
        self.api.stream(numToRead)

        self.api.clearIMUPacketEngine()
        keys = [
            'sentinal', 'footer', 'temp', 'gx', 'gy', 'gz', 'ax', 'ay', 'az',
            'sentinal'
        ]
        #keys = ['gx','gy','gz','ax','ay','az']
        packets = []
        t = time.time()
        for x in range(0, numToRead):
            p = self.api.getIMUPacket()
            if p:
                ''' Update the data in the plot.. '''
                showPacket(p, keys)
            else:
                self.api.configimu()
                self.api.stream(numToRead - x)

        tdiff = time.time() - t
        print("Total time:%6.6f Time per Packet:%6.6f" % (tdiff, tdiff / x))
Beispiel #30
0
class BaseViewer(HasTraits):
    main_tab = Instance(Component)

    traits_view = View(Item('main_tab', editor=ComponentEditor),
                       width=500,
                       height=500,
                       resizable=True,
                       title="Salinity Plot")

    def __init__(self, **kwargs):
        HasTraits.__init__(self, **kwargs)
        self.init_data()

    def init_data(self):
        file_name = '/home/dpothina/work/apps/pysonde/tests/ysi_test_files/BAYT_20070323_CDT_YS1772AA_000.dat'
        sonde = Sonde(file_name)
        sal_ds = np.array([1, 2, 3, 4, 5, 6, 7,
                           8])  # sonde.data['seawater_salinity']
        time_ds = sal_ds**2  # [time.mktime(date.utctimetuple()) for date in sonde.dates]
        #time_ds = ArrayDataSource(dt)
        #sal_ds = ArrayDataSource(salinity, sort_order="none")
        self.plot_data = ArrayPlotData(sal_ds=sal_ds, time_ds=time_ds)

    def _main_tab_default(self):
        self.sal_plot = Plot(self.plot_data)
        self.sal_plot.plot(('time_ds', 'sal_ds'), type='line')
        #sal_plot.overlays.append(PlotAxis(sal_plot, orientation='left'))
        #bottom_axis = PlotAxis(sal_plot, orientation="bottom",# mapper=xmapper,
        #                   tick_generator=ScalesTickGenerator(scale=CalendarScaleSystem()))
        #sal_plot.overlays.append(bottom_axis)

        #hgrid, vgrid = add_default_grids(sal_plot)
        #vgrid.tick_generator = bottom_axis.tick_generator
        #sal_plot.tools.append(PanTool(sal_plot, constrain=True,
        #                              constrain_direction="x"))
        #sal_plot.overlays.append(ZoomTool(sal_plot, drag_button="right",
        #                                  always_on=True,
        #                                  tool_mode="range",
        #                                  axis="index",
        #                                  max_zoom_out_factor=10.0,
        #                                  ))

        container = VPlotContainer(bgcolor="lightblue",
                                   spacing=40,
                                   padding=50,
                                   fill_padding=False)
        container.add(sal_plot)
        #container.add(price_plot)
        #container.overlays.append(PlotLabel("Salinity Plot with Date Axis",
        #                                    component=container,
        #                                    #font="Times New Roman 24"))
        #                                    font="Arial 24"))
        return container