Example #1
0
  def handle_arguments(self,*args,**kwargs): 
    HasTraits.__init__(self)		#magic by fnoble
    for a in args:
      if isinstance(a,Frame):
        self.parent=a
    for k,v in kwargs.items():
      if k == 'frame':
        self.parent=v
      elif k == 'T':
         if isinstance(v,Expression):
           self.T=v
         else:
           self.T=self.parent.variables.new_expression(v)
      elif len(self.trait_get(k))>0:
         #self.trait_set({k:v})
         self.__setattr__(k,v)
      elif len(self.actor.trait_get(k))>0:
         self.actor.__setattr__(k,v)
      elif len(self.properties.trait_get(k))>0:
         self.properties.__setattr__(k,v)
      elif len(self.source.trait_get(k))>0:
         self.source.__setattr__(k,v)
      else :
         print "unknown argument", k , v

    if not(self.parent):
      self.parent = WorldFrame()
Example #2
0
    def __init__(self, fgcolor=(0.0, 0.0, 0.0), bgcolor=(1.0, 1.0, 1.0),
                 **traits):
        HasTraits.__init__(self, **traits)
        scene = self.scene.scene

        scene.foreground = fgcolor
        scene.background = bgcolor
Example #3
0
    def handle_arguments(self, *args, **kwargs):
        HasTraits.__init__(self)  #magic by fnoble
        for a in args:
            if isinstance(a, Frame):
                self.parent = a
        for k, v in kwargs.items():
            if k == 'frame':
                self.parent = v
            elif k == 'T':
                if isinstance(v, Expression):
                    self.T = v
                else:
                    self.T = self.parent.variables.new_expression(v)
            elif len(self.trait_get(k)) > 0:
                #self.trait_set({k:v})
                self.__setattr__(k, v)
            elif len(self.actor.trait_get(k)) > 0:
                self.actor.__setattr__(k, v)
            elif len(self.properties.trait_get(k)) > 0:
                self.properties.__setattr__(k, v)
            elif len(self.source.trait_get(k)) > 0:
                self.source.__setattr__(k, v)
            else:
                print "unknown argument", k, v

        if not (self.parent):
            self.parent = WorldFrame()
Example #4
0
    def __init__(self, parent=None, manage_overlay=True, **traits):
        HasTraits.__init__(self, **traits)
        self.master_src # instantiates default master_src and blender
        self.func_man
        from xipy.vis.mayavi_widgets.overlay_blending import ImageBlendingComponent
        from xipy.vis.mayavi_widgets.overlay_thresholding_surface import OverlayThresholdingSurfaceComponent
        from xipy.vis.mayavi_widgets.cortical_surface import CorticalSurfaceComponent
        from xipy.vis.mayavi_widgets.translated_planes import TranslatedPlanes

        # set up components
        self.vis_helpers.append(
            ImageBlendingComponent(self, manage_overlay)
            )
        self.vis_helpers.append(
            TranslatedPlanes(self)
            )
        self.vis_helpers.append(
            OverlayThresholdingSurfaceComponent(self)
            )

        self.vis_helpers.append(
            CorticalSurfaceComponent(self)
            )
                        
        
        anat_alpha = np.ones(256)
        anat_alpha[:5] = 0
        self.blender.set(main_alpha=anat_alpha, trait_notify_change=False)
        self.__reposition_planes_after_interaction = False
Example #5
0
    def __init__(self, fgcolor=(0.0, 0.0, 0.0), bgcolor=(1.0, 1.0, 1.0),
                 **traits):
        HasTraits.__init__(self, **traits)
        scene = self.scene.scene

        scene.foreground = fgcolor
        scene.background = bgcolor
 def __init__(self):
     HasTraits.__init__(self)
     x, y, z = ogrid[-10:10:100j, -10:10:100j, -10:10:100j]
     scalars = sin(x * y * z) / (x * y * z)
     src = ArraySource(scalar_data=scalars)
     self.scene.mayavi_scene.add_child(src)
     src.add_module(IsoSurface())
Example #7
0
 def _showerror_fired(self,evt):
     if self.tmodel.lastfitfailure:
         ex = self.tmodel.lastfitfailure
         dialog = HasTraits(s=ex.__class__.__name__+': '+str(ex))
         view = View(Item('s',style='custom',show_label=False),
                     resizable=True,buttons=['OK'],title='Fitting error message')
         dialog.edit_traits(view=view)
