예제 #1
0
 def run(self):
     print "Performing expensive calculation in %s..." % self.getName(),
     sleep(3)
     sd = self.data.scalar_data
     sd += numpy.sin(numpy.random.rand(*sd.shape) * 2.0 * numpy.pi)
     GUI.invoke_later(self.data.update)
     print 'done.'
예제 #2
0
 def run(self):
     print "Performing expensive calculation in %s..." % self.getName(),
     sleep(3)
     sd = self.data.scalar_data
     sd += numpy.sin(numpy.random.rand(*sd.shape) * 2.0 * numpy.pi)
     GUI.invoke_later(self.data.update)
     print "done."
예제 #3
0
    def wrapper(*args, **kw):
        """Wrapper function to run given function inside the GUI event
        loop.
        """
        global _gui, _stop_show
        tk = ETSConfig.toolkit

        if is_ui_running():
            # In this case we should not pop up the UI since we likely
            # don't want to stop the mainloop.
            return func(*args, **kw)
        else:
            g = GUI()
            if tk == "wx":
                # Create a dummy app so invoke later works on wx.
                a = ApplicationWindow(size=(1, 1))
                GUI.invoke_later(lambda: a.close())
                a.open()

            GUI.invoke_later(func, *args, **kw)
            _gui = g
            if stop:
                # Pop up the UI to stop the mainloop.
                _stop_show = StopShow()
            g.start_event_loop()
예제 #4
0
    def wrapper(*args, **kw):
        """Wrapper function to run given function inside the GUI event
        loop.
        """
        global _gui, _stop_show
        tk = ETSConfig.toolkit

        if is_ui_running():
            # In this case we should not pop up the UI since we likely
            # don't want to stop the mainloop.
            return func(*args, **kw)
        else:
            g = GUI()
            if tk == 'wx':
                # Create a dummy app so invoke later works on wx.
                a = ApplicationWindow(size=(1, 1))
                GUI.invoke_later(lambda: a.close())
                a.open()

            GUI.invoke_later(func, *args, **kw)
            _gui = g
            if stop:
                # Pop up the UI to stop the mainloop.
                _stop_show = StopShow()
            g.start_event_loop()
예제 #5
0
    def run(self):
        if ((not hasattr(self,'nonlinear_distortion_model')) or
            (self.nonlinear_distortion_model is None)):
            do_undistortion = False
        else:
            do_undistortion = True

        if do_undistortion:
            im,ll,ur = self.nonlinear_distortion_model.remove_distortion(
                self.image_data)
        else:
            im = self.image_data
            ll = 0,0
            ur = im.shape[:2][::-1]-np.array([1,1])

        ax = self.mplwidget.axes
        ax.images=[]
        ax.lines=[]
        kwargs = {}

        if self.display_transform == 'flip y':
            display_im = im
            kwargs['origin']='lower'
            kwargs['extent']=(ll[0],ur[0],ll[1],ur[1])
        elif self.display_transform == 'identity':
            display_im = im
            kwargs['extent']=(ll[0],ur[0],ur[1],ll[1])
        elif self.display_transform == 'rotate 180':
            display_im = np.rot90(np.rot90(im))
            kwargs['extent']=(ur[0],ll[0],ll[1],ur[1])#(ll[0],ur[0],ur[1],ll[1])
        elif self.display_transform == 'rotate 90':
            display_im = np.rot90(im)
            kwargs['extent']=(ll[1],ur[1],ll[0],ur[0])
        elif self.display_transform == 'rotate 270':
            display_im = np.rot90(np.rot90(np.rot90(im)))
            kwargs['extent']=(ur[1],ll[1],ur[0],ll[0])
        else:
            raise ValueError("unknown transform '%s'"%self.display_transform)

        ax.imshow(display_im,
                  aspect='equal',
                  cmap=cm.pink,
                  **kwargs)

        if hasattr(self,'lines'):
            if do_undistortion:
                func = self.nonlinear_distortion_model.undistort
            else:
                func = None
            draw_lines_on_ax(ax,self.lines,func=func,
                             display_transform=self.display_transform)

        GUI.invoke_later(self.mplwidget.figure.canvas.draw)
예제 #6
0
 def _loaded_changed(self, value):
     if value:
         n = self.dname
         if ' [Active]' not in n:
             self.dname = "%s [Loaded]" % n
             
         if not self.window is None:
             #from enthought.pyface.timer.api import do_later
             from enthought.pyface.api import GUI
             GUI.invoke_later(self.window.status_bar_manager.set, message = '')
         
     else:
         self.dname = self.dname.replace(' [Loaded]', '')
