Esempio n. 1
0
 def getViewItems(self, context_name=""):
     Items, Context = super().getViewItems(context_name=context_name)
     Items[0].editor = SetEditor(
         values=self.trait("TestFactors").option_range)
     Items[3].editor = SetEditor(
         values=self.trait("CorrMethod").option_range)
     return (Items, Context)
Esempio n. 2
0
    def test_simple_set_editor_deleted_valid_values(self):
        editor_factory = SetEditor(values=["one", "two", "three", "four"])
        view = View(UItem(
            "value",
            editor=editor_factory,
            style="simple",
        ))
        list_edit = ListModel()

        with reraise_exceptions(), self.setup_gui(list_edit, view) as editor:

            self.assertEqual(get_list_items(editor._unused), ["four", "three"])
            self.assertEqual(get_list_items(editor._used), ["one", "two"])

            editor_factory.values = ["two", "three", "four"]
            process_cascade_events()

            self.assertEqual(get_list_items(editor._unused), ["four", "three"])
            # FIXME issue enthought/traitsui#840
            if is_wx():
                with self.assertRaises(AssertionError):
                    self.assertEqual(get_list_items(editor._used), ["two"])
                self.assertEqual(get_list_items(editor._used), ["one", "two"])
            else:
                self.assertEqual(get_list_items(editor._used), ["two"])
            self.assertEqual(list_edit.value, ["two"])
Esempio n. 3
0
    def test_simple_editor_mapping_values(self):
        class IntListModel(HasTraits):
            value = List()

        set_editor_factory = SetEditor(
            values=[0, 1], format_func=lambda v: str(bool(v)).upper())
        formatted_view = View(
            UItem(
                "value",
                editor=set_editor_factory,
                style="simple",
            ))

        with reraise_exceptions(), self.setup_ui(IntListModel(),
                                                 formatted_view) as editor:

            self.assertEqual(editor.names, ["FALSE", "TRUE"])
            self.assertEqual(editor.mapping, {"FALSE": 0, "TRUE": 1})
            self.assertEqual(editor.inverse_mapping, {0: "FALSE", 1: "TRUE"})

            set_editor_factory.values = [1, 0]

            self.assertEqual(editor.names, ["TRUE", "FALSE"])
            self.assertEqual(editor.mapping, {"TRUE": 1, "FALSE": 0})
            self.assertEqual(editor.inverse_mapping, {1: "TRUE", 0: "FALSE"})
Esempio n. 4
0
class SetEditorDemo(HasTraits):
    """ This class specifies the details of the SetEditor demo.
    """

    # Define a trait each for four variants
    unord_nma_set = List(
        editor=SetEditor(values=['kumquats', 'pomegranates', 'kiwi'],
                         can_move_all=False,
                         left_column_title='Available Fruit',
                         right_column_title='Exotic Fruit Bowl'))

    unord_ma_set = List(
        editor=SetEditor(values=['kumquats', 'pomegranates', 'kiwi'],
                         left_column_title='Available Fruit',
                         right_column_title='Exotic Fruit Bowl'))

    ord_nma_set = List(
        editor=SetEditor(values=['apples', 'berries', 'cantaloupe'],
                         ordered=True,
                         can_move_all=False,
                         left_column_title='Available Fruit',
                         right_column_title='Fruit Bowl'))

    ord_ma_set = List(
        editor=SetEditor(values=['apples', 'berries', 'cantaloupe'],
                         ordered=True,
                         left_column_title='Available Fruit',
                         right_column_title='Fruit Bowl'))

    # SetEditor display, unordered, no move-all buttons.
    no_nma_group = Group(Item('unord_nma_set', style='simple'),
                         label='Unord I',
                         show_labels=False)

    # SetEditor display, unordered, move-all buttons.
    no_ma_group = Group(Item('unord_ma_set', style='simple'),
                        label='Unord II',
                        show_labels=False)

    # SetEditor display, ordered, no move-all buttons.
    o_nma_group = Group(Item('ord_nma_set', style='simple'),
                        label='Ord I',
                        show_labels=False)

    # SetEditor display, ordered, move-all buttons.
    o_ma_group = Group(Item('ord_ma_set', style='simple'),
                       label='Ord II',
                       show_labels=False)

    # The view includes one group per data type.  These will be displayed
    # on separate tabbed panels.
    view1 = View(no_nma_group,
                 no_ma_group,
                 o_nma_group,
                 o_ma_group,
                 title='SetEditor',
                 buttons=['OK'])
Esempio n. 5
0
    def _pipeline_view(self, show_label=True):
        import wx
        if wx.GetApp() is None:
            return None
        
        from traitsui.api import View, Group, Item, TextEditor, SetEditor

        modname = ','.join(self.inputs) + ' -> ' + self.__class__.__name__ + ' -> ' + ','.join(self.outputs)

        if show_label:
            return View(Group(Item('idColumnName'),
                              Item('ids', editor=SetEditor(values=self._possible_ids)),label=modname))
        else:
            return View(Group(Item('idColumnName'),
                              Item('ids', editor=SetEditor(values=self._possible_ids))))