Example #8
0
 def __init__(self):
     HasTraits.__init__(self)
     x, y, z = ogrid[-10:10:100j, -10:10:100j, -10:10:100j]
     scalars = sin(x*y*z)/(x*y*z)
     src = ArraySource(scalar_data=scalars)
     self.scene.mayavi_scene.add_child(src)
     src.add_module(IsoSurface())
Example #9
0
 def _showerror_fired(self,evt):
     if self.tmodel.lastfitfailure:
         ex = self.tmodel.lastfitfailure
         dialog = HasTraits(s=ex.__class__.__name__+': '+str(ex))
         view = View(Item('s',style='custom',show_label=False),
                     resizable=True,buttons=['OK'],title='Fitting error message')
         dialog.edit_traits(view=view)
Example #10
0
 def __init__(self, vmin, vmax, vdefault, **traits):
     HasTraits.__init__(self, **traits)
     self.vmin = vmin
     self.vmax = vmax
     trait = Range(float(vmin), float(vmax), value=vdefault)
     self.add_trait("coord", trait)
     self.coord = vdefault
 def __init__(self, source, **traits):
     HasTraits.__init__(self, **traits)
     nTs = self.time.shape[0]
     if isinstance(source, HasTraits):
         self.traited = True
         self.tracking = source.traits(track=True).keys()
         for attr in self.tracking:
             shape = (nTs,)
             if type(getattr(source, attr)) is _numpy.ndarray:
                 shape += getattr(source, attr).shape
             self.data[attr] = _numpy.zeros(shape, "d")
     else:
         if type(source) is type([]):
             self.tracking = source
             for var in source:
                 self.data[var] = _numpy.zeros((nTs,), "d")
             self._update = _copy(source)
         elif type(source) is type({}):
             self.tracking = source.keys()
             for var in self.tracking:
                 shape = (nTs,) + tuple(source[var])
                 self.data[var] = _numpy.zeros(shape, "d")
             self._update = _copy(self.tracking)
         else:
             raise TypeError, self.__class__.__doc__
     self.source = source
Example #12
0
 def __init__(self):
     HasTraits.__init__(self)
     # Create some data, and plot it using the embedded scene's engine
     x, y, z = ogrid[-10:10:100j, -10:10:100j, -10:10:100j]
     scalars = sin(x * y * z) / (x * y * z)
     src = ArraySource(scalar_data=scalars)
     self.scene.engine.add_source(src)
     src.add_module(IsoSurface())
 def __init__(self, pos_data, **traits):
     """Required first argument is the 4-column data array from a Pos.p file
     """
     HasTraits.__init__(self, **traits)
     if not (pos_data[:,-1] == -99).all():
         valid = (pos_data[:,-1] != -99).nonzero()[0]
         pos_data = pos_data[valid]
     self.t, self.x, self.y, self.angle = pos_data.T
Example #14
0
 def __init__(self, **traits):
     # if incoming args have a subject list, ignore any nsubj spec
     if 'subjs' in traits:
         traits['nsubj'] = len(traits['subjs'])
     HasTraits.__init__(self, **traits)
     print self.cname # force default
     if 'cname' not in traits:
         Condition.cond += 1
Example #15
0
 def __init__(self, condition, avg_beams, stats_results, **traits):
     HasTraits.__init__(self, **traits)
     self._avg_dict = {}
     self.stats_results = stats_results
     
     for c, b in zip(condition, avg_beams):
         self._avg_beams.append(str(c))
         self._avg_dict[str(c)] = b
Example #16
0
 def __init__(self):
     HasTraits.__init__(self)
     # Create some data, and plot it using the embedded scene's engine
     x, y, z = ogrid[-10:10:100j, -10:10:100j, -10:10:100j]
     scalars = sin(x*y*z)/(x*y*z)
     src = ArraySource(scalar_data=scalars)
     self.scene.engine.add_source(src)
     src.add_module(IsoSurface())
Example #17
0
    def __init__(self, **traits):
        HasTraits.__init__(self, **traits)
        self.engine_view = EngineView(engine=self.scene.engine)

        # Hook up the current_selection to change when the one in the engine
        # changes.  This is probably unnecessary in Traits3 since you can show
        # the UI of a sub-object in T3.
        self.scene.engine.on_trait_change(self._selection_change,
                                          'current_selection')