예제 #7
0
 def _active_changed(self , value):
     if value:
         n = self.name
         if ' [Active]' not in n:
             self.name = "%s [Active]" % n
             
         # XXX: do refactor with threaded loading of surfaces
         # and default spring force layout for graph rendering!
         # see also TraitsUI Demos: Multi thread demo
         
         # load the surface containers data
         # make a deep copy of the already loaded surface containers
         import copy
         self.surfaces = copy.deepcopy(self.surfaces_loaded)
         for surfcont in self.surfaces:
             surfcont.load_surface_container()
         
         if self.rendermanager is None:
             self._create_datasourcemanager()
             self._create_renderer()
             # if there are no surfaces, initialize
             # network rendering, but only if dn_positions are given
             if len(self.surfaces) == 0:
                 logger.debug('No surfaces found. Try to render graph view with dn_position information.')
                 self.rendermanager.datasourcemanager._compute_3DLayout(-1, -1)
                 self.rendermanager.visualize_graph()
             else:
                 logger.debug('SurfaceContainer found. Try to render 3D View using %s.' % self.surfaces[0].name)
                 if len(self.surfaces[0].surfaces) == 0:
                     logger.debug('Rendering not possible because SurfaceContainer contains no surfaces.')
                 else:
                     logger.debug('Using first surface for rendering.')
                     self.surfaces[0].surfaces[0]._layout_3DView()
         
         if not self._parentcfile._workbenchwin is None:
             #from enthought.pyface.timer.api import do_later
             from enthought.pyface.api import GUI
             GUI.invoke_later(self._parentcfile._workbenchwin.status_bar_manager.set, message = '')
         
     else:
         self.name = self.name.replace(' [Active]', '')
         logger.debug('Close RenderManager scenes')
         self.rendermanager.close_scenes()
         logger.debug('All scenes closed.')
         # FIXME: what is happening in the following?
         # e.g. for instances. e.g. reset traits?
         # XXX: this is somehow not correct. do i need to use del
         # or remove/reset traits?
         self.rendermanager = None
         self.datasourcemanager = None
         self.surfaces = []
예제 #8
0
파일: tree.py 프로젝트: sjl421/code-2
    def _on_tree_end_label_edit(self, event):
        """ Called when the user has finished editing am item's label. """

        wxid = event.GetItem()

        # The item data is a tuple.  The first element indicates whether or not
        # we have already populated the item with its children.  The second
        # element is the actual item data.
        populated, node = self.control.GetPyData(wxid)

        # Give the model a chance to veto the edit.
        label = event.GetLabel()

        # Making sure the new label is not an empty string

        if label is not None and len(label) > 0 and \
            self.model.can_set_text(node, label):

            def end_label_edit():
                """ Called to complete the label edit. """

                # Set the node's text.
                self.model.set_text(node, label)

                # If a label edit callback was specified (in the call to
                # 'edit_label'), then call it).
                if self._label_edit_callback is not None:
                    self._label_edit_callback(self, node, label)

                return

            # We use a deffered call here, because a name change can trigger
            # the structure of a node to change, and hence the actual tree
            # nodes might get moved/deleted before the label edit operation has
            # completed.  When this happens wx gets very confused!  By using
            # 'invoke_later' we allow the label edit to complete.
            GUI.invoke_later(end_label_edit)

        else:
            event.Veto()

            # If a label edit callback was specified (in the call to
            # 'edit_label'), then call it).
            if self._label_edit_callback is not None:
                self._label_edit_callback(self, node, label)

        return
예제 #9
0
파일: tree.py 프로젝트: enthought/traitsgui
    def _on_tree_end_label_edit(self, event):
        """ Called when the user has finished editing am item's label. """

        wxid = event.GetItem()

        # The item data is a tuple.  The first element indicates whether or not
        # we have already populated the item with its children.  The second
        # element is the actual item data.
        populated, node = self.control.GetPyData(wxid)

        # Give the model a chance to veto the edit.
        label = event.GetLabel()

        # Making sure the new label is not an empty string

        if label is not None and len(label) > 0 and \
            self.model.can_set_text(node, label):
            def end_label_edit():
                """ Called to complete the label edit. """

                # Set the node's text.
                self.model.set_text(node, label)

                # If a label edit callback was specified (in the call to
                # 'edit_label'), then call it).
                if self._label_edit_callback is not None:
                    self._label_edit_callback(self, node, label)

                return

            # We use a deffered call here, because a name change can trigger
            # the structure of a node to change, and hence the actual tree
            # nodes might get moved/deleted before the label edit operation has
            # completed.  When this happens wx gets very confused!  By using
            # 'invoke_later' we allow the label edit to complete.
            GUI.invoke_later(end_label_edit)

        else:
            event.Veto()

            # If a label edit callback was specified (in the call to
            # 'edit_label'), then call it).
            if self._label_edit_callback is not None:
                self._label_edit_callback(self, node, label)

        return