Esempio n. 6
0
    def test_simple_editor_mapping_name(self):
        class IntListModel(HasTraits):
            value = List()
            possible_values = List([0, 1])

        formatted_view = View(
            UItem(
                'value',
                editor=SetEditor(
                    name="object.possible_values",
                    format_func=lambda v: str(bool(v)).upper(),
                ),
                style="simple",
            ))
        model = IntListModel()

        with reraise_exceptions(), self.setup_ui(model,
                                                 formatted_view) as editor:

            self.assertEqual(editor.names, ["FALSE", "TRUE"])
            self.assertEqual(editor.mapping, {"FALSE": 0, "TRUE": 1})
            self.assertEqual(editor.inverse_mapping, {0: "FALSE", 1: "TRUE"})

            model.possible_values = [1, 0]

            self.assertEqual(editor.names, ["TRUE", "FALSE"])
            self.assertEqual(editor.mapping, {"TRUE": 1, "FALSE": 0})
            self.assertEqual(editor.inverse_mapping, {1: "TRUE", 0: "FALSE"})
 def trait_view(self, name=None, view_element=None):
     legal_values = [
         value for value in self.context.keys()
         if hasattr(self.context[value], 'shape')
         and len(self.context[value].shape) == 1
     ]
     return View(VSplit(
         Item(
             'plot_list',
             editor=SetEditor(
                 values=legal_values,
                 left_column_title='Variables',
                 right_column_title='Plots',
             ),
             show_label=False,
             width=400,
             height=100,
         ),
         Item('plot',
              editor=InstanceEditor(),
              style='custom',
              show_label=False),
     ),
                 width=500,
                 height=500,
                 resizable=True)
Esempio n. 8
0
 def default_traits_view(self):
     v = View(VGroup(
         Item('headstage_flavor', label='HS Type'),
         Item('file_dir', label='Data directory'),
         Tabbed(
             UItem('working_files',
                   editor=SetEditor(name='_available_hdf5_files',
                                    left_column_title='Available files',
                                    right_column_title='Files to process',
                                    ordered=True)),
             UItem('filters', style='custom')),
         HGroup(
             VGroup(
                 HGroup(UItem('batch_proc'), UItem('join')),
                 HGroup(UItem('batch_with_handoff'),
                        Label('Filter with level matching')),
             ), spring, Item('file_suffix', label='File suffix'), spring,
             Item('file_size',
                  label='Estimated file size',
                  style='readonly')),
         HGroup(UItem('downsample'),
                Item('ds_rate', label='Downsample factor'),
                Item('set_Fs', label='Fs for set', style='readonly')),
     ),
              handler=FilesHandler,
              title='Batch processing tool',
              resizable=True)
     return v
Esempio n. 9
0
    def __init__(self, **traits):
        """Initialise the object."""

        buttons = [
            Action(name="Search"),
            Action(name="Add"),
            Action(name="Modify"),
            Action(name="Delete"), CancelButton
        ]

        all_perms = list(
            get_permissions_manager().policy_manager.permissions.values())

        perms_editor = SetEditor(values=all_perms,
                                 left_column_title="Available Permissions",
                                 right_column_title="Assigned Permissions")

        perms_group = Group(Item(name='permissions', editor=perms_editor),
                            label='Permissions',
                            show_border=True,
                            show_labels=False)

        super(_RoleView, self).__init__(Item(name='name'),
                                        Item(name='description'),
                                        perms_group,
                                        buttons=buttons,
                                        **traits)
Esempio n. 10
0
class DeviceManager(BaseManager):
    name = 'Devices'

    available = List()
    included = List()
    devices = List(BaseDevice)
    view = View(
        VGroup(
            Item(name='included',
                 editor=SetEditor(
                     name='available',
                     left_column_title='Available',
                     right_column_title='System',
                 ),
                 show_label=False), ), )

    def _included_changed(self):
        self.devices = [dev() for dev in self.included]

    def _available_default(self):
        return [dev for dev in device_dict.values()]

    def _included_default(self):
        return [dev for dev in device_dict.values()]

    def _devices_default(self):
        return [dev() for dev in device_dict.values()]
Esempio n. 11
0
 def default_traits_view(self):
     view = View(VGroup(
         UItem('_selected_items_names',
               editor=SetEditor(name='_all_items_names',
                                ordered=True,
                                left_column_title=u'Not Displayed',
                                right_column_title=u'Displayed')), ),
                 title=self.title,
                 buttons=OKCancelButtons)
     return view
Esempio n. 12
0
def get_view(can_move_all=True, ordered=False):
    return View(
        UItem(
            "value",
            editor=SetEditor(
                values=["one", "two", "three", "four"],
                ordered=ordered,
                can_move_all=can_move_all,
            ),
            style="simple",
        ))
Esempio n. 13
0
class Team(HasTraits):

    batting_order = List(Str)
    roster = List(['Tom', 'Dick', 'Harry', 'Sally'], Str)

    view = View(
        Item('batting_order', editor=SetEditor(name='roster', ordered=True)),
        '_',
        'roster@',
        height=500,
        resizable=True,
    )