Example #18
0
 def __init__(self, *args, **kw):
     HasTraits.__init__(self, *args, **kw)
     numpoints = 200
     plotdata = ArrayPlotData(x=sort(random(numpoints)), y=random(numpoints))
     plot = Plot(plotdata)
     plot.plot(("x", "y"), type="scatter")
     plot.tools.append(PanTool(plot))
     plot.overlays.append(ZoomTool(plot))
     self.plot = plot
Example #19
0
 def __init__(self):
     # Do not forget to call the parent's __init__
     HasTraits.__init__(self)
     x, y, z, = tens_fld(1, 1, 1, self.beta, self.alpha)
     self.plot = self.scene.mlab.mesh(x,
                                      y,
                                      z,
                                      colormap='copper',
                                      representation='surface')
Example #20
0
 def __init__ ( self, object, name, index, trait, value ):
     HasTraits.__init__( self )
     self.inited = False
     self.object = object
     self.name   = name
     self.index  = index
     if trait is not None:
         self.add_trait( 'value', trait )
         self.value  = value
     self.inited = True
Example #21
0
 def __init__(self, object, name, index, trait, value):
     HasTraits.__init__(self)
     self.inited = False
     self.object = object
     self.name = name
     self.index = index
     if trait is not None:
         self.add_trait('value', trait)
         self.value = value
     self.inited = True
Example #22
0
    def __init__(self, **traits):
        HasTraits.__init__(self, **traits)
        self.engine_view = EngineView(engine=self.scene.engine)

        # Hook up the current_selection to change when the one in the engine
        # changes.  This is probably unnecessary in Traits3 since you can show
        # the UI of a sub-object in T3.
        self.scene.engine.on_trait_change(self._selection_change,
                                          'current_selection')

        self.generate_data_mayavi()
Example #23
0
 def __init__(self, *args, **kw):
     HasTraits.__init__(self, *args, **kw)
     # Create the data and the PlotData object
     x = linspace(-14, 14, 100)
     y = sin(x) * x**3
     plotdata = ArrayPlotData(x = x, y = y)
     # Create the scatter plot
     plot = Plot(plotdata)
     plot.plot(("x", "y"), type=self.plot_type, color="blue")
     plot.tools.append(PanTool(plot))
     plot.tools.append(ZoomTool(plot))
     self.plot = plot
Example #24
0
    def __init__(self, **traits):
        HasTraits.__init__(self, **traits)
        
        try:
            if not path.exists(self.datadir):
                makedirs(self.datadir)
        except OSError:
            self.out('Reverting to base directory:\n%s'%ANA_DIR, error=True)
            self.datadir = ANA_DIR
        finally:
            self.datadir = path.abspath(self.datadir)

        self.out('%s initialized:\n%s'%(self.__class__.__name__, str(self)))
 def __init__(self, pmap, **traits):
     HasTraits.__init__(self, **traits)
     try:
         self.PMap = pmap
     except TraitError:
         self.out('PlaceMap subclass instance required', error=True)
         return
     self.fdata = self.PMap.get_field_data()
     self.udata = self.PMap.get_unit_data()
     self.add_trait('unit', Range(low=0, high=self.PMap.num_maps-1))
     self._update_unit_values()
     self.out('Bringing up place-map visualization...')
     self.view()
     self.out('Done!')
Example #26
0
 def __init__(self, eval=None, label='Value', 
              trait=None, min=0.0, max=1.0, 
              initial=None, **traits):
     HasTraits.__init__(self, **traits)
     if trait is None:
         if min > max: 
             min, max = max, min
         if initial is None:
             initial = min 
         elif not (min <= initial <= max):
             initial = [min, max][
                         abs(initial - min) > 
                         abs(initial - max)]
         trait = Range(min, max, value = initial)
     self.add_trait(label, trait)
Example #27
0
    def __init__(self, klass, blist, subj_labels, cond_labels):
        self._comp_args = (blist, subj_labels, cond_labels)
        self._comp_class = klass
        HasTraits.__init__(self)
        for c in np.unique(cond_labels):
            self.all_conditions.append(str(c))
        # an ordered list of conditions to use in comparisons
        self.add_trait(
            'active_conditions',
            List(editor=CheckListEditor(cols=1, values=self.all_conditions))
            )

        self.__iscontrast = klass is bstats.BeamContrastAverager
        self.on_trait_change(self._make_comp, 'run_comp', dispatch='new')
        self.on_trait_change(self._make_test, 'run_stats', dispatch='new')