예제 #10
0
    def _on_editor_closed(self, editor):
        """ Dynamic trait change handler. """

        index = self.editors.index(editor)
        del self.editors[index]
        if editor is self.active_editor:
            if len(self.editors) > 0:
                index = min(index, len(self.editors) - 1)
                # If the user closed the editor manually then this method is
                # being called from a toolkit-specific event handler. Because
                # of that we have to make sure that we don't change the focus
                # from within this method directly hence we activate the editor
                # later in the GUI thread.
                GUI.invoke_later(self.activate_editor, self.editors[index])

            else:
                self.active_editor = None

        return
예제 #11
0
    def normal_right_down(self, event):
        """ Right click will bring up a dialog to edit the
            prefix/suffix of the selected variables.
        """
        field = self._get_underlying_box_field(event.x, event.y)
        if field:
            selected_fields = self.input_selected_fields + self.output_selected_fields
            if field in selected_fields:
                for group in self.menu.groups:
                    for action_item in group.items:
                        action = action_item.action
                        action.container = self.component
                        action.selected_fields = selected_fields
                menu = self.menu.create_menu(event.window.control)

                if len(event._pos_stack) > 0:
                    real_x, real_y = event._pos_stack[0]
                else:
                    real_x, real_y = event.x, event.y
                from enthought.pyface.api import GUI
                GUI.invoke_later(menu.show, real_x - 10, event.window._flip_y(real_y))
                self.component.request_redraw()
        event.handled = True
예제 #12
0
 def run(self):
     im = self.image
     X, Y = indices(im.shape)
     x = sum(X*im)/sum(im)
     y = sum(Y*im)/sum(im)
     width = sqrt(abs(sum(((X-x)**2+(Y-y)**2)*im)/sum(im))) 
     GUI.invoke_later(setattr, self.results, 'x', x)
     GUI.invoke_later(setattr, self.results, 'y', y)
     GUI.invoke_later(setattr, self.results, 'width', width)