Esempio n. 14
0
class StoragePlotter(HasTraits):

    figure = Instance(Figure, ())
    avail_columns = List(Str)
    columns = List(editor=SetEditor(
        name='avail_columns',
        format_func=lambda x: x,
    ), )

    view = View(
        HSplit(
            Item('figure', editor=MPLFigureEditor(), show_label=False),
            Item(
                'columns',
                style='custom',
                show_label=False,
            ),
            scrollable=True,
        ),
        width=700,
        height=400,
        resizable=True,
    )

    def __init__(self, stofpath, *args):
        HasTraits.__init__(self, trait_value=True)
        if stofpath.endswith('.sto') or stofpath.endswith('.mot'):
            if 'StaticOptimization' in stofpath:
                self.data = storage2numpy(stofpath, excess_header_entries=2)
            else:
                self.data = storage2numpy(stofpath)
        elif stofpath.endswith('.trc'):
            self.data = TRCFile(stofpath).data
        avail_columns = list(self.data.dtype.names)
        avail_columns.remove('time')
        self.avail_columns = avail_columns

        self.axes = self.figure.add_subplot(111)

        # TODO
        #for arg in args:
        #    self.columns.append(arg)
        #    self._columns_changed()

    @on_trait_change('columns')
    def _columns_changed(self):
        self.axes.cla()
        for name in self.columns:
            self.axes.plot(self.data['time'], self.data[name], label=name)
        self.axes.set_xlabel('time (s)')
        self.axes.legend(loc='best')
        self.figure.canvas.draw()
Esempio n. 15
0
    def default_view(self):
        import wx
        if wx.GetApp() is None:
            return None
        
        from traitsui.api import View, Group, Item, TextEditor, SetEditor
        from PYME.ui.custom_traits_editors import CBEditor, FilterEditor

        return View(Item('inputName', editor=CBEditor(choices=self._namespace_keys)),
                    Item('_'),
                    Item('idColumnName'),
                    Item('ids', editor=SetEditor(values=self._possible_ids)),
                    Item('_'),
                    Item('outputName'), buttons=['OK'])
class waveform(HasTraits):
    name = Str
    channels = List(['empty', 'empty'])
    time = List()
    data = List()

    #This object is used as the channel selector
    select_channels = List(editor=SetEditor(
        name='channels',
        ordered=False,
        left_column_title='Available Channels',
        right_column_title='Plot Channels'), )
    #
    view = View(Item('select_channels', show_label=False), )
Esempio n. 17
0
    def __init__(self, all_roles, **traits):
        """Initialise the object."""

        buttons = [Action(name="Search"), Action(name="Save"), CancelButton]

        roles_editor = SetEditor(values=list(all_roles.values()),
                left_column_title="Available Roles",
                right_column_title="Assigned Roles")

        roles_group = Group(Item(name='roles', editor=roles_editor),
                label='Roles', show_border=True, show_labels=False)

        super(_AssignmentView, self).__init__(Item(name='user_name'),
                Item(name='description', style='readonly'), roles_group,
                buttons=buttons, **traits)
Esempio n. 18
0
 def default_traits_view(self):
     v = View(VGroup(
         HGroup(
             VGroup(
                 Label('Headstage'),
                 UItem('headstage'),
             ), VGroup(Label('Channel map'), UItem('chan_map')),
             UItem('concat_tool_launch'),
             HGroup(VGroup(
                 Label('N signal channelsl'),
                 UItem('n_chan'),
             ),
                    VGroup(Label('Skip chans'), UItem('skip_chan')),
                    VGroup(Label('Grid geometry'), UItem('elec_geometry')),
                    visible_when='chan_map=="unknown"'),
             VGroup(Label('Connectors (comma-sep)'),
                    UItem('chan_map_connectors'),
                    visible_when='_is_subset_map')),
         Tabbed(
             UItem('file_data', style='custom'),
             UItem('filters', style='custom'),
             UItem('module_set',
                   editor=SetEditor(name='all_modules',
                                    left_column_title='Analysis modules',
                                    right_column_title='Modules to load')),
         ),
         HGroup(
             VGroup(Label('Offset per channel (in uV)'), UItem('offset', )),
             VGroup(Label('Screen Channels?'), UItem('screen_channels')),
             VGroup(Label('Begin screening at x minutes'),
                    UItem('screen_start'))),
         HGroup(UItem('b'),
                Item('max_window_width', label='Max. window length'))),
              resizable=True,
              title='Launch Visualization',
              handler=HeadstageHandler)
     return v
