Пример #1
0
    def get_fav_group(self, edit_view=None):
        cols = [CheckboxColumn(name='enabled'),
                CheckboxColumn(name='default'),
                ObjectColumn(name='kind'),
                ObjectColumn(name='name'),
                ObjectColumn(name='username'),
                ObjectColumn(name='password',
                             format_func=lambda x: '*' * len(x),
                             editor=TextEditor(password=True)),
                ObjectColumn(name='host'),
                ObjectColumn(name='dbname',
                             label='Database',
                             editor=EnumEditor(name='names')),
                ObjectColumn(name='path', style='readonly')]

        editor = TableEditor(columns=cols,
                             selected='_selected',
                             sortable=False)
        if edit_view:
            editor.edit_view = edit_view

        fav_grp = VGroup(UItem('_fav_items',
                               width=100,
                               editor=editor),
                         HGroup(
                             icon_button_editor('add_favorite', 'database_add',
                                                tooltip='Add saved connection'),
                             icon_button_editor('add_favorite_path', 'dbs_sqlite',
                                                tooltip='Add sqlite database'),
                             icon_button_editor('delete_favorite', 'delete',
                                                tooltip='Delete saved connection'),
                             icon_button_editor('test_connection_button', 'database_connect',
                                                tooltip='Test connection'),
                             icon_button_editor('load_names_button', 'arrow_refresh',
                                                enabled_when='load_names_enabled',
                                                tooltip='Load available database schemas on the selected server'),
                             Spring(width=10, springy=False),
                             Label('Status:'),
                             CustomLabel('_connected_label',
                                         label='Status',
                                         weight='bold',
                                         color_name='_connected_color'),
                             spring,
                             show_labels=False))
        return fav_grp
from kromatography.model.product import Product
from kromatography.model.product_component import ProductComponent
from kromatography.model.product_component_assay import ProductComponentAssay
from kromatography.model.factories.product_component_assay import \
    assay_instances_from_names, assay_names_from_instances
from kromatography.utils.traitsui_utils import NoAutoTextEditor
from .product_component_model_view import COMPONENT_NAME_TOOLTIP, \
    VALID_COMP_NAME

COMPONENT_TABLE_EDITOR = TableEditor(
    columns=[
        ObjectColumn(name='name',
                     _label="Component name",
                     editor=NoAutoTextEditor(),
                     cell_color="lightgrey"),
        UnitScalarColumn(name='molecular_weight'),
        UnitScalarColumn(name='extinction_coefficient'),
    ],
    auto_size=True,
    sortable=False,
    row_factory=ProductComponent,
)

COMPONENT_CONC_EXPRESSION_EDITOR = TabularEditor(adapter=PandasSeriesAdapter(
    values_label="Concentration expression",
    values_tooltip=("Component concentration expression. Should be valid "
                    "python expressions only using the assays names below"
                    " and the total product concentration as "
                    "`product_concentration`."),
    index_label="Component name",
    index_tooltip="Component name"))
Пример #3
0
    import VGroup, HGroup, Item, TableEditor

from traitsui.table_column \
    import ObjectColumn

from etsdevtools.developer.tools.envisage_browser.object_adapter \
    import Export

from etsdevtools.developer.tools.envisage_browser.extension_point_adapter \
    import ExtensionPointAdapter

#-------------------------------------------------------------------------------
#  Precedes table editor definition:
#-------------------------------------------------------------------------------

precedes_table_editor = TableEditor(
    columns=[ObjectColumn(name='precedes', width=0.97)], editable=False)

#-------------------------------------------------------------------------------
#  'ResourceManagerAdapter' class:
#-------------------------------------------------------------------------------


class ResourceManagerAdapter(ExtensionPointAdapter):

    #-- ExtensionPointAdapter Overrides --------------------------------------------

    def get_children(self):
        """ Returns the unadapted extension points immediately contained within
            this one.
        """
        return self.adaptee.resource_types
Пример #4
0

EDIT_VIEW = View(HGroup(preferred_item, metadata_grp))

cols = [
    CheckboxColumn(name='use', label='Save', width=10),
    UObjectColumn(name='identifier', width=50),
    BaseColumn(name='name', width=50),
    BaseColumn(name='repository_identifier',
               width=50,
               editor=EnumEditor(name='controller.repository_identifiers')),
]

editor = TableEditor(columns=cols,
                     orientation='vertical',
                     selection_mode='rows',
                     selected='selected',
                     sortable=False,
                     edit_view=EDIT_VIEW)

VIEW = okcancel_view(HGroup(
    icon_button_editor(
        'sync_metadata_button',
        'database_link',
        tooltip='Sync the Interpreted Age metadata with the database. This '
        'will supersede the metadata saved with the analyses. Use '
        'this option if the metadata is missing or if the metadata '
        'was modified after analysis')),
                     Item('items', show_label=False, editor=editor),
                     width=1200,
                     title='Set Interpreted Age')
Пример #5
0
    def _get_assess_value(self):
        return self.ls_table.assess_value

    traits_view = View(Item('ls_table@', show_label=False),
                       resizable=True,
                       scrollable=True)


# The definition of the demo TableEditor:
lcc_list_editor = TableEditor(
    columns_name='lcc_table_columns',
    editable=False,
    selection_mode='row',
    selected='object.lcc',
    show_toolbar=True,
    auto_add=False,
    configurable=True,
    sortable=True,
    reorderable=False,
    sort_model=False,
    auto_size=False,
)


