def _search_results_items_changed(self, event):
        """ Add/remove the items from the context.

        This should only get called when the user adds or deletes a row from the
        GUI. Changing the search term does not affect this.

        Unique names are enforced. The enforcement is done here because the
        variables are constructed before being put on the list so this is the
        first opportunity to check with the context.
        """
        # XXX: use the undo framework for this.

        self.context.defer_events = True

        for var in event.added:
            var.name = self._create_unique_key(var.name)
            self.context[var.name] = var.value

        for var in event.removed:
            del self.context[var.name]

        # This may have been triggered by creating a new var with the UI,
        # in which case, adding the new row needs to finish before we handle
        # the context events.

        def _enable_events(context):
            context.defer_events = False

        do_later(_enable_events, self.context)
    def _filter_changed(self, old_filter, new_filter):
        """Handles the current filter being changed."""

        if not self._no_notify:
            if new_filter is customize_filter:
                do_later(self._customize_filters, old_filter)
            else:
                self._update_filtering()
                self.model.invalidate()
                self.set_selection(self.selected)
Beispiel #3
0
    def write(self, text):
        def aux():
            self.log += self.text_buffer
            self.text_buffer = ''

        self.text_buffer += text

        tt = time.clock()
        if tt > (self.time_tag + 2.0):
            do_later(aux)
            self.time_tag = tt
Beispiel #4
0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    if "-h" in args or "--help" in args:
        usage()
        sys.exit(0)

    if "-v" in args:
        logger.addHandler(logging.StreamHandler())
        logger.setLevel(logging.INFO)
        args.remove("-v")

    kw = {}
    files = []
    for arg in args:
        if "=" not in arg:
            if arg.endswith(".npz"):
                files.append(arg)
                continue
            else:
                usage()
                sys.exit(1)
        key, arg = [x.strip() for x in arg.split("=")]
        try:
            val = eval(arg, math.__dict__)
            # this will fail if arg is a string.
        except NameError:
            val = arg
        kw[key] = val

    def _sort_func(x, y):
        """Sort the files correctly."""

        def _process(arg):
            a = os.path.splitext(arg)[0]
            return int(a[a.rfind("_") + 1 :])

        return cmp(_process(x), _process(y))

    files.sort(_sort_func)
    # This hack to set n_files first is a dirty hack to work around issues with
    # setting up the UI but setting the files only after the UI is activated.
    # If we set the particle arrays before the scene is activated, the arrays
    # are not displayed on screen so we use do_later to set the files.  We set
    # n_files to number of files so as to set the UI up correctly.
    m = MayaviViewer(n_files=len(files) - 1)
    do_later(m.set, files=files, **kw)
    m.configure_traits()
Beispiel #5
0
def sync_camera(reference_figure, target_figure):
    """ Synchronise the camera of the target_figure on the camera of the
        reference_figure.
    """
    reference_figure.scene._renderer.sync_trait('active_camera',
                                                target_figure.scene._renderer)
    target_figure.scene._renderer.active_camera.on_trait_change(
        lambda: do_later(target_figure.scene.render))
Beispiel #6
0
def sync_camera(reference_figure, target_figure):
    """ Synchronise the camera of the target_figure on the camera of the
        reference_figure.
    """
    reference_figure.scene._renderer.sync_trait('active_camera', 
                        target_figure.scene._renderer)
    target_figure.scene._renderer.active_camera.on_trait_change(
            lambda: do_later(target_figure.scene.render))
Beispiel #7
0
 def toggle_feature ( cls, event ):
     """ Toggles the feature on or off.
     """
     if cls.state == 0:
         cls.state = 1
         add_feature( cls )
         for control in event.window.control.GetChildren():
             window = getattr( control, 'owner', None )
             if isinstance( window, DockWindow ):
                 do_later( window.update_layout )
     else:
         method    = 'disable'
         cls.state = 3 - cls.state
         if cls.state == 1:
             method = 'enable'
         cls.instances = [ aref for aref in cls.instances 
                                if aref() is not None ]
         for aref in cls.instances:
             feature = aref()
             if feature is not None:
                 getattr( feature, method )()