Esempio n. 19
0
class PortfolioModel(HasTraits):


    symbols = List(init_symbols)
    # Test this for now...
    symbols2 = List(Instance(Symbol))
    symbol_pool = List(Instance(Symbol))

    # Arbitrary date range for pulling asset data
    startdate = Str("2000-01-1")
    enddate = Str("2012-03-23")

    dbfilename = File("data/stocks.db")
    portfolio = Instance(mpt.Portfolio)
    plot = Instance(Component)

    recalc_button = Button(label='Recalculate')
    save_plot_button = Button(label='Save Plot')

    symbol_pool_item = Item('symbol_pool', editor=symbol_pool_tabular_editor,
                                 width=20, resizable=True)

    symbols_item = Item('symbols', style="simple", resizable=True,
                        editor=SetEditor(values=all_symbols,
                        can_move_all=True,
                        left_column_title='Symbols',
                        right_column_title='Selected Symbols'),
                        width=0.1)

    model_portfolio_x = Float(0.0241)
    model_portfolio_y = Float(0.051)
    
    traits_view = View(
                    Group(
                        Group(
                            Item('dbfilename',
                                 label='Database File',
                                 width=-20),
                            Item('startdate',
                                 label='Start Date',
                                 width=-20),
                            Item('enddate',
                                 label='End Date',
                                 width=-20),
                            Item('model_portfolio_x',
                                 label='Model Portfolio Volatility',
                                 style='simple'),
                            Item('model_portfolio_y',
                                 label='Model Portfolio Return',
                                 style='simple'),
                            Item('recalc_button', show_label=False,
                                 width=-20),
                            Item('save_plot_button', show_label=False,
                                 width=-20),
                            symbols_item,
                            #symbol_pool_item,
                            Item('symbols2', editor=symbols_tabular_editor,
                                 height=0.2, springy=True),
                            orientation="vertical",
                            springy=True,
                            id='leftpane'),
                        Group(
                            Item('plot',
                                editor=ComponentEditor(size=(400,400)),
                                show_label=False),
                            orientation="vertical",
                            show_labels=False
                            ),
                        orientation="horizontal",
                        show_labels=False),
                    resizable=True,
                    title="Markowitz Mean-Variance View (MPT)",
                    width=0.9,
                    height=0.9)

    def __init__(self, *args, **kw):
        self.symbols.sort()
        super(PortfolioModel, self).__init__(*args, **kw)
        symbol_list = price_utils.load_symbols_from_table(dbfilename=self.dbfilename)['symbol'].tolist()
        self.symbol_pool = [Symbol(symbol=symb) for symb in symbol_list]
        #self.symbols2 = [Symbol(symbol=s) for s in init_symbols]
        self.plot = self._create_plot_component()

    # #############################
    # Methods triggered by trait events
    # #############################
    def _recalc_button_fired(self, event):
        self.symbols.sort()
        self.plot = self._create_plot_component(recalc=True)
        #self.plot.invalidate_draw()
        self.plot.request_redraw()

    def _save_plot_button_fired(self, event):
        save_plot(pm.plot, "chaco_ef.png", 400,300)

    def _dbfilename_changed(self, event):
        #reload symbols
        # TODO: what's the right way to do this?
        symbol_list = price_utils.load_symbols_from_table(dbfilename=self.dbfilename)['symbol'].tolist()
        #print self.dbfilename, symbol_list
        if len(symbol_list) > 2:
            #print "New symbols: ", symbol_list
            self.trait_view('symbols_item').editor.values = symbol_list
            #print "Symbol list setting: ", self.trait_view('symbols_item').editor.values

            self.trait_view('traits_view').updated = True

            self.symbols = symbol_list[:2]
            #self.trait_view( 'symbols' ).updated = True
        return


    def _symbols_changed(self, event):
        self.symbols2 = [Symbol(symbol=s) for s in self.symbols]

    def _plot_default(self):
        return self._create_plot_component()
    
    def get_stock_data(self):
        
        self.portfolio = p = mpt.Portfolio(symbols=self.symbols,
                                 startdate=self.startdate, enddate=self.enddate,
                                 dbfilename=db)
                                 
        # Assemble and report pre-optimized portfolio data
        x = []
        y = []

        for symbol in p.symbols:
            stk = p.stocks[symbol]
            x.append(stk.annual_volatility)
            y.append(stk.annualized_adjusted_return)
    
        return x, y
    
    def get_ef_data(self):
    
        # Note: The risk tolerance variable seems to require a daily
        # volatility value, given our daily rate data.  So, to make this more
        # friendly, start with annual volatility and convert for our
        # calculations.
        rt0 = 0.02
        rtn = 1.0
        rtstep = 0.02
        tdy = TRADING_DAYS_PER_YEAR
        rtrange = np.arange(rt0/tdy, rtn/tdy, rtstep/tdy)

        efx = []
        efy = []
        allocations = {}
        
        p = self.portfolio
    
        for rt in rtrange:
            p.optimize_portfolio(rt=rt, lower_bound_weight=0.1, upper_bound_weight=1.0)
            px = p.port_opt.volatility
            py = p.port_opt.portfolio_return
            efx.append(px)
            efy.append(py)
            # convert to annual returns in %
            allocations[round(rt * 100, 2)] = p.port_opt.weights

            # reset the optimization
            p.port_opt = None

        # cache the results
        self.efx = efx
        self.efy = efy
        self.allocations = allocations

        return efx, efy, allocations


    def _create_plot_component(self, recalc=False):

        container = VPlotContainer()

        ### Assemble the scatter plot of the Efficient Frontier
        x, y = self.get_stock_data()
        if not hasattr(self, "efx") or recalc:
            efx, efy, allocations = self.get_ef_data()
        else:
            efx = self.efx
            efy = self.efy

        p = self.portfolio

        symbs = p.symbols

        pd = ArrayPlotData(x=x, y=y, efx=efx, efy=efy, mp_x=[self.model_portfolio_x], mp_y=[self.model_portfolio_y])

        # Create some plots of the data
        plot = Plot(pd, title="Efficient Frontier")

        # Create a scatter plot (and keep a handle on it)
        stockplt = plot.plot(("x", "y"), color="transparent",
                                         type="scatter",
                                         marker="dot",
                                         marker_line_color="transparent",
                                         marker_color="transparent",
                                         marker_size=1)[0]

        efplt = plot.plot(("efx", "efy"), color=(0.0,0.5,0.0,0.25),
                                          type="scatter",
                                          marker="circle",
                                          marker_size=6)[0]
        efpltline = plot.plot(("efx", "efy"), color=(0.1,0.4,0.1,0.7),
                                          type="line")[0]


        # Create another one-point scatter for a model portfolio
        mp_plot = plot.plot(("mp_x", "mp_y"), color=(1.0, 0.5, 0.5, 0.25),
            type="scatter",
            market="triangle",
            market_size=7)[0]

        for i in range(len(p.stocks)):
            label = DataPointLabel(component=plot, data_point=(x[i], y[i]),
                              label_position="bottom right",
                              padding=4,
                              bgcolor="transparent",
                              border_visible=False,
                              text=self.symbols[i],
                              marker="circle",
                              marker_color=(0.0,0.0,0.5,0.25),
                              marker_line_color="lightgray",
                              marker_size=6,
                              arrow_size=8.0,
                              arrow_min_length=7.0,
                              font_size=14)

            plot.overlays.append(label)

            tool = DataLabelTool(label, drag_button="left", auto_arrow_root=True)
            label.tools.append(tool)

        stockplt.tools.append(ScatterInspector(stockplt, selection_mode="toggle",
                                          persistent_hover=False))

        scatinsp = ScatterInspectorOverlay(stockplt,
                hover_color = "red",
                hover_marker_size = 8,
                hover_outline_color = (0.7, 0.7, 0.7, 0.5),
                hover_line_width = 1)

        stockplt.overlays.append(scatinsp)

        # Tweak some of the plot properties
        plot.padding = 50
        stockplt.value_range.low=0.0
        stockplt.value_range.high=0.1
        stockplt.index_range.low=0.0
        stockplt.index_range.high=0.1
        # Attach some tools to the plot
        plot.tools.append(PanTool(plot, drag_button="right"))
        plot.overlays.append(ZoomTool(plot))

        #### Assemble the "stacked area" plot
        if not hasattr(self, "efx") or recalc:
            a = self.get_ef_data()[2]
        else:
            a = self.allocations

        rts = a.keys()
        rts.sort()
        rts = np.array(rts)

        symbs = a[rts[0]].keys()
        symbs.sort()

        # "Transpose" symbols' weights to get vectors of weights for each symbol
        symb_data = np.array([[a[rt][symb] for rt in rts] for symb in symbs])

        self.symbols2 = [Symbol(symbol=symbs[i], color=COLORS[i]) for i in range(len(symbs))]

        # Create a plot data object and give it this data
        bpd = ArrayPlotData()
        bpd.set_data("index", rts)
        bpd.set_data("allocations", symb_data)

        # Create a contour polygon plot of the data
        bplot = Plot(bpd, title="Allocations")
        bplot.stacked_bar_plot(("index", "allocations"),
                        color = COLORS,
                        outline_color = "gray")

        bplot.padding = 50
        #bplot.legend.visible = True

        # Add a plot of the stocks
        stock_obj_list = [p.stocks[symb] for symb in symbs]
        
        #for itm in stock_obj_list:
            #itm.print_traits()
            #print "Has Cache?:", itm.stock_data_cache is not None

        splot = StockPlot(stocks=[p.stocks[symb] for symb in symbs], colors=COLORS).plot

        container.add(bplot)
        container.add(plot)
        container.add(splot)
        
        return container