Example #28
0
 def __init__(self, *l, **kw):
     # TODO: implement aspect ratio maintaining
     HasTraits.__init__(self, *l, **kw)
     #self.plotdata = ArrayPlotData(x=self.pointsx, y=self.pointsy)
     plot = Plot(self.plotdata)
     plot.plot(("x", "y"))
     plot.plot(("x", "y"), type='scatter')
     
     plot.tools.append(PanTool(plot, drag_button='left'))
     plot.tools.append(ZoomTool(plot, tool_mode='box'))
     plot.tools.append(DragZoom(plot, tool_mode='box', drag_button='right'))
     plot.tools.append(CustomSaveTool(plot))#, filename='/home/pankaj/Desktop/file.png'))
     plot.tools.append(TraitsTool(plot))
     self.plot = plot
     self.set_plotdata()
Example #29
0
 def __init__(self, eval=None, label='Value',
              trait=None, min=0.0, max=1.0,
              initial=None, **traits):
     HasTraits.__init__(self, **traits)
     if trait is None:
         if min > max:
             min, max = max, min
         if initial is None:
             initial = min
         elif not (min <= initial <= max):
             initial = [min, max][
                 abs(initial - min) >
                 abs(initial - max)]
         trait = Range(min, max, value=initial)
     self.add_trait(label, trait)
Example #30
0
    def __init__(self, under_image, over_image):
        """
        Provide the underlay and overlay NiftiImages.  Can also
        provide filename strings.

        Example:

        stat = OverlayMap('anat.nii.gz','stat.nii.gz')
        """
        # we've got traits
        HasTraits.__init__(self)

        # load in the image
        if isinstance(under_image, NiftiImage):
            # use it
            self.__under_image = under_image
        elif isinstance(under_image, str):
            # load from file
            self.__under_image = NiftiImage(under_image)
        else:
            raise ValueError("under_image must be a NiftiImage or a file.")

        # TODO: set the extent and spacing of the under image

        # set the over data
        if isinstance(over_image, str):
            # load from file
            over_image = NiftiImage(over_image)

        if isinstance(over_image, NiftiImage):
            # TODO: make sure it matches the dims of under image
            # TODO: set the extent
            
            # save just the dat
            self.__over_image = over_image.data.T

        elif isinstance(over_image, np.ndarray):
            # just set it
            # assumes it matches the dims and extent of the under image
            self.__over_image = over_image

        else:
            raise ValueError("over_image must be a NiftiImage, ndarray, or file.")

        self.__over_image = np.ma.masked_invalid(self.__over_image)

        self.configure_traits()
        pass
Example #31
0
    def edit_traits(self, *args, **kwargs):
        """Extend to set up the view and bind key events."""

        if self.parent:
            # Allow the inspector to handle key events
            self.parent.Bind(wx.EVT_CHAR, self.handleKeyEvent)
            self.parent.SetFocusFromKbd()

        # Set the view to the traits_view attribute if it is not specified
        # Necessary because traits_view is created as an instance attribute
        # at runtime, rather than as part of the class definition
        if not kwargs.get('view', None):
            kwargs['view'] = self.traits_view

        # Set handler and buttons if they are not specified
        if not kwargs['view'].handler:
            kwargs['view'].handler = RegionInspectorHandler
        if not kwargs['view'].buttons:
            kwargs['view'].buttons = NoButtons

        if self.parent:
            # Inspector is being embedded - don't show the title
            self.traits_view.title = ""

        #if 'level1' in self.region.getName():
        #  from dbgp.client import brk; brk(port=9011)

        return HasTraits.edit_traits(self, *args, **kwargs)
Example #32
0
    def __init__(self):
        HasTraits.__init__(self)
        print 'GraphDisplay.__init__()'

        x = arange(0, 10, 0.5)
        plotdata = ArrayPlotData(x=x, y1=np.sin(x))
        # Create the left plot
        left_plot = Plot(plotdata)
        renderer = left_plot.plot(('x', 'y1'), type='line', color='blue'
                                  , width=2.0)[0]
        renderer.overlays.append(LineInspector(renderer, axis='value',
                                 write_metadata=True, is_listener=True))
        renderer.overlays.append(LineInspector(renderer, axis='index',
                                 write_metadata=True, is_listener=True))

        self.plot = left_plot