def create_plot ( parent, editor ):
    """ Creates a data explorer plot.
    """
    try:
        nmep  = editor.object
        model = nmep.model
        items = nmep.plot_items
        if len( items ) == 0:
            return wx.Panel( parent, -1 )
        index = nmep.plot_index
        if index is None:
            plot_index = PlotValue( arange( 0.0, len( model.model_indices ) ) )
            selection_index = None
        else:
            plot_index      = PlotValue( ModelData( model = model,
                                                    name  = index.name ) )
            selection_index = PlotValue( SelectionData( model = model,
                                                        name  = index.name ) )
        canvas = PlotCanvas( plot_type     = items[0].plot_type,
                             plot_bg_color = items[0].canvas_color )
        canvas.axis_index = PlotAxis()
        if index is not None:
            canvas.axis_index.title = index.label
        if len( items ) == 1:
            canvas.axis = PlotAxis( title = items[0].label )
        else:
            canvas.add( PlotGroup(
                            overlay  = True,
                            position = 'top right',
                            *[ PlotOverlay( legend_color = item.line_color,
                                            text         = item.label,
                                            border_size  = 0,
                                            bg_color     = transparent,
                                            margin       = 0,
                                            padding      = 2 )
                               for item in items ] ) )
        for item in items:
            canvas.add( PlotValue( ModelData( model = model ).set(
                                              name  = item.name ),
                                   index         = plot_index,
                                   plot_type     = item.plot_type,
                                   line_weight   = item.line_weight,
                                   line_color    = item.line_color,
                                   fill_color    = item.fill_color,
                                   outline_color = item.outline_color,
                                   size          = 'small' ) )
            if selection_index is not None:
                plot_value = PlotValue( SelectionData( model = model ).set(
                                                       name  = item.name ),
                                        index      = selection_index,
                                        plot_type  = 'scatter',
                                        size       = item.selection_size,
                                        fill_color = item.selection_color )
                canvas.add( plot_value )

        # Set up the interactive data filters:
        if selection_index is not None:
            canvas.interaction = nmep._interaction = ia = \
                NumericModelExplorerInteraction( value = plot_value )
            nmep._selection_models = sms = []
            ia._filters = filters = []
            for item in items:
                sm = model.get_selection_model()
                sms.append( sm )
                sm.model_filter = PolygonFilter( x_value = index.name,
                                                 y_value = item.name )
                filters.append( sm.model_filter )

            ia.on_trait_change( editor.ui.handler.interaction_complete,
                                'points' )
            if len( nmep.polygon ) > 0:
                do_later( ia.set_selection, nmep.polygon )

        return Window( parent,
                       component = PlotComponent( component = canvas ) ).control
    except:
        import traceback
        traceback.print_exc()
        raise