Esempio n. 20
0
 def _view_items(self, params=None):
     from traitsui.api import Item, TextEditor, SetEditor
     return [
         Item('idColumnName'),
         Item('ids', editor=SetEditor(values=self._possible_ids)),
     ]
Esempio n. 21
0
class ContribFinder(HasTraits):
    """
    This class helps find installed mayavi contributions.
    """

    # The preference helper whose contrib_packages trait we contribute
    # to.
    preference_helper = Instance(HasTraits)

    # The selected contributions.
    contrib_packages = DelegatesTo('preference_helper')

    # The found contrib packages.
    found_contrib = List(Str,
                         desc='the mayavi contribution '
                         'packages on the system')

    # Search for contributions.
    search = Button('Search for packages',
                    desc='search again for contributions')

    ########################################
    # View related code.

    view = View(Item('contrib_packages',
                     show_label=False,
                     editor=SetEditor(name='found_contrib',
                                      left_column_title='Available '\
                                                        'contributions',
                                      right_column_title='Selected '\
                                                        'contributions',
                                      can_move_all=False),
                     resizable=True,
                     ),
                 Item('search', show_label=False),
                 resizable=True
                )

    ######################################################################
    # `object` interface.
    ######################################################################
    def __init__(self, **traits):
        super(ContribFinder, self).__init__(**traits)
        # Find the contributions by default.
        self.find()

    ######################################################################
    # `ContribFinder` interface.
    ######################################################################
    def find(self):
        """Find the contrib directories from sys.path."""
        found = []
        for d in sys.path:
            if isdir(d):
                for s in listdir(d):
                    if exists(join(d, s, 'user_mayavi.py')):
                        found.append(s)
        self.found_contrib = found

    ######################################################################
    # Non-public interface.
    ######################################################################
    def _preference_helper_default(self):
        from preference_manager import preference_manager
        return preference_manager.root

    def _search_fired(self):
        self.find()
