Beispiel #1
0
class Network(BaseNetwork):

    name = Str

    nodes = List(Node)

    edges = List(Edge)

    def __init__(self, name):

        self.name = name

    def add_node(self, n, **attr):
        """ How to store bidir node names?
        Add a dictionary and/or a list of parameters
        """

        a = Node(n)
        # create Traits attribute for dict

        a.attr.trait_set(**attr)
        #for k,v in attr.items():
        #    a.attr.add_trait(k, v)

        self.nodes.append(a)
Beispiel #2
0
class ToolkitEditorFactory(EditorFactory):
    """ Editor factory for graph editors.
    """
    #--------------------------------------------------------------------------
    #  Trait definitions:
    #--------------------------------------------------------------------------

    canvas = Instance(GraphCanvas)

    # Graph node definitions.
    nodes = List(Instance(GraphNode))

    # Graph edge definitions.
    edges = List(Instance(GraphEdge))

    # Called when a graph element is selected.
    on_select = Callable

    #--------------------------------------------------------------------------
    #  Property getters:
    #--------------------------------------------------------------------------

    def _get_simple_editor_class(self):
        """ Returns the editor class to use for "simple" style views.
        """
        return SimpleGraphEditor
Beispiel #3
0
class PupilGenerator(HasTraits):
    wavelength = Float(700)
    NA = Float(1.49)
    n = Float(1.51)
    pupilSizeX = Int(61)
    pixelSize = Float(70)

    pupils = List(_pupils)

    aberations = List(ZernikeMode, value=[ZernikeMode(i) for i in range(25)])

    basePupil = Instance(Pupil, _getDefaultPupil)

    pupil = None

    view = View(Item(
        'basePupil',
        label='Pupil source',
        editor=InstanceEditor(name='pupils', editable=True),
    ),
                Item('_'),
                Item('wavelength'),
                Item('n'),
                Item('NA'),
                Item('pupilSizeX'),
                Item('pixelSize'),
                Item('_'),
                Item('aberations'),
                buttons=[OKButton])

    def GetPupil(self):
        u, v, R, pupil = self.basePupil.GeneratePupil(self.pixelSize,
                                                      self.pupilSizeX,
                                                      self.wavelength, self.NA,
                                                      self.n)
Beispiel #4
0
class Equalizer(HasTraits):
    freq = Range(10.0, SAMPLING_RATE / 2, 1000)
    Q = Range(0.1, 10.0, 1.0)
    gain = Range(-24.0, 24.0, 0)

    a = List(Float, [1.0, 0.0, 0.0])
    b = List(Float, [1.0, 0.0, 0.0])

    h = Array(dtype=np.complex, transient=True)

    def __init__(self):
        super(Equalizer, self).__init__()
        self.design_parameter()

    @on_trait_change("freq,Q,gain")
    def design_parameter(self):
        '''设计系数并计算频率响应'''
        try:
            self.b, self.a = design_equalizer(self.freq, self.Q, self.gain,
                                              SAMPLING_RATE)
        except:
            self.b, self.a = [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]
        self.h = myfreqz(self.b, self.a, W)

    def export_parameters(self, f):
        '''输出滤波器系数为C语言数组'''
        tmp = self.b[0], self.b[1], self.b[2], self.a[1], self.a[
            2], self.freq, self.Q, self.gain
        f.write("{%s,%s,%s,%s,%s}, // %s,%s,%s\n" % tmp)
class CheckListTest ( Handler ):
    
    #---------------------------------------------------------------------------
    #  Trait definitions:  
    #---------------------------------------------------------------------------
    
    value       = List( editor = CheckListEditor( name = 'values', cols = 5 ) )
    values      = List( Str )
    values_text = Str( 'red orange yellow green blue indigo violet' )
    
    #---------------------------------------------------------------------------
    #  Traits view definitions:  
    #---------------------------------------------------------------------------
        
    simple_view = View( 'value',  'values_text@' )
    custom_view = View( 'value@', 'values_text@' )
                        
    #---------------------------------------------------------------------------
    #  'Initializes the object:  
    #---------------------------------------------------------------------------
                               
    def __init__ ( self, **traits ):
        super( CheckListTest, self ).__init__( **traits )
        self._values_text_changed()
    
    #---------------------------------------------------------------------------
    #  Event handlers:  
    #---------------------------------------------------------------------------
        
    def _values_text_changed ( self ):
        self.values = self.values_text.split()