Example #33
0
 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)
Example #34
0
    def __init__(self, *l, **kw):
        # TODO: implement aspect ratio maintaining
        HasTraits.__init__(self, *l, **kw)
        #self.plotdata = ArrayPlotData(x=self.pointsx, y=self.pointsy)
        plot = Plot(self.plotdata)
        plot.plot(("x", "y"))
        plot.plot(("x", "y"), type='scatter')

        plot.tools.append(PanTool(plot, drag_button='left'))
        plot.tools.append(ZoomTool(plot, tool_mode='box'))
        plot.tools.append(DragZoom(plot, tool_mode='box', drag_button='right'))
        plot.tools.append(CustomSaveTool(
            plot))  #, filename='/home/pankaj/Desktop/file.png'))
        plot.tools.append(TraitsTool(plot))
        self.plot = plot
        self.set_plotdata()
Example #35
0
def get_trait_names():
    global TRAIT_NAMES
    from enthought.traits.api import HasTraits
    if TRAIT_NAMES is None:
        TRAIT_NAMES = set( dir2(HasTraits()) ) - set( dir2(object()) )
    else:
        return TRAIT_NAMES
Example #36
0
  def edit_traits(self, *args, **kwargs):
    """Extend to set up the view and bind key events."""

    if self.parent:
      # Allow the inspector to handle key events
      self.parent.Bind(wx.EVT_CHAR, self.handleKeyEvent)
      self.parent.SetFocusFromKbd()

    # Set the view to the traits_view attribute if it is not specified
    # Necessary because traits_view is created as an instance attribute
    # at runtime, rather than as part of the class definition
    if not kwargs.get('view', None):
      kwargs['view'] = self.traits_view

    # Set handler and buttons if they are not specified
    if not kwargs['view'].handler:
      kwargs['view'].handler = RegionInspectorHandler
    if not kwargs['view'].buttons:
      kwargs['view'].buttons = NoButtons

    if self.parent:
      # Inspector is being embedded - don't show the title
      self.traits_view.title = ""

    #if 'level1' in self.region.getName():
    #  from dbgp.client import brk; brk(port=9011)

    return HasTraits.edit_traits(self, *args, **kwargs)
Example #37
0
    def test_extended(self):
        """ Tests a dynamic trait change handler using extended names. """
        class Child(HasTraits):
            i = Int

        class Parent(HasTraits):
            child = Instance(Child)

        # Create objects
        parent = Parent(child=Child())
        target = HasTraits()

        # Set up to count changes in i
        self.count = 0

        def count_notifies():
            self.count += 1

        parent.on_trait_change(count_notifies, "child:i", target=target)

        # Change the trait
        parent.child.i = 10
        # Delete the target and change it again
        del target
        parent.child.i = 0
        # The count should be 1
        self.assertEqual(self.count, 1)
Example #38
0
    def __init__(self, *args, **kwargs):
        """ Try to find an module actor with the same name, on the given 
        parent (if any) and use it rather than building a new module."""
        # Call the HasTraits constructor, but not the PipeBase one.
        HasTraits.__init__(self)
        self._scene = gcf()
        if not 'figure' in kwargs:
            self._engine = get_engine() 
        else:
            figure = kwargs['figure']
            self._engine = engine_manager.find_figure_engine(figure)
            self._engine.current_scene = figure
            kwargs.pop('figure')
        if self._scene.scene is not None:
            self._scene.scene.disable_render = True
        # Process the arguments
        if len(args)==1:
            (parent, ) = args
        elif len(args)==0:
            parent = self._engine.current_object
        else:
            raise ValueError, "Wrong number of arguments"

        # Try to find an existing module, if not add one to the pipeline
        if parent == None:
            target = self._scene
        else:
            target = parent
        
        klass = self._target.__class__

        for obj in tools._traverse(target):
            if ( isinstance(obj, klass)
                        and obj.name == self.name ):
                self._target = obj
                break
        else:
            # Keep a reference to the parent
            self._parent = parent
            self._engine.add_module(self._target, obj=parent)

        # Now calling the traits setter, so that traits handlers are
        # called
        self.set(**kwargs)
        if self._scene.scene is not None:
            self._scene.scene.disable_render = False