Esempio n. 22
0
class calterm_data_viewer(HasTraits):
    """
    This is the user interface for plotting results from data acquisition
    supplemented with log file data from Calterm III, the Cummins ECM
    interface application. The UI is built with Enthought's Traits and TraitsUI
    """
    parameters = List(Parameter)
    selected_params = List
    parameter_names = Property(List(String), depends_on=['parameters'])
    parameter_units = Property(List(String), depends_on=['parameters'])

    channels = List(Channel)
    channel_names = Property(List(String), depends_on=['channels'])
    channel_gains = Property(List(String), depends_on=['channels'])
    selected_channels = List
    selected_channels_gains = Property(List(Float),
                                       depends_on=['selected_channels'])
    ## UI elements
    align_button = Button()
    plot_button = Button()
    save_button = Button()

    param_select_button = Button()
    channel_select_button = Button()
    gain_set_button = Button()

    sensor_data = Data()
    log_data = Data()

    data_file = File(filter=['csv'])
    log_file = File(filter=['csv'])

    data_file_status = Str('none loaded')
    log_file_status = Str('none loaded')

    # The text being edited:
    text = Str

    # The current length of the text being edited:
    length = Property(depends_on='text')

    # The current time:
    time = Str

    main_view = View(Group(Group(Group(Item(name='data_file', style='simple'),
                                       Item('channel_select_button',
                                            label='Ch. Select',
                                            show_label=False),
                                       Item('gain_set_button',
                                            label='Gain Set',
                                            show_label=False),
                                       orientation='horizontal'),
                                 Group(Item(name='log_file', style='simple'),
                                       Item('param_select_button',
                                            label='Parameter Select',
                                            show_label=False),
                                       orientation='horizontal'),
                                 orientation='vertical'),
                           Group(Item(name='align_button',
                                      label="Align Data",
                                      show_label=False),
                                 Item(name='plot_button',
                                      label="Plot",
                                      show_label=False),
                                 Item(name='save_button',
                                      label="Save",
                                      show_label=False),
                                 orientation="vertical"),
                           orientation="horizontal"),
                     statusbar=[
                         StatusItem(name='data_file_status', width=85),
                         StatusItem(name='log_file_status', width=85)
                     ],
                     title="Calterm III data alignment and analysis",
                     buttons=[OKButton])

    parameter_view = View(Item(name='selected_params',
                               show_label=False,
                               style='custom',
                               editor=SetEditor(
                                   name='parameter_names',
                                   ordered=True,
                                   can_move_all=True,
                                   left_column_title="Available parameters",
                                   right_column_title="Parameters to plot")),
                          title="Select parameters to plot",
                          buttons=[OKButton, CancelButton])

    channel_view = View(Item(name='selected_channels',
                             show_label=False,
                             style='custom',
                             editor=SetEditor(
                                 name='channel_names',
                                 ordered=True,
                                 can_move_all=True,
                                 left_column_title="Available channels",
                                 right_column_title="Channels to plot")),
                        title="Select channels to plot",
                        buttons=[OKButton, CancelButton])

    gains_view = View(
        Item(
            name='channels',
            style='custom',
            #             editor=TableEditor()),
            editor=ListEditor(use_notebook=True)),
        title="Set the gains for each channel",
        buttons=[OKButton, CancelButton])

    def _get_parameter_names(self):
        return [n.name for n in self.parameters]

    def _get_parameter_units(self):
        return [n.unit for n in self.parameters]

    def _get_channel_names(self):
        return [n.name for n in self.channels]

    def _get_channel_gains(self):
        return [n.gain for n in self.channels]

    def _channel_gains_changed(self):
        print "setting gains.\n"
        print self.channel_gains
        for n in range(self.channel_gains):
            self.channels[n].gain = channel_gains[n]

    def _get_selected_channels_gains(self):
        return [
            self.channel_gains[self.channel_names.index(n)]
            for n in self.selected_channels
        ]

    def _log_file_changed(self):
        [self.log_data.time, self.log_data.data, err] = \
                             import_calterm_log_file(self.log_file)
        if not err:
            self.log_data.loaded = True
            [p, u] = import_calterm_log_param_names(self.log_file)
            p_raw = p.split(',')
            u_raw = u.split(',')
            self.parameters = []
            for i in range(len(p_raw)):
                self.parameters.append(Parameter(name=p_raw[i], unit=u_raw[i]))
            self.configure_traits(view='parameter_view')
        else:
            print "Deal with the error here."
            self.log_data.loaded = False

    def _param_select_button_fired(self):
        self.configure_traits(view='parameter_view')

    def _channel_select_button_fired(self):
        self.configure_traits(view='channel_view')

    def _gain_set_button_fired(self):
        self.configure_traits(view='gains_view')

    def _data_file_changed(self):
        from os.path import splitext
        DEFAULT_GAIN = 1.875  ## nA/V
        DEFAULT_UNIT = 'nA'

        def npz_open():
            npz = np.load(self.data_file)
            return ([npz['time'], npz['data']])

        def csv_open():
            import re
            f = open(self.data_file)
            date_str = f.readline()
            step_str = f.readline()
            [a, b] = re.split("=", step_str.strip('\r\n'))
            step = float(b)
            del a, b
            data = np.genfromtxt(f, delimiter=',', unpack=True, names=True)
            f.close()
            length = data.shape[0]
            time = np.linspace(0, step * (length - 1), length)
            return ([time, data])

        fileopen = {
            '.npz': npz_open,
            '.csv': csv_open,
        }
        [self.sensor_data.time, self.sensor_data.data] = \
                                fileopen[splitext(self.data_file)[1]]()
        for i in self.sensor_data.data.dtype.names:
            self.channels.append(
                Channel(name=i, gain=DEFAULT_GAIN, unit=DEFAULT_UNIT))
        self.sensor_data.loaded = True
        self.configure_traits(view='channel_view')

    def _plot_button_fired(self):
        import matplotlib as mpl
        import matplotlib.pyplot as plt

        pad = 0.05
        fig_width = 8.5
        ax_left = 0.18
        ax_width = 0.75

        #Count how many axes need to be plotted
        num_axes = 0 + self.sensor_data.loaded
        #ax[i].set_ylabel(self.selected_param

        if self.log_data.loaded:
            num_axes += len(self.selected_params)
        if not (num_axes):
            print "No files loaded or no parameters selected.\n"
            return

        fig_height = 11  ## 2. * num_axes + 1.5
        fig = plt.figure(1, figsize=[fig_width, fig_height])
        fig.clf()

        #calculate the geometry for displaying the axes
        total_pad = pad * (num_axes + 1)
        ax_height = (1. - total_pad) / num_axes
        ax_bottom = np.linspace(pad, 1. - (ax_height + pad), num_axes)
        ax_top = ax_bottom + ax_height
        ax = {}

        for i in range(num_axes - self.sensor_data.loaded):
            ax[i] = fig.add_axes([ax_left, ax_bottom[i], ax_width, ax_height])
            ax[i].plot(self.log_data.time - self.log_data.time[0],
                       self.log_data.data[self.selected_params[i]])
            ax[i].set_ylabel(self.selected_params[i].replace('_', ' '))

        i = num_axes - 1
        if self.sensor_data.loaded:
            ax[i] = fig.add_axes([ax_left, ax_bottom[i], ax_width, ax_height])
            for j in range(len(self.selected_channels)):
                ax[i].plot(self.sensor_data.time,
                           self.sensor_data.data[self.selected_channels[j]] \
                           * self.selected_channels_gains[j],
                           label=self.selected_channels[j].replace('_', ' '))
            ax[i].set_xlabel('Time (s)')
            ax[i].set_ylabel('Sensor Current (nA)')
            ax[i].legend(loc='best')
        fig.show()

    def start(self):
        self.configure_traits(view='main_view')