Beispiel #6
0
class MultiSelect ( HasPrivateTraits ):
    
    choices  = List( Str )
    selected = List( Str )
    
    view = View(
        HGroup(
            Item( 'choices',
                  show_label = False,
                  editor     = TabularEditor(
                                   show_titles  = False,
                                   selected     = 'selected',
                                   editable     = False,
                                   multi_select = True,
                                   adapter      = MultiSelectAdapter() )
            ),
            Item( 'selected',
                  show_label = False,
                  editor     = TabularEditor(
                                   show_titles  = False,
                                   editable     = False,
                                   adapter      = MultiSelectAdapter() )
            )
        )
    )
Beispiel #7
0
class Patient(HasTraits):
    studies = List(Study)
    dicom_datasets = List(PythonValue)

    patient_id = Str
    name = Str

    label = Property(depends_on=['dicom_dataset'])

    def _get_label(self):
        return "%s <%s>" % (self.name, self.patient_id)

    @on_trait_change("dicom_datasets[]")
    def update_studies(self, obj, name, old, new):
        print "Patient.update_studies()"
        studyuids = defaultdict(lambda: [])
        for x in self.dicom_datasets:
            studyuids[x.StudyInstanceUID].append(x)
        sd = {x.study_instance_uid: x for x in self.studies}
        newuids = [uid for uid in studyuids if uid not in sd]
        goneuids = [uid for uid in sd if uid not in studyuids]
        updateduids = [uid for uid in sd if uid in studyuids]
        for uid in newuids:
            self.studies.append(
                Study(dicom_datasets=studyuids[uid],
                      patient=self,
                      study_instance_uid=uid))
        for uid in goneuids:
            self.studies.pop(sd[uid])
        for uid in updateduids:
            sd[uid].dicom_datasets = studyuids[uid]
Beispiel #8
0
class Series(HasTraits):
    sopinstances = List(SOPInstance)
    # study = Instance(Study)
    dicom_datasets = List(PythonValue)

    series_instance_uid = Str

    label = Property(depends_on=['dicom_dataset'])

    def _get_label(self):
        return "Series %s [%s]" % (self.dicom_datasets[0].Modality,
                                   self.series_instance_uid)

    @on_trait_change("dicom_datasets[]")
    def update_sopinstances(self, obj, name, old, new):
        print "Series.update_sopinstances()"
        sopuids = defaultdict(lambda: [])
        for x in self.dicom_datasets:
            sopuids[x.SOPInstanceUID].append(x)
        sd = {x.sopinstanceuid: x for x in self.sopinstances}
        newuids = [uid for uid in sopuids if uid not in sd]
        goneuids = [uid for uid in sd if uid not in sopuids]
        for uid in newuids:
            assert len(sopuids[uid]) == 1
            cls = specialsops[sopuids[uid][0].SOPClassUID]
            print "building %s" % (cls, )
            self.sopinstances.append(
                cls(dicom_dataset=sopuids[uid][0], series=self))
        for uid in goneuids:
            self.sopinstances.pop(sd[uid])