Beispiel #9
0
 def RecalcSizes ( self ):
     """ Layout the contents of the sizer based on the sizer's current size 
         and position.
     """
     horizontal = (self._orient == wx.HORIZONTAL)
     x,   y     = self.GetPosition()
     dx, dy     = self.GetSize()
     x0, y0     = x, y
     ex         = x + dx
     ey         = y + dy
     mdx = mdy  = sdx = sdy = i = 0
     
     visible = True
     cur_max = 0
     while True:
         try:
             item = self.GetItem( i )
             if item is None:
                 break
             i += 1
         except:
             break
            
         idx, idy  = item.CalcMin()
         expand    = item.GetFlag() & wx.EXPAND
         if horizontal:
             if (x > x0) and ((x + idx) > ex):
                 x   = x0
                 y  += (mdy + sdy)
                 mdy = sdy = 0
                 if y >= ey:
                     visible = False
                     
             cur_max = max( idy, cur_max )
             if expand:
                 idy = cur_max
             
             if item.IsSpacer():
                 sdy = max( sdy, idy )
                 if x == x0:
                     idx = 0
             item.SetDimension( wx.Point( x, y ), wx.Size( idx, idy ) )
             item.Show( visible )
             x  += idx
             mdy = max( mdy, idy ) 
         else:
             if (y > y0) and ((y + idy) > ey):
                 y   = y0
                 x  += (mdx + sdx)
                 mdx = sdx = 0
                 if x >= ex:
                     visible = False
                     
             cur_max = max( idx, cur_max )
             if expand:
                 idx = cur_max
                     
             if item.IsSpacer():
                 sdx = max( sdx, idx )
                 if y == y0:
                     idy = 0
                 
             item.SetDimension( wx.Point( x, y ), wx.Size( idx, idy ) )
             item.Show( visible )
             y  += idy
             mdx = max( mdx, idx )
             
     if (not visible) and (self._needed_size is None):
         max_dx = max_dy = 0
         if horizontal:
             max_dy = max( dy, y + mdy + sdy - y0 )
         else:
             max_dx = max( dx, x + mdx + sdx - x0 )
         self._needed_size = wx.Size( max_dx, max_dy )
         if not self._frozen:
             self._do_parent( '_freeze' )
         do_later( self._do_parent, '_thaw' )
     else:
         self._needed_size = None
    def layout_3dview(self, surfacecontainerid, surfaceid):
        """ Visualizes the 3D view, initial rendering if necessary!
        
        Parameters
        ----------
        surfacecontainerid : int
            The surface container id to use for layouting
        surfaceid : int
            The particular surface to use for layouting
        
        """
        import time
        
        tic = time.time()
        # compute the sourceobject for layouting
        self.datasourcemanager._compute_3DLayout(surfacecontainerid, surfaceid)
        toc = time.time()
        logger.debug("SourceObject has been changed successfully. (Time: %s)" % str(toc-tic))

        # disable rendering for speedup
        self.scene3d.scene.disable_render = True

        # set the correct scene for the update (scene3d)
        self.engine.current_scene = self.scene3d

        # is there already data in the scenes, when not, create.
        if self.nodesrc is None and self.vectorsrc is None and self.surfsrc is None:
            
            tic = time.time()
            self.visualize_graph()
            toc = time.time()
            logger.debug('Graph rendered. Time: %s' % str(toc-tic))
            
            tic = time.time()
            self.visualize_surface()
            toc = time.time()
            logger.debug('Surface rendered. Time: %s' % str(toc-tic))
        else:
            # get the source object
            tso = self.datasourcemanager.get_sourceobject()
            
            tic = time.time()
            # update the positions of the network nodes
            self.nodesrc.mlab_source.set(x=tso.positions[:,0],\
                                                 y=tso.positions[:,1],\
                                                 z=tso.positions[:,2])
            self.nodesrc.mlab_source.update()
            
            toc = time.time()
            logger.debug('Node position updated. Time: %s' % str(toc-tic))
            
            tic = time.time()
            # update start_positions and vectors for the network
            self.vectorsrc.mlab_source.set(x=tso.start_positions[0],\
                y=tso.start_positions[1],z=tso.start_positions[2],\
                u=tso.vectors[0],v=tso.vectors[1],w=tso.vectors[2])
            
            # update the rendering
            self.vectorsrc.mlab_source.update()
            toc = time.time()
            logger.debug('Connectivity source updated. Time: %s' % str(toc-tic))
            
            tic = time.time()
            # update surface coordinates, triangles and labelarray
            # important: use reset because dimensions might have changed
            self.surfsrc.mlab_source.reset(x=tso.daV[:,0],\
                y=tso.daV[:,1], z=tso.daV[:,2],\
                triangles=tso.daF,\
                scalars=tso.labelarr.ravel())
            toc = time.time()
            
            # update the surface visibility
            self._show_surface()
            
            logger.debug('Surface source updated. Time: %s' % str(toc-tic))
            
        # enable rendering again
        self.scene3d.scene.disable_render = False
        
        # update statusbar (with do_later)
        from enthought.pyface.timer.api import do_later
        do_later(self.network._parentcfile._workbenchwin.status_bar_manager.set, message = '')
Beispiel #11
0
 def run(self):
     sol = pde_solve(self.gui.input_filename,
                     output_dir=self.gui.output_dir)
     do_later(assign_solution_to_gui, self.gui, sol)