Esempio n. 23
0
class MainWindow(HasTraits):
    display = Instance(TextDisplay(), ())
    model = Instance(Model)
    figure = Instance(ImageGrid, ())
    layers = t.List(editor=SetEditor(name='avail'))
    category = Int(0)
    restrict = Bool()
    predicate = String()
    fraction = Float()
    percentile = Float(0.0)
    back = Button()

    view = View(Item('display',
                     show_label=False,
                     style='custom',
                     style_sheet='*{font-size:11pt}'),
                Tabbed(Group('model', 'layers', label='Model'),
                       Group(Group('category',
                                   'restrict',
                                   Item('back', show_label=False),
                                   orientation='horizontal',
                                   style='simple'),
                             Group(Item('predicate', style='readonly'),
                                   Item('fraction', style='readonly'),
                                   Item('percentile', style='simple'),
                                   orientation='horizontal'),
                             Item('figure',
                                  editor=ImageGridEditor(),
                                  show_label=False,
                                  springy=True),
                             label='Images'),
                       style='custom',
                       style_sheet='*{font-size:11pt}'),
                resizable=True)

    # List of availaible layers, used by `layers`, above
    avail = t.List([])

    # Stack of states
    _states: List[State] = []
    signals: Signals

    def _model_default(self):
        return Model(top=self)

    def __init__(self):
        super(MainWindow, self).__init__()
        self.signals = Signals()
        self.signals.model_loaded.connect(self.model_loaded)
        self.signals.push_state.connect(self.push_state)

    def update(self):
        self.figure.clear()
        if len(self._states):
            self._states[-1].render()

    def model_loaded(self):
        state = InitState()
        self.model._data_model_changed()  # update the interpolation parameters
        self.model._size_changed()  # update model evaluators
        state.top = self
        self.avail = self.model.layers()
        layer_idxs = self.model.data_model.params.get('layers', [])
        self.layers = list_elems(self.avail, [i + 1 for i in layer_idxs])
        self.message(
            'Select layers for explanations, then choose an input image in the images tab.\n'
        )
        self.push_state(state)

    def push_state(self, state: State):
        self._states.append(state)
        self.update()
        QApplication.restoreOverrideCursor()

    def message(self, msg: str):
        self.display.string = self.display.string + msg

    def onclick(self, event):
        if self._states:
            self._states[-1].onclick(event)

    def on_axes_enter(self, event):
        if self._states:
            self._states[-1].on_axes_enter(event)

    def _back_fired(self):
        if len(self._states) > 1:
            self._states.pop()
            QApplication.setOverrideCursor(Qt.WaitCursor)
            self.update()
            QApplication.restoreOverrideCursor()

    def _restrict_changed(self):
        self.update()

    def _category_changed(self):
        self.update()