Beispiel #9
0
class IUserManager(Interface):
    """The interface implemented by a user manager to manage users."""

    # The list of PyFace management actions (ie. actions related to all users)
    # implemented by this user manager.
    management_actions = List(Instance(Action))

    # The current user.
    user = Instance(IUser)

    # The list of PyFace user actions (ie. actions related to the current user)
    # implemented by this user manager.
    user_actions = List(Instance(Action))

    # This is fired whenever the currently authenticated user changes.  It will
    # be None if the current user isn't authenticated.
    user_authenticated = Event(IUser)

    def bootstrapping(self):
        """Return True if the user manager is bootstrapping.  Typically this is
        when no users have been defined."""

    def authenticate_user(self):
        """Authenticate (ie. login) the user.  If successfully authenticated
        all secured objects are re-enabled according to the user's permissions.
        """

    def unauthenticate_user(self):
        """Unauthenticate (ie. logout) the user.  All secured objects are
        disabled."""

    def select_user(self, name):
        """Return an object that implements IUser for the user selected based
Beispiel #10
0
class MultiSelect(HasPrivateTraits):
    """ This class demonstrates using the StringListEditor to select a set
        of string values from a set of choices.
    """

    # The list of choices to select from:
    choices = List(Str)

    # The currently selected list of choices:
    selected = List(Str)

    # A dummy result so that we can display the selection using the same
    # StringListEditor:
    result = List(Str)

    # A traits view showing the list of choices on the left-hand side, and
    # the currently selected choices on the right-hand side:
    view = View(HGroup(
        Item('selected',
             show_label=False,
             editor=StringListEditor(choices='choices')),
        Item('result',
             show_label=False,
             editor=StringListEditor(choices='selected'))),
                width=0.20,
                height=0.25)
Beispiel #11
0
class _StringListEditor(UIEditor):

    # Indicate that the editor is scrollable/resizable:
    scrollable = True

    # The list of available editor choices:
    choices = List(Str)

    # The list of currently selected items:
    selected = List(Str)

    # The traits UI view used by the editor:
    view = View(Item('choices',
                     show_label=False,
                     editor=TabularEditor(show_titles=False,
                                          selected='selected',
                                          editable=False,
                                          multi_select=True,
                                          adapter=MultiSelectAdapter())),
                id='string_list_editor',
                resizable=True)

    def init_ui(self, parent):

        self.sync_value(self.factory.choices, 'choices', 'from', is_list=True)
        self.selected = self.value

        return self.edit_traits(parent=parent, kind='subpanel')

    @on_trait_change(' selected')
    def _selected_modified(self):
        self.value = self.selected
Beispiel #12
0
class Study(HasTraits):
    series = List(Series)
    # patient = Instance(Patient)
    dicom_datasets = List(PythonValue)
    study_instance_uid = Str

    label = Property(depends_on=['dicom_dataset'])

    def _get_label(self):
        return "Study %s [%s]" % (self.dicom_datasets[0].StudyID,
                                  self.study_instance_uid)

    @on_trait_change("dicom_datasets[]")
    def update_series(self, obj, name, old, new):
        print "Study.update_series()"
        seriesuids = defaultdict(lambda: [])
        for x in self.dicom_datasets:
            seriesuids[x.SeriesInstanceUID].append(x)
        sd = {x.series_instance_uid: x for x in self.series}
        newuids = [uid for uid in seriesuids if uid not in sd]
        goneuids = [uid for uid in sd if uid not in seriesuids]
        updateduids = [uid for uid in sd if uid in seriesuids]
        for uid in newuids:
            self.series.append(
                Series(dicom_datasets=seriesuids[uid],
                       study=self,
                       series_instance_uid=uid))
        for uid in goneuids:
            self.series.pop(sd[uid])
        for uid in updateduids:
            sd[uid].dicom_datasets = seriesuids[uid]
Beispiel #13
0
class ExplorerPlugin(Plugin):

    # Extension points we contribute to.
    PERSPECTIVES = 'enthought.envisage.ui.workbench.perspectives'
    VIEWS = 'enthought.envisage.ui.workbench.views'
    SERVICE_OFFERS = 'enthought.envisage.ui.workbench.service_offers'

    # The plugin's unique identifier.
    id = 'explorer3d.Explorer3D'

    # The plugin's name (suitable for displaying to the user).
    name = '3D function explorer'

    # Perspectives.
    perspectives = List(contributes_to=PERSPECTIVES)

    # Services we contribute.
    service_offers = List(contributes_to=SERVICE_OFFERS)

    # Views.
    views = List(contributes_to=VIEWS)

    ######################################################################
    # Private methods.
    def _perspectives_default(self):
        """ Trait initializer. """
        return [ExplorerPerspective]

    def _service_offers_default(self):
        """ Trait initializer. """
        explorer_service_offer = ServiceOffer(
            protocol='explorer_app.Explorer3D',
            factory='explorer_app.Explorer3D')

        return [explorer_service_offer]

    def _views_default(self):
        """ Trait initializer. """
        return [self._explorer_view_factory]

    def _explorer_view_factory(self, window, **traits):
        """ Factory method for explorer views. """
        from enthought.pyface.workbench.traits_ui_view import \
                TraitsUIView

        explorer = self._get_explorer(window)
        tui_engine_view = TraitsUIView(obj=explorer,
                                       id='explorer3d.Explorer3D',
                                       name='Explorer3D',
                                       window=window,
                                       position='left',
                                       **traits)
        return tui_engine_view

    def _get_explorer(self, window):
        """Return the explorer service."""
        return window.get_service('explorer_app.Explorer3D')
class NBSNetworkParameter(HasTraits):

    choices1 = List(Str)
    selected1 = List(Str)

    choices2 = List(Str)
    selected2 = List(Str)

    view = View(
        HGroup(
            Group(HGroup(
                Item('choices1',
                     show_label=False,
                     editor=TabularEditor(show_titles=False,
                                          selected='selected1',
                                          editable=False,
                                          multi_select=True,
                                          adapter=MultiSelectAdapter())),
                Item('selected1',
                     show_label=False,
                     editor=TabularEditor(show_titles=False,
                                          editable=False,
                                          adapter=MultiSelectAdapter())),
            ),
                  label="First group"),
            Group(HGroup(
                Item('choices2',
                     show_label=False,
                     editor=TabularEditor(show_titles=False,
                                          selected='selected2',
                                          editable=False,
                                          multi_select=True,
                                          adapter=MultiSelectAdapter())),
                Item('selected2',
                     show_label=False,
                     editor=TabularEditor(show_titles=False,
                                          editable=False,
                                          adapter=MultiSelectAdapter())),
            ),
                  label="Second group"),
        ),
        title='Select networks',
        width=0.5,
        height=0.5,
        buttons=['OK'],
        resizable=True,
    )

    def __init__(self, cfile, **traits):
        super(NBSNetworkParameter, self).__init__(**traits)

        li = []
        for cobj in cfile.connectome_network:
            li.append(cobj.obj.name)

        self.choices1 = li
        self.choices2 = li
Beispiel #15
0
class SetEditorDemo(HasTraits):
    """ Defines the SetEditor demo class.
    """

    # Define a trait each for four SetEditor 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:
    view = View(no_nma_group,
                no_ma_group,
                o_nma_group,
                o_ma_group,
                title='SetEditor',
                buttons=['OK'])
Beispiel #16
0
class CheckListEditorDemo(HasTraits):
    """ Define the main CheckListEditor demo class. """

    # Define a trait for each of three formations:
    checklist_4col = List(
        editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4))

    checklist_2col = List(
        editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=2))

    checklist_1col = List(
        editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=1))

    # CheckListEditor display with four columns:
    cl_4_group = Group(Item('checklist_4col', style='simple', label='Simple'),
                       Item('_'),
                       Item('checklist_4col', style='custom', label='Custom'),
                       Item('_'),
                       Item('checklist_4col', style='text', label='Text'),
                       Item('_'),
                       Item('checklist_4col',
                            style='readonly',
                            label='ReadOnly'),
                       label='4-column')

    # CheckListEditor display with two columns:
    cl_2_group = Group(Item('checklist_2col', style='simple', label='Simple'),
                       Item('_'),
                       Item('checklist_2col', style='custom', label='Custom'),
                       Item('_'),
                       Item('checklist_2col', style='text', label='Text'),
                       Item('_'),
                       Item('checklist_2col',
                            style='readonly',
                            label='ReadOnly'),
                       label='2-column')

    # CheckListEditor display with one column:
    cl_1_group = Group(Item('checklist_1col', style='simple', label='Simple'),
                       Item('_'),
                       Item('checklist_1col', style='custom', label='Custom'),
                       Item('_'),
                       Item('checklist_1col', style='text', label='Text'),
                       Item('_'),
                       Item('checklist_1col',
                            style='readonly',
                            label='ReadOnly'),
                       label='1-column')

    # The view includes one group per column formation.  These will be displayed
    # on separate tabbed panels.
    view1 = View(cl_4_group,
                 cl_2_group,
                 cl_1_group,
                 title='CheckListEditor',
                 buttons=['OK'],
                 resizable=True)
Beispiel #17
0
class _RegistryData(HasTraits):
    # Object's script ID
    script_id = Property(Str)

    # Path to object in object hierarchy.
    path = Property(Str)

    # Parent data for this object if any.
    parent_data = Instance('_RegistryData', allow_none=True)

    # The name of the trait on the parent which is this object.
    trait_name_on_parent = Str('')

    # List of traits we are listening for on this object.
    names = List(Str)

    # Nested recordable instances on the object.
    sub_recordables = List(Str)

    # List of traits that are lists.
    list_names = List(Str)

    _script_id = Str('')

    ######################################################################
    # Non-public interface.
    ######################################################################
    def _get_path(self):
        pdata = self.parent_data
        path = ''
        if pdata is not None:
            pid = pdata.script_id
            ppath = pdata.path
            tnop = self.trait_name_on_parent
            if '[' in tnop:
                # If the object is a nested object through an iterator,
                # we instantiate it and don't refer to it through the
                # path, this makes scripting convenient.
                if len(ppath) == 0:
                    path = pid + '.' + tnop
                else:
                    path = ppath + '.' + tnop
            else:
                path = ppath + '.' + tnop

        return path

    def _get_script_id(self):
        sid = self._script_id
        if len(sid) == 0:
            pdata = self.parent_data
            sid = pdata.script_id + '.' + self.trait_name_on_parent
        return sid

    def _set_script_id(self, id):
        self._script_id = id
Beispiel #18
0
class GraphCanvas(HasPrivateTraits):
    """ Defines a representation of a graph canvas for use by the graph editor
        and the graph editor factory classes.
    """

    # Names of list traits whose elements are represented as nodes.
    node_children = List(Str)

    # Names of the list traits whose elements are represented as edges.
    edge_children = List(Str)
Beispiel #19
0
class Facet(Sphere):
    """Facet class creates Facet from triangle list, follows the
    usual VTK pipeline and creates a Facet actor, which is passed to
    the show_actor() function as an argument.
    """
    #####################################################################
    # Traits definitions
    coords = List(value=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], 0.0, 0.0, 1.0],
                  desc='the vertex list')
    indices = List(value=[[0, 1, 2]], desc='the triangle index list')
    color = vtk_color_trait((1.0, 1.0, 1.0))
    representation = Enum('s', 'w', 'p')
    visibility = Bool(True)
    viewer = Any
    polydata = Instance(tvtk.PolyData, ())
    property = Instance(tvtk.Property)
    actor = Instance(tvtk.Actor,
                     ())  # tvtk Actor, for the usual pipeline architecture.
    ######################################################################
    # User interface view
    traits_view = View(
        Group(Item(name='coords', style='simple', label='Vertices'),
              Item(name='indices', label='Triangle indices'),
              Item(name='color'),
              Item(name='visibility'),
              Item(name='representation'),
              label='Facet Properties',
              show_border=True))

    def __init__(self, **traits):
        self.property = self.actor.property

        HasTraits.__init__(self, **traits)
        self._create_points(self.coords, self.indices)
        self._color_changed(self.color)
        self._visibility_changed(self.visibility)
        normals = tvtk.PolyDataNormals(input=self.polydata)
        m = tvtk.PolyDataMapper(
            input=normals.output)  # the usual vtk pipleine countinuation
        self.actor.mapper = m
        self.property = self.actor.property
        self.property.representation = self.representation
        show_actor(self.actor)  # passing the actors function for rendering
        self.viewer = get_viewer()  # getting the ivtk viewer
        self.property.on_trait_change(self.viewer.scene.render)
        self.actor.on_trait_change(self.viewer.scene.render)

    ######################################################################
    # Non-public methods, Event handlers
    def _create_points(self, c, i):
        self.polydata = tvtk.PolyData(points=numpy.array(c),
                                      polys=numpy.array(i))
        self.points = c
        return self.points, self.polydata.polys
        class AcmeUIPreferencesHelper(PreferencesHelper):
            """ A helper! """

            # The traits that we want to initialize from preferences.
            bgcolor = Str
            width = Int
            ratio = Float
            visible = Bool
            description = Unicode
            offsets = List(Int)
            names = List(Str)
Beispiel #21
0
class GodotPlugin(Plugin):
    """ Godot plug-in.
    """

    # Extension point IDs
    EDITORS = "puddle.resource.editors"
    NEW_WIZARDS = "puddle.resource.new_wizards"
    ACTION_SETS = "enthought.envisage.ui.workbench.action_sets"

    # Unique plugin identifier
    id = "godot.plugin"

    # Human readable plugin name
    name = "Godot"

    #--------------------------------------------------------------------------
    #  Extensions (Contributions):
    #--------------------------------------------------------------------------

    # Contributed workspace editors:
    editors = List(contributes_to=EDITORS)

    # Contributed new resource wizards:
    new_wizards = List(contributes_to=NEW_WIZARDS)

    # Contributed action sets:
    action_sets = List(contributes_to=ACTION_SETS)

    #--------------------------------------------------------------------------
    #  "ImageEditorPlugin" interface:
    #--------------------------------------------------------------------------

    def _editors_default(self):
        """ Trait initialiser.
        """
        from graph_editor import GraphEditorExtension
        from tree_editor import TreeEditorExtension

        return [GraphEditorExtension, TreeEditorExtension]

    def _new_wizards_default(self):
        """ Trait initialiser.
        """
        from wizard import NewDotWizardExtension

        return [NewDotWizardExtension]

    def _action_sets_default(self):
        """ Trait initialiser.
        """
        from action import GodotWorkbenchActionSet

        return [GodotWorkbenchActionSet]
class ListDemo2(HasTraits):
    filter_types = List(Str, value=[u"低通", u"高通", u"带通", u"带阻"])
    items = List(Str)
    view = View(HGroup(Item("filter_types", label=u"候选"),
                       Item("items",
                            style="custom",
                            editor=CheckListEditor(name="filter_types")),
                       show_labels=False),
                resizable=True,
                width=300,
                height=180,
                title=u"动态修改候选值")
Beispiel #23
0
class MatchDialog(HasTraits):
    choices = List(Str)
    selection = List(Str)

    view = TraitsView(Item('selection',
                           editor=SetEditor(name='choices',
                                            can_move_all=True,
                                            ordered=False),
                           show_label=False),
                      buttons=[OKButton, CancelButton],
                      kind='modal',
                      title='Parameters to match')
Beispiel #24
0
class LoggerDemoPlugin(Plugin):
    """ Add some perspectives.
    """

    id = 'LoggerDemoPlugin'

    BINDINGS = 'enthought.plugins.python_shell.bindings'
    PERSPECTIVES = 'enthought.envisage.ui.workbench.perspectives'
    COMMANDS = 'enthought.plugins.python_shell.commands'
    MAIL_FILES = 'enthought.logger.plugin.mail_files'

    perspectives = List(contributes_to=PERSPECTIVES)
    bindings = List(contributes_to=BINDINGS)
    commands = List(contributes_to=COMMANDS)
    mail_files = List(contributes_to=MAIL_FILES)

    def _perspectives_default(self):
        return [LoggerDemoPerspective]

    def _bindings_default(self):
        bindings = [dict(
            test=self._test,
            test_timing=self._test_timing,
        )]
        return bindings

    def _commands_default(self):
        commands = [
            'import logging',
        ]
        return commands

    def _mail_files_default(self):
        return [self._package_project_files]

    def _test(self, n=2000):
        for i in range(n):
            logging.warn('foo %r', i)

    def _test_timing(self, n=2000):
        t = time.time()
        for i in range(1, n + 1):
            if not (i % 100):
                t2 = time.time()
                print '%1.2f s for 100 logs' % (t2 - t)
                t = t2
            logging.warn('foo %r', i)

    def _package_project_files(self, zf):
        """ Add dummy project files to the userdata.zip file to be mailed back.
        """
        write_str_to_zipfile(zf, 'logger_demo/data.txt', 'Foo!\n')
        class AcmeUIPreferencesHelper(PreferencesHelper):
            """ A helper! """

            # The path to the preferences node that contains our preferences.
            preferences_path = 'acme.ui'

            # The traits that we want to initialize from preferences.
            bgcolor = Str('blue')
            width = Int(50)
            ratio = Float(1.0)
            visible = Bool(True)
            description = Unicode(u'description')
            offsets = List(Int, [1, 2, 3, 4])
            names = List(Str, ['joe', 'fred', 'jane'])
Beispiel #26
0
class RunOutput(HasTraits):
    '''class to store the output if a sequence of runcases'''
    # the names of the variables
    variable_names = List(String)
    # 2d array
    variable_values = Array(numpy.float, shape=(None, None))
    eigenmodes = List(List(EigenMode))
    eigenmatrix = List(EigenMatrix)
    #output_view = Instance(View)
    #eigenmode_view = Instance(View)
    def save_variables(self, file):
        file.write('"%s"\n' %('"\t"'.join(self.variable_names)))
        for row in self.variable_values:
            file.write('%s\n' %('\t'.join([str(var) for var in row])))
        class AcmeUIPreferencesHelper(PreferencesHelper):
            """ A helper! """

            # The path to the preferences node that contains our preferences.
            preferences_path = 'acme.ui'

            # The traits that we want to initialize from preferences.
            bgcolor = Str
            width = Int
            ratio = Float
            visible = Bool
            description = Unicode
            offsets = List(Int)
            names = List(Str)
Beispiel #28
0
class TableTest(HasStrictTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    #people = Instance( Person )
    people = List(Person)

    #---------------------------------------------------------------------------
    #  Traits view definitions:
    #---------------------------------------------------------------------------

    _valid_states = List(["AL", "AR", "AZ", "AK"])

    _state_editor = EnumEditor(name="_valid_states",
                               evaluate=evaluate_value,
                               object='table_editor_object')

    table_editor = TableEditor(columns=[
        ObjectColumn(name='name'),
        ObjectColumn(name='age'),
        ObjectColumn(name='phone'),
        ObjectColumn(name='state', editor=_state_editor),
    ],
                               editable=True,
                               deletable=True,
                               sortable=True,
                               sort_model=True,
                               show_lines=True,
                               orientation='vertical',
                               show_column_labels=True,
                               edit_view=View(
                                   ['name', 'age', 'phone', 'state', '|[]'],
                                   resizable=True),
                               filter=None,
                               filters=filters,
                               row_factory=Person)

    traits_view = View(
        [Item('people', id='people', editor=table_editor), '|[]<>'],
        title='Table Editor Test',
        id='enthought.traits.ui.tests.table_editor_test',
        dock='horizontal',
        width=.4,
        height=.3,
        resizable=True,
        buttons=NoButtons,
        kind='live')
Beispiel #29
0
class PipelineInfo(HasTraits):

    """
    This class represents the information that a particular input or
    output of an object should contain.
    """

    # The datasets supported by the object.
    datasets = List(DataSet)

    # The attribute types the object works on.
    attribute_types = List(AttributeType)

    # The attributes the object can use/produce.
    attributes = List(Attribute)
Beispiel #30
0
class DataSet(HasTraits):
    """
    A class encapsulating a dataset of binary masks of segmented images 
    stored in an HDF5 file.
    """
    h5file = Instance(tables.File)
    plates = List(Str)

    def __init__(self, *args, **kwargs):
        """
        Construct a DataSet object from the given PyTables file handle.
        """
        super(DataSet, self).__init__(*args, **kwargs)
        for platenode in self.h5file.root:
            self.plates.append(getattr(platenode, '_v_pathname'))

    def __len__(self):
        return len(self.plates)

    def __getitem__(self, key):
        if type(key) is slice:
            indices = islice(xrange(len(self)), *key.indices(len(self)))
            return [self[nkey] for nkey in indices]
        else:
            node = self.h5file.getNode(self.plates[key])
            return Plate(h5file=self.h5file, node=node)

    def __contains__(self):
        raise TypeError("Containment checking not supported: %s" % str(self))