Example #39
0
    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)
Example #40
0
    def __init__(self, *args, **kwargs):
        """ Try to find an module actor with the same name, on the given 
        parent (if any) and use it rather than building a new module."""
        # Call the HasTraits constructor, but not the PipeBase one.
        HasTraits.__init__(self)
        self._scene = gcf()
        if not 'figure' in kwargs:
            self._engine = get_engine()
        else:
            figure = kwargs['figure']
            self._engine = engine_manager.find_figure_engine(figure)
            self._engine.current_scene = figure
            kwargs.pop('figure')
        if self._scene.scene is not None:
            self._scene.scene.disable_render = True
        # Process the arguments
        if len(args) == 1:
            (parent, ) = args
        elif len(args) == 0:
            parent = self._engine.current_object
        else:
            raise ValueError, "Wrong number of arguments"

        # Try to find an existing module, if not add one to the pipeline
        if parent == None:
            target = self._scene
        else:
            target = parent

        klass = self._target.__class__

        for obj in tools._traverse(target):
            if (isinstance(obj, klass) and obj.name == self.name):
                self._target = obj
                break
        else:
            # Keep a reference to the parent
            self._parent = parent
            self._engine.add_module(self._target, obj=parent)

        # Now calling the traits setter, so that traits handlers are
        # called
        self.set(**kwargs)
        if self._scene.scene is not None:
            self._scene.scene.disable_render = False
Example #41
0
    def __init__(self, **traits):
        """ Create a new grid model. """

        # Base class constructors.
        HasTraits.__init__(self, **traits)

        # The wx virtual table hook.
        self._grid_table_base = _GridTableBase(self)
        
	if len(self.columns) == 0 and self.data is not None:
	    print "Building default table column model"
	    columns = []
	    # Assume data is rectangular and use the length of the first row.
	    for i in range(len(self.data[0])):
		columns.append(GridColumn(label=str(i)))
	    self.columns = columns
	    
        return
Example #42
0
    def __init__(self):
        HasTraits.__init__(self)
        self._scene = mlab.gcf().scene
        #self.q1 = mlab.quiver3d(-2.0,0.0,0.0,1.0,0.0,0.0, colormap='Reds',mode='arrow')
        #self.q2 = mlab.quiver3d(-1.0,0.0,0.0,1.0,0.0,0.0, colormap='Greens',mode='arrow')
        #self.q3 = mlab.quiver3d(0.0,0.0,0.0,1.0,0.0,0.0, colormap='Blues',mode='arrow')
        #self.q4 = mlab.quiver3d(1.0,0.0,0.0,1.0,0.0,0.0, colormap='Reds',mode='arrow')
        #self.q5 = mlab.quiver3d(2.0,0.0,0.0,1.0,0.0,0.0,  colormap='Greens',mode='arrow')
        #self.q6 = mlab.quiver3d(3.0,0.0,0.0,1.0,0.0,0.0,  colormap='Blues',mode='arrow')


        self.queue = Queue()
        self.c = CaptureThread("COM4")
        self.c.start()

        simModel = loadBVHFile('walk.bvh', conversionFactor=0.01)

        self.configure_traits()
Example #43
0
    def __init__(self, millisec, callable, *args, **kwargs):
        """Constructor.

        **Parameters**

          :millisec: int specifying the delay in milliseconds
                     between calls to the callable.

          :callable: callable function to call after the specified
                     delay.

          :\*args: optional arguments to be passed to the callable.

          :\*\*kwargs: optional keyword arguments to be passed to the callable.

        """
        HasTraits.__init__(self)
        self.delay = millisec
        self.timer = Timer(millisec, callable, *args, **kwargs)