class LCCTable(HasTraits):
    '''Loading Case Manager.
    Generates and sorts the loading case combinations
    of all specified loading cases.
    '''

    # define ls
Пример #6
0
            self.name = self._name
            fbi_wiretap.wiretap((self.object, None, self.condition), True)
            fbi_wiretap.wiretap((self.object, self.name, self.condition),
                                False)


#-------------------------------------------------------------------------------
#  Wiretap table editor definition:
#-------------------------------------------------------------------------------

wiretap_table_editor = TableEditor(columns=[
    ObjectColumn(name='entire_object'),
    ObjectColumn(name='object', editable=False),
    ObjectColumn(name='name', editable=False),
    ObjectColumn(name='condition')
],
                                   deletable=True,
                                   configurable=False,
                                   auto_size=False,
                                   selection_bg_color=0xFBD391,
                                   selection_color='black')

#-------------------------------------------------------------------------------
#  'Wiretap' plugin:
#-------------------------------------------------------------------------------


class Wiretap(HasPrivateTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
        return 'light grey'


# The 'players' trait table editor:
player_editor = TableEditor(sortable=False,
                            configurable=False,
                            auto_size=False,
                            selected_indices='selected_player_indices',
                            columns=[
                                CheckboxColumn(name='in_lineup',
                                               label='In Lineup',
                                               width=0.12),
                                PlayerColumn(name='name',
                                             editable=False,
                                             width=0.24,
                                             horizontal_alignment='left'),
                                PlayerColumn(name='at_bats', label='AB'),
                                PlayerColumn(name='strike_outs', label='SO'),
                                PlayerColumn(name='singles', label='S'),
                                PlayerColumn(name='doubles', label='D'),
                                PlayerColumn(name='triples', label='T'),
                                PlayerColumn(name='home_runs', label='HR'),
                                PlayerColumn(name='walks', label='W'),
                                PlayerColumn(name='average',
                                             label='Ave',
                                             editable=False,
                                             format='%0.3f')
                            ])


class Player(HasStrictTraits):
class PropertyListDemo(HasPrivateTraits):
    """ Displays a random list of Person objects in a TableEditor that is
        refreshed every 3 seconds by a background thread.
     """

    # An event used to trigger a Property value update:
    ticker = Event

    # The property being display in the TableEditor:
    people = Property(List, depends_on='ticker')

    # Tiny hack to allow starting the background thread easily:
    begin = Int

    #-- Traits View Definitions ------------------------------------------------

    view = View(Item('people',
                     show_label=False,
                     editor=TableEditor(columns=[
                         ObjectColumn(name='name', editable=False, width=0.50),
                         ObjectColumn(name='age', editable=False, width=0.15),
                         ObjectColumn(name='gender',
                                      editable=False,
                                      width=0.35)
                     ],
                                        auto_size=False,
                                        show_toolbar=False)),
                title='Property List Demo',
                width=0.25,
                height=0.33,
                resizable=True)

    #-- Property Implementations -----------------------------------------------

    @cached_property
    def _get_people(self):
        """ Returns the value for the 'people' property.
        """
        return [
            Person(name='%s %s' %
                   (choice(['Tom', 'Dick', 'Harry', 'Alice', 'Lia', 'Vibha']),
                    choice(['Thomas', 'Jones', 'Smith', 'Adams', 'Johnson'])),
                   age=randint(21, 75),
                   gender=choice(['Male', 'Female']))
            for i in xrange(randint(10, 20))
        ]

    #-- Default Value Implementations ------------------------------------------

    def _begin_default(self):
        """ Starts the background thread running.
        """
        thread = Thread(target=self._timer)
        thread.setDaemon(True)
        thread.start()

        return 0

    #-- Private Methods --------------------------------------------------------

    def _timer(self):
        """ Triggers a property update every 3 seconds for 30 seconds.
        """
        for i in range(10):
            sleep(3)
            self.ticker = True
Пример #9
0
    def traits_view(self):
        def column(klass=ObjectColumn, editable=False, **kw):
            return klass(text_font='arial 10', editable=editable, **kw)

        cols = [
            column(klass=CheckboxColumn,
                   name='use',
                   label='Use',
                   editable=True,
                   width=30),
            column(name='hole_id', label='Hole'),
            column(name='identifier', label='Identifier'),
            column(name='sample', label='Sample', width=115),
            #column(name='x', label='X', format='%0.3f', width=50),
            #column(name='y', label='Y', format='%0.3f', width=50),
            #column(name='theta', label=u'\u03b8', format='%0.3f', width=50),
            column(name='n', label='N'),
            column(name='saved_j',
                   label='Saved J',
                   format_func=lambda x: floatfmt(x, n=6, s=4)),
            column(name='saved_jerr',
                   label=u'\u00b1\u03c3',
                   format_func=lambda x: floatfmt(x, n=6, s=4)),
            column(name='percent_saved_error',
                   label='%',
                   format_func=lambda x: floatfmt(x, n=2)),
            column(name='mean_j',
                   label='Mean J',
                   format_func=lambda x: floatfmt(x, n=6, s=4) if x else ''),
            column(name='mean_jerr',
                   label=u'\u00b1\u03c3',
                   format_func=lambda x: floatfmt(x, n=6, s=4) if x else ''),
            column(name='percent_mean_error',
                   label='%',
                   format_func=lambda x: floatfmt(x, n=2) if x else ''),
            column(name='j',
                   label='Pred. J',
                   format_func=lambda x: floatfmt(x, n=8, s=4),
                   width=75),
            column(name='jerr',
                   format_func=lambda x: floatfmt(x, n=10, s=4),
                   label=u'\u00b1\u03c3',
                   width=75),
            column(name='percent_pred_error',
                   label='%',
                   format_func=lambda x: floatfmt(x, n=2) if x else ''),
            column(name='dev', label='dev', format='%0.2f', width=70),
            column(klass=CheckboxColumn,
                   name='save',
                   label='Save',
                   editable=True,
                   width=30)
        ]

        editor = TableEditor(columns=cols, sortable=False, reorderable=False)

        jfloatfmt = lambda x: floatfmt(x, n=2)
        v = View(
            VSplit(
                UItem('graph',
                      style='custom',
                      editor=InstanceEditor(),
                      height=0.72),
                VGroup(
                    HGroup(
                        UItem('recalculate_button'),
                        Item('min_j',
                             format_str='%0.4e',
                             style='readonly',
                             label='Min. J'),
                        Item('max_j',
                             style='readonly',
                             format_str='%0.4e',
                             label='Max. J'),
                        Item('percent_j_change',
                             style='readonly',
                             format_func=floatfmt,
                             label='Delta J(%)'),
                        Item('j_gradient',
                             style='readonly',
                             format_func=floatfmt,
                             label='Gradient J(%/cm)'), spring,
                        icon_button_editor(
                            'save_unknowns_button',
                            'dialog-ok-5',
                            tooltip='Toggle "save" for unknown positions'),
                        icon_button_editor(
                            'save_all_button',
                            'dialog-ok-apply-5',
                            tooltip='Toggle "save" for all positions')),
                    UItem('positions', editor=editor, height=0.28))))
        return v
Пример #10
0
image_table_editor = TableEditor(
    columns = [
        ImageColumn( label = 'Image',      width = 42,
                     auto_editable = True, view  = image_view,
                     horizontal_alignment = 'center' ),
        VolumeColumn(   name = 'volume',      width = 0.10 ),
        NameColumn(     name = 'name',        width = 0.10 ),
        #LibraryColumn(  name = 'image_name',  width = 0.15,
        #                label = 'Image Name' ),
        LibraryColumn(  name = 'width',       width = 0.075,
                        horizontal_alignment = 'center' ),
        LibraryColumn(  name = 'height',      width = 0.075,
                        horizontal_alignment = 'center' ),
        LibraryColumn(  name = 'category',    width = 0.10,
                        horizontal_alignment = 'center' ),
        KeywordsColumn( name = 'keywords',    width = 0.10 ),
        TextColumn(     name = 'description', width = 0.10,
                        auto_editable = True, view  = description_view ),
        TextColumn(     name = 'copyright',   width = 0.10,
                        auto_editable = True, view  = copyright_view ),
        TextColumn(     name = 'license',     width = 0.10,
                        auto_editable = True, view  = license_view ),
    ],
    auto_size           = False,
    editable            = False,
    edit_on_first_click = False,
    show_toolbar        = False,
    filter_name         = 'filter',
    filtered_indices    = 'filtered_indices',
    selection_bg_color  = 0xFBD391,
    selection_color     = 'black',
    selection_mode      = 'rows',
    selected            = 'selected_images'
)
Пример #11
0
#-------------------------------------------------------------------------

people = [['Dave', 39, '555-1212'], ['Mike', 28, '555-3526'],
          ['Joe', 34, '555-6943'], ['Tom', 22, '555-7586'],
          ['Dick', 63, '555-3895'], ['Harry', 46, '555-3285'],
          ['Sally', 43, '555-8797'], ['Fields', 31, '555-3547']]

#-------------------------------------------------------------------------
#  Table editor definition:
#-------------------------------------------------------------------------

table_editor = TableEditor(
    columns=[
        ListColumn(index=0, label='Name'),
        ListColumn(index=1, label='Age'),
        ListColumn(index=2, label='Phone')
    ],
    editable=False,
    show_column_labels=True,  #
)

#-------------------------------------------------------------------------
#  'TableTest' class:
#-------------------------------------------------------------------------


class TableTest(HasStrictTraits):

    #-------------------------------------------------------------------------
    #  Trait definitions:
    #-------------------------------------------------------------------------
    def get_drag_value(self, object):
        return object.full_name


table_editor = TableEditor(columns=[
    MatchesColumn1(name='matches',
                   label='#',
                   editable=False,
                   width=0.05,
                   horizontal_alignment='center'),
    MatchesColumn2(name='matches',
                   width=0.35,
                   format_func=lambda x: (x + [''])[0].strip(),
                   editor=CodeEditor(
                       line='object.live_search.selected_match',
                       selected_line='object.live_search.selected_match'),
                   style='readonly',
                   edit_width=0.95,
                   edit_height=0.33),
    FileColumn(name='base_name', label='Name', width=0.30, editable=False),
    ObjectColumn(name='ext_path', label='Path', width=0.30, editable=False),
],
                           filter_name='filter',
                           auto_size=False,
                           show_toolbar=False,
                           selected='selected',
                           selection_color=0x000000,
                           selection_bg_color=0xFBD391)

#-- LiveSearch class -----------------------------------------------------

Пример #13
0
        self.cell_color = ( min( 255, int( 63.75 * (depth - 1) ) ),
                            max(   0, int( 63.75 * (5 - depth) ) ),
                            0 )

        return self.cell_color_

events_table_editor = TableEditor(
    columns = [
        ObjectColumn( name = 'class_name', width = 0.15,  editable = False ),
        ObjectColumn( name = 'id',         width = 0.15,  editable = False,
                      label = 'Object Id', format = '%08X' ),
        ObjectColumn( name = 'name',       width = 0.15,  editable = False ),
        ValueColumn(  name = 'old',        width = 0.175, editable = False ),
        ValueColumn(  name = 'new',        width = 0.175, editable = False ),
        DepthColumn(  name = 'depth',      width = 0.05,  editable = False,
                      horizontal_alignment = 'center' ),
        ObjectColumn( name = 'timestamp',  width = 0.15,  editable = False,
                      format = '%.3f', horizontal_alignment = 'right' )
    ],
    show_toolbar       = False,
    editable           = False,
    auto_size          = False,
    selection_bg_color = 0xFBD391,
    selection_color    = 'black'
)

#-------------------------------------------------------------------------------
#  'NotificationEvent' class:
#-------------------------------------------------------------------------------

class NotificationEvent ( HasPrivateTraits ):
Пример #14
0
class DatasetEditor(HasTraits):
    datasets = List(DatasetUI)
    selected = List(DatasetUI)

    color = Color
    active = Bool(True)
    highlighted = Bool(False)
    marker_size = Float(1.0)
    line_width = Float(1.0)

    table_click = Event

    dataset_editor = TableEditor(auto_size=True,
                                 selection_mode='rows',
                                 sortable=False,
                                 configurable=False,
                                 editable=True,
                                 edit_on_first_click=False,
                                 cell_bg_color='white',
                                 label_bg_color=(232, 232, 232),
                                 selection_bg_color=(232, 232, 232),
                                 columns=[
                                     DatasetColumn(name='name',
                                                   cell_color='white',
                                                   editable=False,
                                                   width=0.9),
                                     ColorColumn(name='color'),
                                     CheckboxColumn(name='active'),
                                     CheckboxColumn(name='highlighted'),
                                     DatasetColumn(name='marker_size'),
                                     DatasetColumn(name='line_width'),
                                 ])

    traits_view = View(VGroup(
        HGroup(Item('datasets', editor=dataset_editor, show_label=False)),
        VGroup(
            Label('Modify all selected items:'),
            VGroup(Item('color', editor=ColorEditor()),
                   Item('active'),
                   Item('highlighted'),
                   Item('marker_size'),
                   Item('line_width'),
                   springy=True),
        ),
    ),
                       resizable=True,
                       width=0.5,
                       height=0.5,
                       kind='livemodal',
                       title='Edit datasets')

    def __init__(self, *args, **kwargs):
        self.datasets = map(lambda d: d.metadata['ui'], kwargs.pop('datasets'))
        super(DatasetEditor, self).__init__(*args, **kwargs)
        self.dataset_editor.on_select = self._selection_changed
        self.selecting = False

    def _selection_changed(self, selected_objs):
        self.selected = selected_objs
        self._update_ui()

    def _table_click_changed(self, trait, value):
        self._update_ui()

    def _update_ui(self):
        if not self.selected:
            return
        self.selecting = True
        # If the colors are all the same
        if all(map(lambda o: o.color != None, self.selected)) and \
            len(set(map(lambda o: tuple(o.color), self.selected))) == 1:
            self.color = self.selected[0].color
        else:
            # This makes sure 'custom' is displayed
            self.color = (1, 2, 3, 4)
        self.active = self.selected[0].active
        self.highlighted = self.selected[0].highlighted
        self.marker_size = self.selected[0].marker_size
        self.line_width = self.selected[0].line_width
        self.selecting = False

    @on_trait_change('active, color, highlighted, marker_size, line_width')
    def _trait_changed(self, trait, value):
        if not self.selecting:
            for obj in self.selected:
                setattr(obj, trait, value)
Пример #15
0
class ListItem(HasTraits):
    """ Items to visualize in a table editor """
    value = Str
    other_value = Int


class ObjectList(HasTraits):
    values = List(Instance(ListItem))


simple_view = View(
    Item('values',
         show_label=False,
         editor=TableEditor(columns=[
             ObjectColumn(name='value'),
             ObjectColumn(name='other_value'),
         ], )),
    buttons=['OK'],
)


@skip_if_null
def test_table_editor():
    gui = GUI()
    object_list = ObjectList(
        values=[ListItem(value=str(i**2)) for i in range(10)])

    with store_exceptions_on_all_threads():
        ui = object_list.edit_traits(view=simple_view)
        gui.process_events()
        press_ok_button(ui)
Пример #16
0
class ExperimentDialogModel(HasTraits):
    """
    The model for the Experiment setup dialog.
    """

    # TODO - there's some bug here with categorical things

    # the tubes.  this is the model; the rest is for communicating with the View
    tubes = List(Tube)

    # the tubes' traits.
    tube_traits = Dict(Str, TraitType)

    # a collections.Counter that keeps track of duplicates for us.  rebuilt
    # whenever the Tube elements of self.tubes changes
    tubes_counter = Property(depends_on='tubes[]')

    # traits to communicate with the TabularEditor
    update = Bool
    refresh = Bool
    selected = List

    view = View(Group(Item(name='tubes',
                           id='table',
                           editor=TableEditor(
                               editable=True,
                               sortable=True,
                               auto_size=True,
                               configurable=False,
                               selection_mode='cells',
                               selected='selected',
                               columns=[
                                   ExperimentColumn(name='Source',
                                                    editable=False),
                                   ExperimentColumn(name='Tube',
                                                    editable=False)
                               ],
                           ),
                           enabled_when="object.tubes"),
                      show_labels=False),
                title='Experiment Setup',
                id='edu.mit.synbio.experiment_table_editor',
                width=0.60,
                height=0.75,
                resizable=True)

    def init_model(self, op):

        # I DON'T KNOW WHY THIS STICKS AROUND ACROSS DIALOG INVOCATIONS.
        del self.tubes[:]

        dtype_to_trait = {
            "category": Str,
            "float": Float,
            "log": LogFloat,
            "bool": Bool,
            "int": Int
        }

        has_row = any(tube.row for tube in op.tubes)
        has_col = any(tube.col for tube in op.tubes)

        for op_tube in op.tubes:
            tube = Tube(Source=op_tube.source,
                        Tube=op_tube.tube,
                        _file=op_tube.file,
                        _parent=self)
            if has_row:
                tube.add_trait("Row", Str)
                tube.Row = op_tube.row
                if not "Row" in self.tube_traits:
                    self.tube_traits["Row"] = Str()
            if has_col:
                tube.add_trait("Col", Str)
                tube.Col = op_tube.col
                if not "Col" in self.tube_traits:
                    self.tube_traits["Col"] = Str()

            for condition in op_tube.conditions:
                condition_dtype = op.conditions[condition]
                condition_trait = \
                    dtype_to_trait[condition_dtype](condition = True)
                tube.add_trait(condition, condition_trait)
                if not condition in self.tube_traits:
                    self.tube_traits[condition] = condition_trait
            tube.trait_set(**op_tube.conditions)

            self.tubes.append(tube)

    def update_import_op(self, op):
        trait_to_dtype = {
            "Str": "category",
            "Float": "float",
            "LogFloat": "log",
            "Bool": "bool",
            "Int": "int"
        }

        op.conditions.clear()

        for trait_name, trait in self.tube_traits.items():
            if not trait.condition:
                continue

            trait_type = trait.__class__.__name__
            op.conditions[trait_name] = trait_to_dtype[trait_type]

        for tube in self.tubes:
            op_tube = CytoflowTube(source=tube.Source,
                                   tube=tube.Tube,
                                   file=tube._file)

            if "Row" in tube.trait_names():
                op_tube.row = tube.Row

            if "Col" in tube.trait_names():
                op_tube.col = tube.Col

            op_tube.conditions = tube.trait_get(condition=True)

            # AFAICT this is going to cause the op to reload THE ENTIRE
            # SET each time a tube is added.  >.>

            # TODO - FIX THIS.  need a general strategy for only updating
            # if there's a "pause" in the action.
            op.tubes.append(op_tube)

    ## i'd love to cache this, but it screws up the coloring stuff  :-/
    def _get_tubes_counter(self):
        return Counter(self.tubes)
        setattr(object, self.name, getattr(object, self.name) - 1)


# The 'players' trait table editor:
player_editor = TableEditor(
    editable=True,
    sortable=False,
    auto_size=False,
    columns=[
        ObjectColumn(name='name', editable=False, width=0.28),
        AffectsAverageColumn(name='at_bats', label='AB'),
        AffectsAverageColumn(name='strike_outs', label='SO'),
        AffectsAverageColumn(name='singles', label='S'),
        AffectsAverageColumn(name='doubles', label='D'),
        AffectsAverageColumn(name='triples', label='T'),
        AffectsAverageColumn(name='home_runs', label='HR'),
        AffectsAverageColumn(name='walks', label='W'),
        ObjectColumn(
            name='average',
            label='Ave',
            editable=False,
            width=0.09,
            horizontal_alignment='center',
            format='%0.3f'
        )
    ]
)


# 'Player' class:
class Player(HasStrictTraits):
Пример #18
0
                if i != j:
                    result.append(Integer(n=j))
            i += 1

        result.sort(key=attrgetter('n'))

        return result

#-- The table editor used for the pop-up view ----------------------------

factor_table_editor = TableEditor(
    columns=[
        ObjectColumn(name='n',
                     width=1.0,
                     editable=False,
                     horizontal_alignment='center')
    ],
    sortable=False,
    auto_size=False,
    show_toolbar=False,
    show_column_labels=False
)

#-- The table editor used for the main view ------------------------------

factors_view = View(
    Item('factors',
         id='factors',
         show_label=False,
         editor=factor_table_editor
         ),
    id='traits.examples.demo.Advanced.factors_view',
Пример #19
0
 def dynamic_view(self):
     return View(
         Item('electrodes',
              editor=TableEditor(
                  columns=[
                      ObjectColumn(label='electrode',
                                   editor=TextEditor(),
                                   style='readonly',
                                   editable=False,
                                   name='default_repr'),
                      ObjectColumn(
                          label='corner',
                          editor=CheckListEditor(values=[
                              '', 'corner 1', 'corner 2', 'corner 3'
                          ]),
                          style='simple',
                          name='corner'),
                      ObjectColumn(label='geometry',
                                   editor=CSVListEditor(),
                                   name='geom_coords'),
                      ObjectColumn(label='channel name',
                                   editor=TextEditor(),
                                   name='name'),
                      ObjectColumn(label='ROIs',
                                   editor=ListStrEditor(),
                                   editable=False,
                                   name='roi_list'),
                      ObjectColumn(label='RAS',
                                   editor=TextEditor(),
                                   style='readonly',
                                   editable=False,
                                   name='ras_repr'),
                      ObjectColumn(label='iso',
                                   editor=TextEditor(),
                                   style='readonly',
                                   editable=False,
                                   name='iso_repr'),
                      ObjectColumn(label='snap',
                                   editor=TextEditor(),
                                   style='readonly',
                                   editable=False,
                                   name='postsnap_repr'),
                  ],
                  selected='cur_sel',
                  deletable=True,
                  row_factory=self.electrode_factory,
              ),
              show_label=False,
              height=350,
              width=700),
         HGroup(
             VGroup(
                 Label('Automatic labeling parameters'),
                 HGroup(
                     Item('name_stem'),
                     Item('naming_convention'),
                     Item('include_underscore'),
                     Item('grid_type'),
                 ),
                 HGroup(
                     Item('labeling_delta'),
                     Item('labeling_rho'),
                     Item('labeling_epsilon'),
                 ),
             ),
             #VGroup(
             #    Label( 'ROI identification parameters' ),
             #    Item('parcellation'),
             #    Item('error_radius'),
             #),
             #VGroup(
             #    Label('Image parameters' ),
             #    Item('img_dpi', label='dpi'),
             #    Item('img_size', label='size', editor=CSVListEditor()),
             #),
         ),
         resizable=True,
         kind='panel',
         title='modify electrodes',
         #buttons=[OKButton, swap_action, label_auto_action,
         #    interpolate_action, save_montage_action, find_rois_action])
         buttons=[self.label_auto_action, self.swap_action, OKButton],
         menubar=MenuBar(
             Menu(
                 self.label_auto_action,
                 self.label_manually_action,
                 self.rotate_grid_left_action,
                 self.rotate_grid_right_action,
                 self.rotate_grid_180_action,
                 self.reflect_grid_action,
                 name='Labeling',
             ),
             Menu(
                 self.add_blank_action,
                 self.interpolate_action,
                 self.find_rois_action,
                 self.find_all_rois_action,
                 self.manual_reposition_action,
                 name='Operations',
             ),
             Menu(
                 self.save_montage_action,
                 self.save_csv_action,
                 self.save_coronal_slice_action,
                 name='Save Output',
             ),
         ))
Пример #20
0
    VSplit, \
    View, UItem, Item, TableEditor, VGroup

from .i_bcond import \
    IBCond
from traitsui.table_column \
    import ObjectColumn
from ibvpy.view.plot2d import Vis2D
from ibvpy.view.ui import BMCSTreeNode

from .bc_dof import BCDof

bcond_list_editor = TableEditor(
    columns=[
        ObjectColumn(label='Type', name='var'),
        ObjectColumn(label='Value', name='value'),
        ObjectColumn(label='DOF', name='dof')
    ],
    editable=False,
)


@provides(IBCond)
class BCDofList(BMCSTreeNode, Vis2D):
    '''
    Implements the IBC functionality for a constrained dof.
    '''
    tree_node_list = List

    tree_node_list = Property(depends_on='bcdof_list,bcdof_list_items')

    @cached_property
Пример #21
0
 def _get_table_editor(self):
     cols = self._get_table_columns()
     table_editor = TableEditor(columns=cols,
                                selected='_selected',
                                selection_mode='row')
     return table_editor
Пример #22
0
    def build_plot_list_editor(self):
        """ Build a table editor for the model's list of PlotDescriptors.
        """
        num_containers = self.model.canvas_manager.num_container_managers
        container_idx_vals = list(
            range(num_containers)) + [CONTAINER_IDX_REMOVAL]

        name_to_col = {
            "id":
            ObjectColumn(name='id', style="readonly", cell_color="lightgrey"),
            "plot_title":
            ObjectColumn(name="plot_title"),
            # The format_func is called with an argument, the object to
            # display, therefore the x argument placeholder:
            'edit_plot_style':
            ObjectColumn(name='edit_plot_style',
                         label="Edit Style",
                         format_func=lambda x: "Edit"),
            "visible":
            CheckboxColumn(name='visible'),
            "frozen":
            CheckboxColumn(name='frozen',
                           tooltip="Freeze the plot and skip updates when "
                           "source data changes"),
            "plot_type":
            ObjectColumn(name='plot_type',
                         style="readonly",
                         cell_color="lightgrey"),
            "x_col_name":
            ObjectColumn(name='x_col_name',
                         style="readonly",
                         cell_color="lightgrey",
                         label="X column"),
            'x_axis_title':
            ObjectColumn(name='x_axis_title'),
            "y_col_name":
            ObjectColumn(name='y_col_name',
                         style="readonly",
                         cell_color="lightgrey",
                         label="Y column"),
            'y_axis_title':
            ObjectColumn(name='y_axis_title'),
            'secondary_y_axis_title':
            ObjectColumn(name='secondary_y_axis_title',
                         label="Second. Y title"),
            "z_col_name":
            ObjectColumn(name='z_col_name',
                         style="readonly",
                         cell_color="lightgrey",
                         label="Z column (color)"),
            'z_axis_title':
            ObjectColumn(name='z_axis_title'),
            "data_filter":
            ObjectColumn(name='data_filter',
                         label="Analyzer data filter",
                         style="readonly"),
            'container_idx':
            ObjectColumn(name='container_idx',
                         editor=EnumEditor(values=container_idx_vals),
                         label="Move/Delete")
        }

        columns = [name_to_col[col] for col in self.plot_control_cols]

        plot_list_editor = TableEditor(columns=columns,
                                       auto_size=True,
                                       sortable=True,
                                       h_size_policy="expanding",
                                       editable=True,
                                       edit_on_first_click=False,
                                       reorderable=False,
                                       row_factory=None,
                                       deletable=False)
        return plot_list_editor
Пример #23
0

class Company(HasTraits):

    employees = List(Employee)


############################################################################
# Views and Editors
############################################################################

employees_editor = TableEditor(
    columns=[
        ObjectColumn(name='retired', label='Retired'),
        ObjectColumn(name='first_name', label='First'),
        ObjectColumn(name='last_name', label='Last'),
        ObjectColumn(name='gender', label='Gender'),
    ],
    configurable=False,  # removes table buttons
    sortable=False,  # removes buttons
)

view = View(
    Group(
        Item('employees', show_label=False, editor=employees_editor),
        show_border=True,
        label="Employees",
    ),
    resizable=True,
    width=400,
    height=600,
)
Пример #24
0
class Optimizer(HasTraits):

    context = Instance(ParametricContext)
    block = Instance(Block)
    objective_var = Str
#    constraint_vars = List(ConstraintOptimizationVariable)
    constraint_var = Str
    input_vars = List(InputOptimizationVariable)
    _working_context = Instance(DataContext)

    inputs_table_editor = TableEditor(columns=[ObjectColumn(name='name'),
                                               ObjectColumn(name='min'),
                                               ObjectColumn(name='max')],
                                      editable=True,
                                      deletable=True,
                                      row_factory=InputOptimizationVariable,
                                      )
    traits_view = View(Item('objective_var'),
                       Item('constraint_var',),
                       Item('input_vars', editor=inputs_table_editor),
                       buttons=['OK', 'Cancel'],
                       close_result=False,
                       width=500,
                       height=500,
                       resizable=True
                       )
    def optimize(self):
        input_var_names = [var_obj.name for var_obj in self.input_vars]

        # FIXME: Do we want to create shadows with multiple names?
        self._working_context = self.context.create_shadow(input_var_names[0])
        for var_name in input_var_names:
            self._working_context[var_name] = self.context[var_name][:]
        sub_block = self.block.restrict(inputs=input_var_names,
                                        outputs=[self.objective_var, self.constraint_var])
        input_len = len(self._working_context[input_var_names[0]])
        cobyla_instances = [COBYLAInstance(index=i, optimizer=self) for \
                            i in range(input_len)]
        greenlet_list = [greenlet(cobyla_instance.minimize_at_index) for \
                         cobyla_instance in cobyla_instances]
        self.cobyla_status_arr = zeros(input_len, dtype=bool)
        active_greenlets = input_len
        while active_greenlets > 0:
            active_greenlets = 0
            for greenlet_inst in greenlet_list:
                if not greenlet_inst.dead:
                    active_greenlets += 1
                    greenlet_inst.switch()
            sub_block.execute(self._working_context)

        self.context['plot_index'] = arange(input_len)
        input_plots = [PlotConfig(number=plot_num, x = 'plot_index', y=var_name, type='Line') for \
                       plot_num, var_name in enumerate(input_var_names)]


        plot_configs = input_plots + [
                        PlotConfig(number=len(input_var_names), x='plot_index', y=self.objective_var, type='Line'),
                        PlotConfig(number=len(input_var_names) + 1, x='plot_index', y=self.constraint_var, type='Line'),]

        result_view = View(Item('context',
                                editor=ContextPlotEditor(#view_shadows=True,
                                                         plot_configs=plot_configs,
                                                         ),
                                show_label=False),
                            width=500,
                            height=500,
                            resizable=True)
        self.edit_traits(view=result_view, kind='modal')

        return
Пример #25
0
    """Filter model with adaptive menu. Menu can build transfer functions."""

    filt_type = Enum('butterworth', available_filters)
    filt_menu = Instance(HasTraits)

    view = View(VGroup(
        Item('filt_type', label='Filter type'),
        Group(UItem('filt_menu', style='custom'), label='Filter menu')),
                handler=FilterHandler,
                resizable=True)


filter_table = TableEditor(columns=[ObjectColumn(name='filt_type')],
                           deletable=True,
                           auto_size=True,
                           show_toolbar=True,
                           reorderable=True,
                           edit_view=None,
                           row_factory=Filter,
                           selected='selected')


def pipeline_factory(f_list,
                     filter_modes,
                     output_file=None,
                     data_field='data'):
    # TODO: if f_list is empty, is it consistent not to create an output file?
    if not len(f_list):
        return lambda x: x

    def get_x_props(x):
        if isinstance(x, (list, tuple)):
Пример #26
0
    selected_cells = List(Tuple(Instance(ListItem), Str))
    selected_cell_index = Tuple(Int, Int)
    selected_cell_indices = List(Tuple(Int, Int))


class ObjectList(HasTraits):
    values = List(Instance(ListItem))


simple_view = View(
    Item(
        'values',
        show_label=False,
        editor=TableEditor(
            columns=[
                ObjectColumn(name='value'),
                ObjectColumn(name='other_value'),
            ],
        )
    ),
    buttons=['OK'],
)

filtered_view = View(
    Item(
        'values',
        show_label=False,
        editor=TableEditor(
            columns=[
                ObjectColumn(name='value'),
                ObjectColumn(name='other_value'),
            ],
Пример #27
0
    # 'ApplicationModel' interface.
    ###########################################################################

    #### Trait initializers ###################################################

    def _plugin_models_default(self):
        """ Trait initializer. """

        return [PluginModel(plugin=plugin) for plugin in self.application]


extension_point_table_editor = TableEditor(
    columns=[
        ObjectColumn(name='id'),
        #ObjectColumn(name='desc')
    ],

    #   selected = 'extension_point_selected',
    editable=True,
    edit_view=View(Item(name='desc', show_label=False), style='custom'))

plugin_browser_view = View(VGroup(Item(name='id'),
                                  Item(name='name'),
                                  label='General'),
                           VGroup(
                               Item(name='extension_points',
                                    editor=extension_point_table_editor,
                                    show_label=False),
                               label='Extension Points',
                           ),
                           width=.8,
Пример #28
0
def template ( method, profile ):
    def %(method_name)s ( %(args)s, **kw ):
        return profile( method, %(args)s, **kw )
    return %(method_name)s
handler = template( method, profile )
"""

#-------------------------------------------------------------------------------
#  Profiler table editor definition:
#-------------------------------------------------------------------------------

profiler_table_editor = TableEditor(columns=[
    ObjectColumn(name='package_name', label='Package', editable=False),
    ObjectColumn(name='module_name', label='Module', editable=False),
    ObjectColumn(name='class_name', label='Class', editable=False),
    ObjectColumn(name='method_name', label='Method', editable=False)
],
                                    auto_size=False,
                                    selection_bg_color=0xFBD391,
                                    selection_color='black',
                                    deletable=True)

#-------------------------------------------------------------------------------
#  'Profiler' plugin:
#-------------------------------------------------------------------------------


class Profiler(HasPrivateTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------
Пример #29
0
   Person( name = 'Sally',  age = 43, phone = '555-8797' ),
   Person( name = 'Fields', age = 31, phone = '555-3547' )
]

#-------------------------------------------------------------------------------
#  Table editor definition:
#-------------------------------------------------------------------------------

filters      = [ EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate ]

table_editor = TableEditor(
    columns     = [ ObjectColumn( name = 'name' ),
                    ObjectColumn( name = 'age' ),
                    ObjectColumn( name = 'phone' ) ],
    editable    = True,
    deletable   = True,
    sortable    = True,
    sort_model  = True,
    filters     = filters,
    search      = RuleTableFilter(),
    row_factory = Person
)

#-------------------------------------------------------------------------------
#  'ListTraitTest' class:
#-------------------------------------------------------------------------------

class ListTraitTest ( HasStrictTraits ):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------
Пример #30
0
                          ObjectColumn)
from matplotlib.figure import Figure
from scpy2.traits import MPLFigureEditor


###1###
class Point(HasTraits):
    x = Float()
    y = Float()


point_table_editor = TableEditor(columns=[
    ObjectColumn(name='x', width=100, format="%g"),
    ObjectColumn(name='y', width=100, format="%g")
],
                                 editable=True,
                                 sortable=False,
                                 sort_model=False,
                                 auto_size=False,
                                 row_factory=Point)


###1###
###2###
class FunctionPlotter(HasTraits):
    figure = Instance(Figure, ())  #❶
    code = Code()  #❷
    points = List(Instance(Point), [])  #❸
    draw_button = Button("Plot")

    view = View(
Пример #31
0
    selected_cell = Tuple(Instance(ListItem), Str)
    selected_cells = List(Tuple(Instance(ListItem), Str))
    selected_cell_index = Tuple(Int, Int)
    selected_cell_indices = List(Tuple(Int, Int))


class ObjectList(HasTraits):
    values = List(Instance(ListItem))


simple_view = View(
    Item(
        "values",
        show_label=False,
        editor=TableEditor(columns=[
            ObjectColumn(name="value"),
            ObjectColumn(name="other_value"),
        ]),
    ),
    buttons=["OK"],
)

filtered_view = View(
    Item(
        "values",
        show_label=False,
        editor=TableEditor(
            sortable=False,
            columns=[
                ObjectColumn(name="value"),
                ObjectColumn(name="other_value"),
            ],