예제 #13
0
    def run(self):
        logger.debug("Start Threaded Parsing of Connectome File ...")
        import time
        tic = time.time()
        
        # given the full path to meta.xml, create lxml tree and
        # under the precondition of having a certain file version and generator
        # one can assume some content of the .cff file
        # loop over the networks, for each network, the surfaces etc.
        # in the form of all the attributes (name, srce filename, description etc.)
        # are given to the created Network instance methods to complete
        from lxml import etree
        tree = etree.fromstring(self.metaxmlcontent)   
        nsprefix = "{%s}" % tree.nsmap[None]
        
        t = 0
        for child in tree.iterchildren():
            if child.tag == (nsprefix+'viewer-network'):
                t = t + 1

        if t != self.data.metadata.nr_of_networks:
            logger.error('The number of networks of networks in meta.xml is not correct!')
            logger.error('Loading ' + str(t) + ' network(s).')


        # find all the networks
        for child in tree.iterchildren():
            if child.tag == (nsprefix+'viewer-network'):

                # load network as string from zip
                # create temporary StringIO
                logger.info('-----------------------------------------')
                logger.info('Now loading ' + child.attrib['src'])
                logger.info('-----------------------------------------')
                
                if child.attrib.has_key('src'):
                    (tmpstring, pickled_graph, local_fname) = self.process_pickle(childnode = child)
                
                tmp_network = Network(name = child.attrib['name'],
                                    src = tmpstring,
                                    pickled_graph = pickled_graph,
                                    directed = child.attrib['directed'],
                                    hierarchical = child.attrib['hierarchical'],
                                    hypergraph = child.attrib['hypergraph'])

                # store pickled version in connectome file
                if not tmpstring is None and pickled_graph is None:
                    self.save_pickle_in_cfile(local_fname, networkref = tmp_network)

                
                # iterate over children
                for mchildren in child.iterchildren():
                    
                    # handling of the metadata
                    # -------------------------
                    if mchildren.tag == (nsprefix+'network-metadata'):
                        tmp_network.metadata = self.process_metadata(metadata_node = mchildren, nsprefix = nsprefix)
                        
                        
                    # handling of the surfaces
                    # ------------------------
                    if mchildren.tag == (nsprefix+'network-surface'):
                    
                        # load into surface
                        attr = mchildren.attrib
    
                        if attr.has_key('src'):
                            # create surface container
                            tmpsurfacecontainer = self.process_surface(surface_node = mchildren, nsprefix = nsprefix)
                            # and add it to the network
                            tmp_network.add_surface_container(tmpsurfacecontainer)

                        # adding a template atlas if stated in the meta.xml
                        if attr.has_key('addatlas'):
                            # create surface container for atlas
                            tmpsurfacecontainer = self.process_atlas(surface_node = mchildren, nsprefix = nsprefix)
                            # and add it to the network
                            tmp_network.add_surface_container(tmpsurfacecontainer)
                            
                        
                    # handling of the volumes
                    # -----------------------
                    elif mchildren.tag == (nsprefix+'network-volume'):
                        
                        # get the description, is there an easier way with lxml?
                        for desc in mchildren.iterchildren():
                            if desc.tag == (nsprefix+'description'):
                                mydescr = desc.text
                      
                        attr = mchildren.attrib
                        
                        if attr.has_key('src') and attr.has_key('name'):
                          
                            if not attr.has_key('segmentation'):
                                segm = False
                            else:
                                segm = bool(attr['segmentation'])
                          
                            # create an instance of the Volume class with it
                            tmpvolume = Volume(volumename = attr['name'], \
                                                 networkref = tmp_network, \
                                                 src = attr['src'], \
                                                 description = mydescr, \
                                                 segmentation = segm)
                            
                            # add this instance to the list of its network
                            tmp_network.add_volume(tmpvolume)
                            logger.info('Added volume ' + tmpvolume.volumename + \
                                        ' to ' + tmp_network.networkname)

                            
                    # handling of the trackfiles
                    # --------------------------
                    elif mchildren.tag == (nsprefix+'network-track'):
                        
                        # get the description, is there an easier way with lxml?
                        for desc in mchildren.iterchildren():
                            if desc.tag == (nsprefix+'description'):
                              mydescr = desc.text
                      
                        attr = mchildren.attrib
                    
                        if attr.has_key('src') and attr.has_key('name'):
                            tmptrack = Trackfile(trkname = attr['name'], tmpfname = attr['src'], \
                                                 description = mydescr, networkref = tmp_network)
                            
                            # add this instance to the list of its trackfiles
                            tmp_network.add_trackfile(tmptrack)
                            logger.info('Added trackfile ' + tmptrack.trkname + \
                                        ' to ' + tmp_network.networkname)

                # setting the correct parent cfile
                tmp_network._parentcfile = self.data
                
                # add the created network object to this cfile
                self.data.networks.append(tmp_network)

        toc = time.time()
        logger.info('Loading Connectome File DONE. (Time: %s)' % str(toc-tic))
        logger.info('-----------------------------------------')
        
        # setting data loaded flag
        self.data._data_loaded = True
        
        # with do_later, we the change in the statusbar is done in the gui main thread
        if not self.data._workbenchwin is None:
            #from enthought.pyface.timer.api import do_later
            #do_later(self.data._workbenchwin.status_bar_manager.set, message = '')
            # TEST
            from enthought.pyface.api import GUI
            GUI.invoke_later(self.data._workbenchwin.status_bar_manager.set, message = '')
예제 #14
0
 def update(self):
   for prim in self.primitives:
     prim.update()
   GUI.invoke_later(self.scene.render)
예제 #15
0
 def update(self):
     for prim in self.primitives:
         prim.update()
     GUI.invoke_later(self.scene.render)
예제 #16
0
 def image_show(self, image):
     """ Plots an image on the canvas in a thread safe way.
     """
     self.mplwidget.axes.images=[]
     self.mplwidget.axes.imshow(image, aspect='auto')
     GUI.invoke_later(self.mplwidget.figure.canvas.draw)
예제 #17
0
 def add_line(self, string):
     """ Adds a line to the textbox display in a thread-safe way.
     """
     GUI.invoke_later(setattr, self, 'results_string', 
                             (string + "\n" + self.results_string)[0:1000] )
예제 #18
0
 def object_update_changed(self, info):
     if info.initialized:
         def run():
             info.object.fig.canvas.draw()
         GUI.invoke_later(run) 
예제 #19
0
 def object_update_changed(self, info):
     if info.initialized:
         info.object.ax.mouse_init() 
         GUI.invoke_later(info.object.fig.canvas.draw) 
예제 #20
0
 def _snrs_changed(self):
   GUI.invoke_later(self.update_snrs)
 def run(self):
     new_data = self.dataset[self.dataset.time]
     GUI.invoke_later(setattr, self.scalar_field.mlab_source, 'scalars',
     new_data)
예제 #22
0
 def add_line(self, string):
     GUI.invoke_later(setattr, self, 'string', string + "\n" + self.string)