Example #44
0
    def __setattr__(self, name, value):
        """Only update traits when their value changes."""

        #if name == 'coincImages':
        #  from dbgp.client import brk; brk(port=9011)
        if hasattr(self, name):
            currentValue = getattr(self, name)
            if isinstance(currentValue, numpy.ndarray):
                if numpy.alltrue(currentValue == value):
                    return
            else:
                try:
                    if type(currentValue) == type(
                            value) and currentValue == value:
                        return
                except ValueError:  # Can occur with numpy array inside a collection
                    pass

        HasTraits.__setattr__(self, name, value)
  def __setattr__(self, name, value):
    """Only update traits when their value changes."""

    #if name == 'coincImages':
    #  from dbgp.client import brk; brk(port=9011)
    if hasattr(self, name):
      currentValue = getattr(self, name)
      if isinstance(currentValue, numpy.ndarray):
        if numpy.alltrue(currentValue == value):
          return
      else:
        try:
          if type(currentValue) == type(value) and currentValue == value:
            return
        except ValueError:  # Can occur with numpy array inside a collection
          pass


    HasTraits.__setattr__(self, name, value)
Example #46
0
    def __init__(self, tMin, tMax, *renderers):
        """
        Initialise idle animator.

        @param tMin: Time to start animation.
        @param tMax: Time at which to wrap back to tMin.
        @param renderers: List of L{AnimatedRenderer} objects.
        """
        HasTraits.__init__(self)
        self._renderers = renderers
        self._tMin = tMin
        self._tMax = tMax
        self.speed = 1
        self.time = tMin
        self.playing = False
        self._scene = mlab.gcf().scene
        autoPositionCamera()
        for r in self._renderers:
            r.renderUpdate(self.time)
        self.edit_traits()
Example #47
0
 def __init__(self, **traits):
     HasTraits.__init__(self, **traits)
     max_level = min(self.pf.h.max_level,
                     self.min_grid_level + self.number_of_levels - 1)
     self.extracted_pf = ExtractedParameterFile(self.pf,
                                                self.min_grid_level,
                                                max_level,
                                                offset=None)
     self.extracted_hierarchy = self.extracted_pf.h
     self._hdata_set = tvtk.HierarchicalBoxDataSet()
     self._ugs = []
     self._grids = []
     self._min_val = 1e60
     self._max_val = -1e60
     gid = 0
     if self.cache:
         for grid_set in self.extracted_hierarchy.get_levels():
             for grid in grid_set:
                 grid[self.field]
     for l, grid_set in enumerate(self.extracted_hierarchy.get_levels()):
         gid = self._add_level(grid_set, l, gid)
     if self.show_grids:
         self.toggle_grid_boundaries()
Example #48
0
    def __init__(self, *l, **kw):
        # TODO: implement aspect ratio maintaining
        HasTraits.__init__(self, *l, **kw)
        #self.plotdata = ArrayPlotData(x=self.pointsx, y=self.pointsy)
        plot = Plot(self.plotdata)
        renderer = plot.plot(("x", "y"))

        #lineplot = create_line_plot((self.pointsx,self.pointsy), width=2.0)
        #lineplot.tools.append(PanTool(lineplot, drag_button='middle'))
        #lineplot.tools.append(ZoomTool(lineplot, tool_mode='box'))
        plot.tools.append(PanTool(plot, drag_button='left'))
        plot.tools.append(ZoomTool(plot, tool_mode='box'))
        plot.tools.append(DragZoom(plot, tool_mode='box', drag_button='right'))
        plot.tools.append(CustomSaveTool(
            plot))  #, filename='/home/pankaj/Desktop/file.png'))
        #plot.overlays.append(PlotLabel('Section : %s' % self.section.type,component=plot))

        #plot.tools.append(PlotToolbar(plot))
        plot.tools.append(TraitsTool(plot))
        #plot.tools.append(ZoomTool(plot, tool_mode='box', axis='index', drag_button='right', always_on=True))
        #plot.aspect_ratio = 3
        #plot.request_redraw()
        #print plot.bounds
        #plot.aspect_ratio = 1
        #plot.bounds = [500,300]
        #print plot.bounds
        #plot.range2d = DataRange2D(low=(0,-.5), high=(1,0.5))
        #print plot.bounds
        for renderer in chain(*plot.plots.values()):
            renderer.index_mapper.stretch_data = False
            renderer.value_mapper.stretch_data = False

            renderer.index_mapper.range.low = 0
            renderer.index_mapper.range.high = 1
            renderer.value_mapper.range.low = -3 / 8.
            renderer.value_mapper.range.high = 3 / 8.
        self.plot = plot