Esempio n. 24
0
class LineListEditor(HasTraits):
    candidates = List
    candidatenames = Property(depends_on='candidates')
    selectednames = List
    selectedobjs = Property(depends_on='selectednames')
    selectedlocs = Property(depends_on='selectednames')
    lineplot = Instance(LinePlot)

    major_view = View(Item('selectednames',
                           editor=SetEditor(
                               name='candidatenames',
                               left_column_title='Candidate Lines',
                               right_column_title='Selected Lines'),
                           show_label=False),
                      Item('lineplot', show_label=False, style='custom'),
                      title='Major Lines')

    minor_view = View(Item('selectednames',
                           editor=SetEditor(
                               name='candidatenames',
                               left_column_title='Candidate Lines',
                               right_column_title='Selected Lines'),
                           show_label=False),
                      Item('lineplot', show_label=False, style='custom'),
                      title='Minor Lines')

    @cached_property
    def _get_candidatenames(self):
        return tuple([str(line) for line in self.candidates])

    @cached_property
    def _get_selectedlocs(self):
        return tuple([o.loc for o in self.selectedobjs])

    @cached_property
    def _get_selectedobjs(self):
        return tuple([
            self.candidates[self.candidatenames.index(n)]
            for n in self.selectednames
        ])

    def _set_selectedobjs(self, val):
        cs, cns, cls = [], [], []
        for c in self.candidates:
            cs.append(c)
            cns.append(str(c))
            cls.append(c.loc)

        names = []
        for v in val:
            if isinstance(v, basestring):
                if v not in cns:
                    raise ValueError('line name ' + v + ' not found')
                names.append(v)
            elif np.isscalar(v):
                if v not in cls:
                    raise ValueError('line location ' + str(v) + ' not found')
                names.append(cns[cls.index(v)])
            else:
                if v not in cs:
                    raise ValueError('line object ' + str(v) + ' not found')
                names.append(cns[cs.index(v)])
        self.names = names
Esempio n. 25
0
    def trait_view(self, name=None, view_element=None):
        """ Creates the view of the data explorer.
        """
        columns = ([NumericColumn(name='model_indices', label='i')] + [
            NumericColumn(name=item.name, format=self.format)
            for item in self.model.model_items
        ])

        number_editor = NumericEditor(columns=columns,
                                      edit_selection_colors=False,
                                      user_selection_filter=IndexFilter(),
                                      deletable=True,
                                      sortable=True,
                                      auto_size=False)

        selection_editor = NumericEditor(
            columns=columns,
            extendable=False,
            choose_selection_filter=False,
            edit_selection_filter=False,
            #user_selection_filter   = IndexFilter(),
            choose_reduction_filter=False,
            edit_reduction_filter=False,
            deletable=False,
            sortable=False,
            auto_size=False)

        return View(VSplit(
            HSplit(
                Tabbed(Item('model', editor=number_editor),
                       Item('selection_model{Selection}',
                            editor=selection_editor),
                       label='Model',
                       export='DockShellWindow',
                       show_labels=False),
                Item('plots@',
                     width=300,
                     height=300,
                     editor=ListEditor(use_notebook=True,
                                       deletable=True,
                                       dock_style='tab',
                                       export='DockShellWindow',
                                       view='view',
                                       page_name='.page_name'),
                     label='Plots',
                     show_label=False,
                     export='DockShellWindow'),
            ),
            HSplit(
                VGroup(VGroup(
                    Item('plot_items{}',
                         editor=SetEditor(
                             name='values',
                             can_move_all=False,
                             left_column_title='Available values:',
                             right_column_title='Values to plot:')), '_',
                    VGroup(
                        Item('plot_index',
                             editor=InstanceEditor(name='values',
                                                   editable=False)),
                        HGroup('plot_name<134>', 'plot{}'))),
                       label='Plot items',
                       export='DockShellWindow'),
                Item('plot_items',
                     width=300,
                     height=150,
                     editor=plot_items_table_editor,
                     label='Plot properties',
                     show_label=False,
                     export='DockShellWindow')),
            id='splitter'),
                    title=self.title,
                    id='blockcanvas.model.numeric_model_explorer',
                    dock='horizontal',
                    width=0.4,
                    height=0.5,
                    resizable=True,
                    buttons=NoButtons)