Example #49
0
 def __init__(self, data, **kwargs):
     HasTraits.__init__(self)
     self.data = data
     if issubclass(self.data.__class__, VMOModel):
         if self.data.num_trials == 1:
             self.data = VMOSession(self.data)
         else:
             self.data.out('Assuming you want trial 1 out of %d!'%
                 self.data.num_trials, error=True)
             self.data = VMOSession(self.data, trial=1)
     
     # Get the population response map
     self.Map = self.data.get_population_matrix(**kwargs)
     self.units, self.bins = self.Map.shape
     self.angle = get_angle_array(self.bins)
     
     # Compute place field sizes, COMs, distribution, etc
     self._find_maxima()
     self._store_fields()
     self._compute_field_info()
     self._compute_coverage()
     
     # Once data is reduced, release reference to original data source
     self.data = None
Example #50
0
    def edit_traits(self, *args, **kwargs):
        """Extend to set the current view."""

        if self.parent:
            # Allow the inspector to handle key events
            self.parent.Bind(wx.EVT_CHAR, self.handleKeyEvent)

        # Set the view to the traits_view attribute if it is not specified
        # Necessary because traits_view is created as an instance attribute
        # at runtime, rather than as part of the class definition
        if not kwargs.get('view', None):
            kwargs['view'] = self.traits_view

        # Set handler and buttons if they are not specified
        if not kwargs['view'].handler:
            kwargs['view'].handler = NetworkInspectorHandler
        if not kwargs['view'].buttons:
            kwargs['view'].buttons = NoButtons

        # Remove the title if the inspector is being embedded
        if self.parent:
            self.traits_view.title = ""

        return HasTraits.edit_traits(self, *args, **kwargs)
Example #51
0
    def test_simple(self):
        """ Tests a simple dynamic trait change handler. """
        class Test(HasTraits):
            i = Int

        # Create objects
        obj = Test()
        target = HasTraits()

        # Set up to count changes in i
        self.count = 0

        def count_notifies():
            self.count += 1

        obj.on_trait_change(count_notifies, "i", target=target)

        # Change the trait
        obj.i = 10
        # Delete the target and change it again
        del target
        obj.i = 0
        # The count should be 1
        self.assertEqual(self.count, 1)
Example #52
0
                             Item('p2.name', label=u"姓名"),
                             Item('p2.salary', label=u"工资"),
                             Item('p2.bonus', label=u"奖金"),
                             show_border=True),
                       orientation='horizontal'),
                 title=u"员工对比")

employee1 = Employee(department=u"开发", name=u"张三", salary=3000, bonus=300)
employee2 = Employee(department=u"销售", name=u"李四", salary=4000, bonus=400)

if __name__ == "__main__":
    # 方法一:调用configure_traits,通过context关键字指定模型对象

    HasTraits().configure_traits(view=comp_view,
                                 context={
                                     "p1": employee1,
                                     "p2": employee2
                                 })

    # 方法二:调用视图对象的ui方法显示模型,它的参数是一个字典,将作为
    # UI对象的context属性。此方法需要后续的代码启动界面库的消息循环
    #comp_view.ui({"p1":employee1, "p2":employee2})

    ##### 通过GUI启动消息循环
    #from enthought.pyface.api import GUI
    #GUI().start_event_loop() # 开始后台界面库的消息循环

    ##### 直接启动wx库的消息循环
    #import wx
    #wx.PySimpleApp().MainLoop() # 开始wx的消息循环
Example #53
0
 def __init__(self, **kwargs):
     t.Thread.__init__(self)
     HasTraits.__init__(self, **kwargs)
Example #54
0
 def __init__(self, variables, expr, **kwargs):
     HasTraits.__init__(self, **kwargs)
     self._vars = variables
     self.set_expr(expr)
Example #55
0
 def __init__(self, **kwargs):
     HasTraits.__init__(self, **kwargs)
     self.viewer_node.on_select = self.click_viewer
Example #56
0
 def __init__(self, **kwargs):
   HasTraits.__init__(self, **kwargs)
   axes = self.figure.add_subplot(111)
   t = linspace(0, 2*pi, 200)
   axes.plot(sin(t)*(1+0.5*cos(11*t)), cos(t)*(1+0.5*cos(11*t)))
Example #57
0
 def __init__(self, **kwargs):
     HasTraits.__init__(self, **kwargs)
     self.init_data()
Example #58
0
 def __init__(self, **traits):
     HasTraits.__init__(self, **traits)
     self.generate_data()