Esempio n. 1
0
    def display_message(self, msg, title=None, is_error=False):
        """
        Display the specified message to the user.

        """

        # Ensure we record any reasons this method doesn't work.  Especially
        # since it's critical in displaying errors to users!
        try:

            # Attempt to identify the current application window.
            parent_window = None
            workbench = self.application.get_service('envisage.'
                'workbench.IWorkbench')
            if workbench is not None:
                parent_window = workbench.active_window.control

            # Display the requested message
            if is_error:
                error(parent_window, msg, title=title)
            else:
                information(parent_window, msg, title=title)

        except:
            logger.exception('Unable to display pop-up message')

        return
Esempio n. 2
0
    def delete ( self, path = None ):
        """ Deletes the associated directory from the file system.
        """
        if path is None:
            path = self.path

        not_deleted = 0
        try:
            for name in listdir( path ):
                fn = join( path, name )
                if isfile( fn ):
                    if self.include_file( fn ):
                        remove( fn )
                    else:
                        not_deleted += 1
                elif isdir( fn ) and (not self.delete( fn )):
                    not_deleted += 1
            if not_deleted == 0:
                rmdir( path )
                return True
        except:
            error( self.handler.parent, "Could not delete '%s'" % fn )

        # Indicate that the directory was not deleted:
        return False
Esempio n. 3
0
    def _show_open_dialog(self, parent):
        """
        Show the dialog to open a project.

        """

        # Determine the starting point for browsing.  It is likely most
        # projects will be stored in the default path used when creating new
        # projects.
        default_path = self.model_service.get_default_path()
        project_class = self.model_service.factory.PROJECT_CLASS

        if self.model_service.are_projects_files():
            dialog = FileDialog(parent=parent, default_directory=default_path,
                title='Open Project')
            if dialog.open() == OK:
                path = dialog.path
            else:
                path = None
        else:
            dialog = DirectoryDialog(parent=parent, default_path=default_path,
                message='Open Project')
            if dialog.open() == OK:
                path = project_class.get_pickle_filename(dialog.path)
                if File(path).exists:
                    path = dialog.path
                else:
                    error(parent, 'Directory does not contain a recognized '
                        'project')
                    path = None
            else:
                path = None

        return path
Esempio n. 4
0
 def read_file(self):
     """Read the file."""
     if op.exists(self.file):
         if self.file.endswith('.fif'):
             bem = read_bem_surfaces(self.file, verbose=False)[0]
             self.points = bem['rr']
             self.norms = bem['nn']
             self.tris = bem['tris']
         else:
             try:
                 points, tris = read_surface(self.file)
                 points /= 1e3
                 self.points = points
                 self.norms = []
                 self.tris = tris
             except Exception:
                 error(message="Error loading surface from %s (see "
                               "Terminal for details).",
                       title="Error Loading Surface")
                 self.reset_traits(['file'])
                 raise
     else:
         self.points = np.empty((0, 3))
         self.norms = np.empty((0, 3))
         self.tris = np.empty((0, 3))
Esempio n. 5
0
    def _get_hsp_raw(self):
        fname = self.hsp_file
        if not fname:
            return

        try:
            pts = read_hsp(fname)

            n_pts = len(pts)
            if n_pts > KIT.DIG_POINTS:
                msg = ("The selected head shape contains {n_in} points, "
                       "which is more than the recommended maximum ({n_rec}). "
                       "The file will be automatically downsampled, which "
                       "might take a while. A better way to downsample is "
                       "using FastScan.")
                msg = msg.format(n_in=n_pts, n_rec=KIT.DIG_POINTS)
                information(None, msg, "Too Many Head Shape Points")
                pts = _decimate_points(pts, 5)

        except Exception as err:
            error(None, str(err), "Error Reading Head Shape")
            self.reset_traits(['hsp_file'])
            raise
        else:
            return pts
Esempio n. 6
0
    def perform(self, event):

        plot_component = self.container.component

        filter = 'PNG file (*.png)|*.png|\nTIFF file (*.tiff)|*.tiff|'
        dialog = FileDialog(action='save as', wildcard=filter)

        if dialog.open() != OK:
            return

        # Remove the toolbar before saving the plot, so the output doesn't
        # include the toolbar.
        plot_component.remove_toolbar()

        filename = dialog.path

        width, height = plot_component.outer_bounds

        gc = PlotGraphicsContext((width, height), dpi=72)
        gc.render_component(plot_component)
        try:
            gc.save(filename)
        except KeyError as e:
            errmsg = ("The filename must have an extension that matches "
                      "a graphics format, such as '.png' or '.tiff'.")
            if str(e.message) != '':
                errmsg = ("Unknown filename extension: '%s'\n" %
                          str(e.message)) + errmsg

            error(None, errmsg, title="Invalid Filename Extension")

        # Restore the toolbar.
        plot_component.add_toolbar()
Esempio n. 7
0
    def _update_points(self):
        """Update the location of the plotted points"""
        if not hasattr(self.src, "data"):
            return

        trans = self.trans
        if np.any(trans):
            if trans.ndim == 0 or trans.shape == (3,) or trans.shape == (1, 3):
                pts = self.points * trans
            elif trans.shape == (3, 3):
                pts = np.dot(self.points, trans.T)
            elif trans.shape == (4, 4):
                pts = apply_trans(trans, self.points)
            else:
                err = (
                    "trans must be a scalar, a length 3 sequence, or an "
                    "array of shape (1,3), (3, 3) or (4, 4). "
                    "Got %s" % str(trans)
                )
                error(None, err, "Display Error")
                raise ValueError(err)
        else:
            pts = self.points

        self.src.data.points = pts
Esempio n. 8
0
    def _save_as_fired(self):
        # create raw
        try:
            raw = self.model.get_raw()
        except Exception as err:
            error(None, str(err), "Error Creating KIT Raw")
            raise

        # find default path
        stem, _ = os.path.splitext(self.sqd_file)
        if not stem.endswith('raw'):
            stem += '-raw'
        default_path = stem + '.fif'

        # save as dialog
        dlg = FileDialog(action="save as",
                         wildcard="fiff raw file (*.fif)|*.fif",
                         default_path=default_path)
        dlg.open()
        if dlg.return_code != OK:
            return

        fname = dlg.path
        if not fname.endswith('.fif'):
            fname += '.fif'
            if os.path.exists(fname):
                answer = confirm(None, "The file %r already exists. Should it "
                                 "be replaced?", "Overwrite File?")
                if answer != YES:
                    return

        self.queue.put((raw, fname))
        self.queue_len += 1
Esempio n. 9
0
 def _inner(self, info, *args, **kw):
     if not self.object_valid(info):
         mesg = 'Unable to save the data due to the following problem(s)\n'
         mesg += self.object_messages(info)
         error(info.ui.control, mesg)
         return False
     return func(self, info, *args, **kw)
Esempio n. 10
0
    def _get_misc_data(self):
        if not self.raw:
            return
        if self.show_gui:
            # progress dialog with indefinite progress bar
            prog = ProgressDialog(title="Loading SQD data...",
                                  message="Loading stim channel data from SQD "
                                  "file ...")
            prog.open()
            prog.update(0)
        else:
            prog = None

        try:
            data, times = self.raw[self.misc_chs]
        except Exception as err:
            if self.show_gui:
                error(None, "Error reading SQD data file: %s (Check the "
                      "terminal output for details)" % str(err),
                      "Error Reading SQD File")
            raise
        finally:
            if self.show_gui:
                prog.close()
        return data
def edit_function_call(func_def):

    if func_def.code is None:
        msg = "Perhaps your python path is not set correctly or\n" \
              "there is an error in the file (or one it imports).\n"
        error(None, msg, "Error loading function")

        return None

    # If it is a user-defined function, one would want to edit it
    # else it can remain un-editable.
    path_dir = os.path.dirname(func_def.filename)
    usr_path = os.path.join(ETSConfig.user_data, USER_MODULE_NAME)

    if path_dir == usr_path:
        # This is a user function

        is_ok = edit_user_function(func_def)

        if is_ok:
            if func_def.dirty:
                func_def.write(overwrite = True)

            return func_def
    else:
        is_ok = edit_sys_function(func_def)

        if is_ok:
            if func_def.dirty:
                func_def.write(overwrite = False)
            return func_def
Esempio n. 12
0
 def convert_output(self,tmp):
     a=tmp.split(" ")
     if len(a)<3:
         error(parent=None, title="error", message= "fehler: falscher string sollte Konvertiert werden: "+ str(a))
         return(tmp)
     print "Konvertiere:", a
     return(float(a[2]))
Esempio n. 13
0
    def get_prepare_bem_model_job(self, subject_to):
        subjects_dir = self.mri.subjects_dir
        subject_from = self.mri.subject

        bem_name = "inner_skull-bem"
        bem_file = bem_fname.format(subjects_dir=subjects_dir, subject=subject_from, name=bem_name)
        if not os.path.exists(bem_file):
            pattern = bem_fname.format(subjects_dir=subjects_dir, subject=subject_to, name="(.+-bem)")
            bem_dir, bem_file = os.path.split(pattern)
            m = None
            bem_file_pattern = re.compile(bem_file)
            for name in os.listdir(bem_dir):
                m = bem_file_pattern.match(name)
                if m is not None:
                    break

            if m is None:
                pattern = bem_fname.format(subjects_dir=subjects_dir, subject=subject_to, name="*-bem")
                err = "No bem file found; looking for files matching " "%s" % pattern
                error(err)

            bem_name = m.group(1)

        bem_file = bem_fname.format(subjects_dir=subjects_dir, subject=subject_to, name=bem_name)

        # job
        desc = "mne_prepare_bem_model for %s" % subject_to
        func = prepare_bem_model
        args = (bem_file,)
        kwargs = {}
        return (desc, func, args, kwargs)
Esempio n. 14
0
    def _children_items_changed ( self, event ):
        """ Handles changes to the 'children' trait.
        """
        for child in event.added:
            if not isinstance( child, DirectoryNode ):
                continue

            new_path = join( self.path, child.dir_name )
            if isfile( new_path ):
                error( self.handler.parent,
                       ("Cannot create the directory '%s'.\nThere is already a "
                        "file with that name.") % child.dir_name )
                return

            if not isdir( new_path ):
                try:
                    mkdir( new_path )
                except:
                    error( self.handler.parent, ("An error occurred creating "
                           "the directory '%s'") % child.dir_name )
                    return

            child.set( path = new_path, file_space = self.file_space )

            self.initialized = False
Esempio n. 15
0
    def _subject_changed(self):
        subject = self.subject
        subjects_dir = self.subjects_dir
        if not subjects_dir or not subject:
            return

        path = None
        if self.use_high_res_head:
            path = _find_high_res_head(subjects_dir=subjects_dir,
                                       subject=subject)
            if not path:
                error(None, "No high resolution head model was found for "
                      "subject {0}, using standard head instead. In order to "
                      "generate a high resolution head model, run:\n\n"
                      "    $ mne make_scalp_surfaces -s {0}"
                      "\n\n".format(subject), "No High Resolution Head")

        if not path:
            path = head_bem_fname.format(subjects_dir=subjects_dir,
                                         subject=subject)
        self.bem.file = path

        # find fiducials file
        fid_files = _find_fiducials_files(subject, subjects_dir)
        if len(fid_files) == 0:
            self.fid.reset_traits(['file'])
            self.lock_fiducials = False
        else:
            self.fid_file = fid_files[0].format(subjects_dir=subjects_dir,
                                                subject=subject)
            self.lock_fiducials = True

        # does not seem to happen by itself ... so hard code it:
        self.reset_fiducials()
Esempio n. 16
0
    def _us_error(e):
        """Display a message to the user after a UserStorageError exception has
        been raised.  If the message is empty then we assume the user has
        already been informed."""

        msg = str(e)
        if msg:
            error(None, msg)
Esempio n. 17
0
 def select_plugin(self, plugin_obj):
     # Set up image capturing
     self.camera = plugin_obj()
     try:
         self.camera.open()
     except CameraError:
         error(None, 'No camera was detected. Did you forget to plug it in?')
         sys.exit()
Esempio n. 18
0
 def delete ( self ):
     """ Deletes the associated file from the file system.
     """
     try:
         remove( self.path )
     except:
         error( self.handler.parent, "Could not delete the file '%s'" %
                                     basename( self.path )[0] )
Esempio n. 19
0
    def init_model(self, op):
        
        dtype_to_trait = {"category" : Str,
                          "float" : Float,
                          "bool" : Bool,
                          "int" : Int}
        
        for op_tube in op.tubes:
            tube = Tube(file = op_tube.file,
                        parent = self)
            
            # first load the tube's metadata and set special columns
            try:
                tube_meta = fcsparser.parse(op_tube.file, 
                                            meta_data_only = True, 
                                            reformat_meta = True)
                #tube_channels = tube_meta["_channels_"].set_index("$PnN")
            except Exception as e:
                error(None, "FCS reader threw an error on tube {0}: {1}"\
                            .format(op_tube.file, e.value),
                      "Error reading FCS file")
                return
            
            # if we're the first tube loaded, create a dummy experiment
            if not self.dummy_experiment:
                self.dummy_experiment = ImportOp(tubes = [op_tube],
                                                 conditions = op.conditions,
                                                 coarse_events = 1).apply()
                
            if '$SRC' in tube_meta:    
                self.tube_traits["$SRC"] = Str(condition = False)
                tube.add_trait("$SRC", Str(condition = False))
                tube.trait_set(**{"$SRC" : tube_meta['$SRC']})
                
            if 'TUBE NAME' in tube_meta:
                #self._add_metadata("TUBE NAME", "TUBE NAME", Str(condition = False))
                self.tube_traits["TUBE NAME"] = Str(condition = False)
                tube.add_trait("TUBE NAME", Str(condition = False))
                tube.trait_set(**{"TUBE NAME" : tube_meta['TUBE NAME']})
                
            if '$SMNO' in tube_meta:
                #self._add_metadata("$SMNO", "$SMNO", Str(condition = False))
                self.tube_traits["$SMNO"] = Str(condition = False)
                tube.add_trait("$SMNO", Str(condition = False))
                tube.trait_set(**{"$SMNO" : tube_meta['SMNO']})

            # next set conditions
            for condition in op_tube.conditions:
                condition_dtype = op.conditions[condition]
                condition_trait = \
                    dtype_to_trait[condition_dtype](condition = True)
                tube.add_trait(condition, condition_trait)
                if not condition in self.tube_traits:
                    self.tube_traits[condition] = condition_trait
            tube.trait_set(**op_tube.conditions)
            
            self.tubes.append(tube)
Esempio n. 20
0
    def _get__info(self):
        if self.file:
            info = None
            fid, tree, _ = fiff_open(self.file)
            fid.close()
            if len(dir_tree_find(tree, FIFF.FIFFB_MEAS_INFO)) > 0:
                info = read_info(self.file, verbose=False)
            elif len(dir_tree_find(tree, FIFF.FIFFB_ISOTRAK)) > 0:
                info = read_dig_montage(fif=self.file)

            if isinstance(info, DigMontage):
                info.transform_to_head()
                digs = list()
                _append_fiducials(digs, info.lpa, info.nasion, info.rpa)
                for idx, pos in enumerate(info.hsp):
                    dig = {'coord_frame': FIFF.FIFFV_COORD_HEAD,
                           'ident': idx,
                           'kind': FIFF.FIFFV_POINT_EXTRA,
                           'r': pos}
                    digs.append(dig)
                info = _empty_info(1)
                info['dig'] = digs
            elif info is None or info['dig'] is None:
                error(None, "The selected FIFF file does not contain "
                      "digitizer information. Please select a different "
                      "file.", "Error Reading FIFF File")
                self.reset_traits(['file'])
                return
            else:
                # check that all fiducial points are present
                has_point = {FIFF.FIFFV_POINT_LPA: False,
                             FIFF.FIFFV_POINT_NASION: False,
                             FIFF.FIFFV_POINT_RPA: False}
                for d in info['dig']:
                    if d['kind'] == FIFF.FIFFV_POINT_CARDINAL:
                        has_point[d['ident']] = True
                if not all(has_point.values()):
                    points = _fiducial_coords(info['dig'])
                    if len(points) == 3:
                        _append_fiducials(info['dig'], *points.T)
                    else:
                        missing = []
                        if not has_point[FIFF.FIFFV_POINT_LPA]:
                            missing.append('LPA')
                        if not has_point[FIFF.FIFFV_POINT_NASION]:
                            missing.append('Nasion')
                        if not has_point[FIFF.FIFFV_POINT_RPA]:
                            missing.append('RPA')
                        error(None, "The selected FIFF file does not contain "
                              "all cardinal points (missing: %s). Please "
                              "select a different file." % ', '.join(missing),
                              "Error Reading FIFF File")
                        self.reset_traits(['file'])
                        return

            return info
Esempio n. 21
0
    def _on_add_condition(self):
        """
        Add a new condition.  Use TraitsUI to make a simple dialog box.
        """
        
        class ValidPythonIdentifier(BaseCStr):
    
            info_text = 'a valid python identifier'
    
            def validate(self, obj, name, value):
                value = super(ValidPythonIdentifier, self).validate(obj, name, value)
                if util.sanitize_identifier(value) == value:
                    return value 
                
                self.error(obj, name, value)
        
        class NewTrait(HasTraits):    
            condition_name = ValidPythonIdentifier()
            condition_type = Enum(["Category", "Number", "True/False"])
    
            view = View(Item(name = 'condition_name'),
                        Item(name = 'condition_type'),
                        buttons = OKCancelButtons,
                        title = "Add a condition",
                        close_result = False)
            
            def _validate_condition_name(self, x):
                return util.sanitize_identifier(x)
            
        
        new_trait = NewTrait()
        new_trait.edit_traits(kind = 'modal')
        
        if not new_trait.condition_name: 
            return

        name = new_trait.condition_name
        
        if name in self.model.dummy_experiment.channels:
            error(None, 
                  "Condition \"{0}\" conflicts with a channel name.".format(name),
                  "Error adding condition")
            return
        
        if name in self.model.tube_traits:
            error(None,
                  "The experiment already has a condition named \"{0}\".".format(name),
                  "Error adding condition")
            return
        
        if new_trait.condition_type == "Category":
            self._add_metadata(name, name + " (Category)", Str(condition = True))
        elif new_trait.condition_type == "Number":
            self._add_metadata(name, name + " (Number)", Float(condition = True))
        else:
            self._add_metadata(name, name + " (T/F)", Bool(condition = True))       
Esempio n. 22
0
 def _get_inst(self):
     if self.file:
         info = read_info(self.file)
         if info['dig'] is None:
             error(None, "The selected FIFF file does not contain "
                   "digitizer information. Please select a different "
                   "file.", "Error Reading FIFF File")
             self.reset_traits(['file'])
         else:
             return info
Esempio n. 23
0
 def saveas_file(self, info):
     file = get_save_file(self.path, self.wildcard)
     if file is not None:
         try:
             self.save_object(info, file)
             self.file = file
             self.path = os.path.dirname(file)
         except BaseException, e:
             log.exception(e)
             error(info.ui.control, str(e))
 def _save_project_graphically(self, parent, project, dirname):
     """ Saves the given project to a name **dirname**.  Gives the user
     graphical feedback.
     """
     # FIXME: pop up a progress bar
     try:
         project.save(dirname)
     except Exception, e:
         pyface.error(parent=parent, message='Error while saving project:\n%s' % str(e))
         raise
Esempio n. 25
0
 def open(self):
     super(ExperimentDialog, self).open()
     
     if self.return_code == OK and not self.model.valid:
         error(None, "Invalid experiment setup.\n"
                     "Was each tube's metadata unique?",
                     "Invalid experiment!")
         self.open()
         
     return self.return_code
Esempio n. 26
0
 def on_cameras_response(self):
     info = self.cameras_dialog.get_plugin_info()
     try:
         self.select_plugin(*info)
     except ImportError:
         error(None, 'Loading the {} camera plugin failed. '
             'Taking you back to the previous one.'.format(info[0]))
         self.cameras_dialog.select_fallback()
         info = self.cameras_dialog.get_plugin_info()
         self.select_plugin(*info)
Esempio n. 27
0
 def on_cameras_response(self):
     plugin_obj = self.cameras_dialog.get_plugin_object()
     try:
         self.select_plugin(plugin_obj)
     except ImportError:
         # some module was not available, select the dummy
         error(None, 'Loading the {} camera plugin failed. '
             'Taking you back to the dummy plugin.'.format(plugin_obj['name']))
         self.cameras_dialog.select_fallback()
         info = self.cameras_dialog.get_plugin_info()
         self.select_plugin(*info)
Esempio n. 28
0
    def init_model(self, op):

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

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

        for op_tube in op.tubes:
            tube = Tube(file=op_tube.file, parent=self)

            # first load the tube's metadata and set special columns
            try:
                tube_meta = fcsparser.parse(op_tube.file, meta_data_only=True, reformat_meta=True)
                # tube_channels = tube_meta["_channels_"].set_index("$PnN")
            except Exception as e:
                error(
                    None,
                    "FCS reader threw an error on tube {0}: {1}".format(op_tube.file, e.value),
                    "Error reading FCS file",
                )
                return

            if "$SRC" in tube_meta:
                self.tube_traits["$SRC"] = Str(condition=False)
                tube.add_trait("$SRC", Str(condition=False))
                tube.trait_set(**{"$SRC": tube_meta["$SRC"]})

            if "TUBE NAME" in tube_meta:
                # self._add_metadata("TUBE NAME", "TUBE NAME", Str(condition = False))
                self.tube_traits["TUBE NAME"] = Str(condition=False)
                tube.add_trait("TUBE NAME", Str(condition=False))
                tube.trait_set(**{"TUBE NAME": tube_meta["TUBE NAME"]})

            if "$SMNO" in tube_meta:
                # self._add_metadata("$SMNO", "$SMNO", Str(condition = False))
                self.tube_traits["$SMNO"] = Str(condition=False)
                tube.add_trait("$SMNO", Str(condition=False))
                tube.trait_set(**{"$SMNO": tube_meta["SMNO"]})

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

            # if we're the first tube loaded, create a dummy experiment
            # to validate voltage, etc for later tubes
            if not self.dummy_experiment:
                self.model.dummy_experiment = ImportOp(tubes=[CytoflowTube(file=op_tube.file)], coarse_events=1).apply()

            self.tubes.append(tube)
Esempio n. 29
0
 def save_file(self, info):
     if self.file is None:
         self.saveas_file(info)
     else:
         try:
             self.save_object(info, self.file)
         except BaseException, e:
             log.exception(e)
             mesg = 'There was an error saving the file.\n'
             mesg += str(e)
             error(info.ui.control, mesg)
Esempio n. 30
0
def role_assignment():
    """Implement the role assignment for the current policy manager."""

    # Create a dictionary of roles keyed by the role name.
    all_roles = {}

    try:
        roles = get_permissions_manager().policy_manager.policy_storage.all_roles()
    except PolicyStorageError, e:
        error(None, str(e))
        return
Esempio n. 31
0
def activate_function_call(func_def):
    """ Given a function and its path (optionally), open a function-call.

        If the function is a user-defined/edited/saved function then make it
        editable. If the user edits the code of the user-function, overwrite the
        function and prompt the user to add the function. If the user does not
        edit the code of the function, just add it as other functions would be
        added.

        Parameters:
        -----------
        func_def: FunctionDefinition
            Contains the function, and its python path.

        Returns:
        --------
        edited_function: function_object
            The function that is edited.
        activated_function: function_object
            The function that must be activated.
        python_string: List[Str]
            includes import and function call to be added to a script.

    """

    if func_def.code is None:
        msg = "Perhaps your python path is not set correctly or\n" \
              "there is an error in the file (or one it imports).\n"
        error(None, msg, "Error loading function")

        return None

    # If it is a user-defined function, one would want to edit it
    # else it can remain un-editable.
    path_dir = os.path.dirname(func_def.filename)
    usr_path = os.path.join(ETSConfig.user_data, USER_MODULE_NAME)

    if path_dir == usr_path:
        # This is a user function

        # We no longer edit the function before dropping it on the canvas
        #is_ok = edit_user_function(func_def)

        # Note: If the user edits the code, one should save the
        #        code and ask the user if (s)he wants to continue
        #        adding the function to the block.
        #        If the user does not edit the code, it should be
        #        the same as it is for a regular function, that is,
        #        the user automatically adds the code to the block.
        if func_def.dirty:
            func_def.write(overwrite=True)

            # Ask for confirmation if the user has to add it to
            # block now or quit without adding.
            msg= 'The user function \'%s' % func_def.name+ \
                 '\' has been edited and overwritten at \n' + \
                 '%s \n\n'% func_def.filename + \
                 'Do you wish to add the function to the block?'

            if confirm(None, msg) == YES:
                return func_def
            else:
                return None

        else:
            return func_def

    else:
        # This is a sys function which we are trying to override as a new user func
        # We no longer edit the function before dropping it on the canvas
        #is_ok = edit_sys_function(func_def)

        if func_def.dirty:
            func_def.write(overwrite=False)

            # Ask for confirmation if the user has to add it to
            # block now or quit without adding.
            msg= 'The user function \'%s' % func_def.name+ \
                 '\' has been written at \n' + \
                 '%s \n\n'% func_def.filename + \
                 'Do you wish to add the function to the block?'

            if confirm(None, msg) == YES:
                return func_def
            else:
                return None

        else:
            return func_def

    return None
Esempio n. 32
0
 def Reload(self, info):
     try:
         self.saveObject.load()
     except:
         error(None, 'Error Loading file.', title='Error')
        return

    logger.debug("Exporting {} datasets exported to {}.".format(
        len(log_dfs), target_file))
    df = pd.concat(log_dfs, axis=1)
    df.to_csv(target_file)
    logger.debug("Data exported to {}.".format(target_file))


central_pane = task.central_pane
active_chrom_plot = central_pane.active_editor.obj
if not isinstance(active_chrom_plot, ChromatogramModel):
    msg = "Active tab is not a plot. Please select the plot you want to " \
          "export and run again."
    logger.exception(msg)
    error(None, msg)
else:
    export_path = to_csv_file_requester()
    if export_path is not None:
        export_ext = splitext(export_path)[1]
        if not export_ext:
            export_path += ".csv"

    abort = False
    # Only confirm on windows, since on Mac, the FileDialog has this builtin.
    if exists(export_path) and IS_WINDOWS:
        result = confirm(None, "The file already exists: overwrite?")
        if result == NO:
            abort = True

    if export_path and not abort:
Esempio n. 34
0
def error(owner, msg):
    print "Exception caught, message: %s" % (msg)
    general.printException()
    pyfaceapi.error(owner, msg)
Esempio n. 35
0
    def open_file(self, path):
        f = open(path, 'r')
        unpickler = pickle.Unpickler(f)

        try:
            version = unpickler.load()
        except TraitError:
            error(parent=None,
                  message="This doesn't look like a Cytoflow file. Or maybe "
                  "you tried to load a workflow older than version "
                  "0.5?")
            return

        if version != self.model.version:
            ret = confirm(
                parent=None,
                message="This is Cytoflow {}, but you're trying "
                "to load a workflow from version {}. This may or "
                "may not work!  Are you sure you want to proceed?".format(
                    self.model.version, version),
                title="Load workflow?")
            if ret != YES:
                return

        try:
            new_workflow = unpickler.load()
        except TraitError:
            error(parent=None, message="Error trying to load the workflow.")
            return

        # a few things to take care of when reloading
        for wi_idx, wi in enumerate(new_workflow):
            # clear the wi status
            wi.status = "invalid"

            # re-link the linked list.  i thought this would get taken care
            # of in deserialization, but i guess not...
            if wi_idx > 0:
                wi.previous = new_workflow[wi_idx - 1]

            # reload the subset lists.  i don't know why this is necessary.
            for view in wi.views:
                subset_list = view.subset_list
                view.subset_list = []
                for s in subset_list:
                    view.subset_list.append(s)

            subset_list = wi.operation.subset_list
            wi.operation.subset_list = []
            for s in subset_list:
                wi.operation.subset_list.append(s)

        # replace the current workflow with the one we just loaded

        if False:  # for debugging the loading of things
            from event_tracer import record_events

            with record_events() as container:
                self.model.workflow = new_workflow

            container.save_to_directory(os.getcwd())
        else:
            self.model.workflow = new_workflow
            self.model.modified = False
Esempio n. 36
0
 def show_error(self, error_string):
     error(
         None,
         "An exception has occurred.  Please report a problem from the Help menu!\n\n"
         "Afterwards, may need to restart Cytoflow to continue working.\n\n"
         + error_string)
Esempio n. 37
0
    def open_file(self, path):
        
        try:
            new_workflow = load_yaml(path)

            # a few things to take care of when reloading.
            # we do this in the try block to catch people who
            # load valid YAML files that aren't from cytoflow.
            
            for wi_idx, wi in enumerate(new_workflow):
                
                # get wi lock
                wi.lock.acquire()
                
                # clear the wi status
                wi.status = "loading"
    
                # re-link the linked list.
                if wi_idx > 0:
                    wi.previous_wi = new_workflow[wi_idx - 1]
                
                if wi_idx < len(new_workflow) - 1:
                    wi.next_wi = new_workflow[wi_idx + 1]

        except yaml.parser.ParserError as e:
            error(None,
                  "Parser error loading {} -- is it a Cytoflow file?\n\n{}"
                  .format(path, str(e)))
            return
        except Exception as e:
            error(None,
                  "{} loading {} -- is it a Cytoflow file?\n\n{}"
                  .format(e.__class__.__name__, path, str(e)))
            return
        
        # are we just running a smoke test?
        if 'startup_test' in new_workflow[0].metadata:
            def quit_app(app):
                app.exit(force = True)
                
            from pyface.timer.api import do_after
            do_after(5*1000, quit_app, self.application)
            return
            
        # check that the FCS files are all there
        
        wi = new_workflow[0]
        assert(wi.operation.id == "edu.mit.synbio.cytoflow.operations.import")
        missing_tubes = 0
        for tube in wi.operation.tubes:
            file = pathlib.Path(tube.file)
            if not file.exists():
                missing_tubes += 1
                
        if missing_tubes == len(wi.operation.tubes):
            warning(self.window.control,
                    "Cytoflow couldn't find any of the FCS files from that "
                    "workflow.  If they've been moved, please open one FCS "
                    "file to show Cytoflow where they've been moved to.")
            
            dialog = FileDialog(parent = self.window.control, 
                                action = 'open',
                                wildcard = (FileDialog.create_wildcard("FCS files", "*.fcs *.lmd")))  # @UndefinedVariable
            
            if dialog.open() == OK:
                # find the "best" file match -- ie, the one with the longest
                # tail match
                fcs_path = pathlib.Path(dialog.path).parts
                best_path_len = -1
                                
                for tube in wi.operation.tubes:
                    tube_path = pathlib.Path(tube.file).parts
                    
                    for i in range(len(fcs_path)):
                        if list(reversed(fcs_path))[:i] == list(reversed(tube_path))[:i] and i > best_path_len:
                            best_path_len = i
                            
                if best_path_len >= 0:
                    for tube in wi.operation.tubes:
                        tube_path = pathlib.Path(tube.file).parts
                        new_path = fcs_path[:-1 * best_path_len] + tube_path[-1 * best_path_len :]
                        tube.file = str(pathlib.Path(*new_path))
                        
        elif missing_tubes > 0:
            warning(self.window.control,
                    "Cytoflow couldn't find some of the FCS files from that "
                    "workflow.  You'll need to re-load them from the Import "
                    "operation.")

        # replace the current workflow with the one we just loaded
        
        if False:  # for debugging the loading of things
            from cytoflowgui.utility.event_tracer import record_events 
            
            with record_events() as container:
                self.model.workflow = new_workflow
                                
            container.save_to_directory(os.getcwd()) 
        else:
            self.model.workflow = new_workflow
            self.model.modified = False
            
        for wi in self.model.workflow:
            wi.lock.release()
            
        if self.model.debug:
            self.model.run_all()
        else:
            ret = confirm(parent = None,
                          message = "Do you want to execute the workflow now?",
                          title = "Run workflow?")
            
            if ret == YES:
                self.model.run_all()
Esempio n. 38
0
    def _get__info(self):
        if self.file:
            info = None
            _, tree, _ = fiff_open(self.file)
            if len(dir_tree_find(tree, FIFF.FIFFB_MEAS_INFO)) > 0:
                info = read_info(self.file, verbose=False)
            elif len(dir_tree_find(tree, FIFF.FIFFB_ISOTRAK)) > 0:
                info = read_dig_montage(fif=self.file)

            if info is None:
                error(None, "The selected FIFF file does not contain "
                      "digitizer information. Please select a different "
                      "file.", "Error Reading FIFF File")
                self.reset_traits(['file'])
                return
            elif isinstance(info, DigMontage):
                info.transform_to_head()
                digs = list()
                digs.append({'coord_frame': FIFF.FIFFV_COORD_HEAD,
                             'ident': FIFF.FIFFV_POINT_LPA,
                             'kind': FIFF.FIFFV_POINT_CARDINAL,
                             'r': info.lpa})
                digs.append({'coord_frame': FIFF.FIFFV_COORD_HEAD,
                             'ident': FIFF.FIFFV_POINT_NASION,
                             'kind': FIFF.FIFFV_POINT_CARDINAL,
                             'r': info.nasion})
                digs.append({'coord_frame': FIFF.FIFFV_COORD_HEAD,
                             'ident': FIFF.FIFFV_POINT_RPA,
                             'kind': FIFF.FIFFV_POINT_CARDINAL,
                             'r': info.rpa})
                for idx, pos in enumerate(info.hsp):
                    dig = {'coord_frame': FIFF.FIFFV_COORD_HEAD,
                           'ident': idx,
                           'kind': FIFF.FIFFV_POINT_EXTRA,
                           'r': pos}
                    digs.append(dig)
                info = _empty_info(1)
                info['dig'] = digs
            else:
                # check that all fiducial points are present
                has_point = {FIFF.FIFFV_POINT_LPA: False,
                             FIFF.FIFFV_POINT_NASION: False,
                             FIFF.FIFFV_POINT_RPA: False}
                for d in info['dig']:
                    if d['kind'] == FIFF.FIFFV_POINT_CARDINAL:
                        has_point[d['ident']] = True
                if not all(has_point.values()):
                    missing = []
                    if not has_point[FIFF.FIFFV_POINT_LPA]:
                        missing.append('LPA')
                    if not has_point[FIFF.FIFFV_POINT_NASION]:
                        missing.append('Nasion')
                    if not has_point[FIFF.FIFFV_POINT_RPA]:
                        missing.append('RPA')
                    error(None, "The selected FIFF file does not contain "
                          "all cardinal points (missing: %s). Please select a "
                          "different file." % ', '.join(missing),
                          "Error Reading FIFF File")
                    self.reset_traits(['file'])
                    return

            return info
Esempio n. 39
0
 def perform(self, event=None):
     """ Open a URL in a web browser. """
     try:
         webbrowser.open(self.url)
     except webbrowser.Error as exc:
         error(None, str(exc))
Esempio n. 40
0
    def init_model(self, op):

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

        new_tubes = []
        for op_tube in op.tubes:
            tube = Tube(file=op_tube.file, parent=self)

            # first load the tube's metadata and set special columns
            try:
                tube_meta = fcsparser.parse(op_tube.file,
                                            meta_data_only=True,
                                            reformat_meta=True)
                #tube_channels = tube_meta["_channels_"].set_index("$PnN")
            except Exception as e:
                error(None, "FCS reader threw an error on tube {0}: {1}"\
                            .format(op_tube.file, e.value),
                      "Error reading FCS file")
                return

            # if we're the first tube loaded, create a dummy experiment
            if not self.dummy_experiment:
                self.dummy_experiment = ImportOp(tubes=[op_tube],
                                                 conditions=op.conditions,
                                                 coarse_events=1).apply()

            if '$SRC' in tube_meta:
                self.tube_traits["$SRC"] = Str(condition=False)
                tube.add_trait("$SRC", Str(condition=False))
                tube.trait_set(**{"$SRC": tube_meta['$SRC']})

            if 'TUBE NAME' in tube_meta:
                self.tube_traits["TUBE NAME"] = Str(condition=False)
                tube.add_trait("TUBE NAME", Str(condition=False))
                tube.trait_set(**{"TUBE NAME": tube_meta['TUBE NAME']})

            if '$SMNO' in tube_meta:
                self.tube_traits["$SMNO"] = Str(condition=False)
                tube.add_trait("$SMNO", Str(condition=False))
                tube.trait_set(**{"$SMNO": tube_meta['SMNO']})

            if 'WELL ID' in tube_meta:
                pos = tube_meta['WELL ID']
                row = pos[0]
                col = int(pos[1:3])

                self.tube_traits["Row"] = Str(condition=False)
                self.tube_traits["Col"] = Int(condition=False)
                tube.add_trait("Row", Str(condition=False))
                tube.add_trait("Col", Int(condition=False))
                tube.trait_set(**{"Row": row, "Col": col})

            # next set conditions
            try:
                conditions_list = op_tube.conditions_list
            except:
                conditions_list = list(op_tube.conditions.keys())

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

            new_tubes.append(tube)

        self.tubes.extend(new_tubes)
Esempio n. 41
0
    def error(msg):
        """Display an error message to the user."""

        error(None, msg)
Esempio n. 42
0
    # Private interface.
    ###########################################################################

    def _select_user(self, name):
        """Select a user returning the data as a tuple of name and description.
        """

        # Get all users that satisfy the criteria.
        try:
            users = self.user_storage.matching_users(name)
        except UserStorageError, e:
            self._us_error(e)
            return '', ''

        if len(users) == 0:
            error(None, "There is no user that matches \"%s\"." % name)
            return '', ''

        return select_user(users)

    @staticmethod
    def _us_error(e):
        """Display a message to the user after a UserStorageError exception has
        been raised.  If the message is empty then we assume the user has
        already been informed."""

        msg = str(e)
        if msg:
            error(None, msg)

Esempio n. 43
0
    def _on_add_tubes(self):
        """
        Handle "Add tubes..." button.  Add tubes to the experiment.
        """

        file_dialog = FileDialog()
        file_dialog.wildcard = "Flow cytometry files (*.fcs)|*.fcs|"
        file_dialog.action = 'open files'
        file_dialog.open()

        if file_dialog.return_code != PyfaceOK:
            return

        new_tubes = []
        for path in file_dialog.paths:
            try:
                tube_meta = fcsparser.parse(path,
                                            meta_data_only=True,
                                            reformat_meta=True)
                #tube_channels = tube_meta["_channels_"].set_index("$PnN")
            except Exception as e:
                raise RuntimeError("FCS reader threw an error on tube {0}: {1}"\
                                   .format(path, e.value))

            # if we're the first tube loaded, create a dummy experiment
            if not self.model.dummy_experiment:
                self.model.dummy_experiment = ImportOp(
                    tubes=[CytoflowTube(file=path)], coarse_events=1).apply()

            # check the next tube against the dummy experiment
            try:
                check_tube(path, self.model.dummy_experiment)
            except util.CytoflowError as e:
                error(None, e.__str__(), "Error importing tube")
                return

            tube = Tube()

            for trait_name, trait in list(self.model.tube_traits.items()):
                tube.add_trait(trait_name, trait)

                # this magic makes sure the trait is actually defined
                # in tube.__dict__, so it shows up in trait_names etc.
                tube.trait_set(**{trait_name: trait.default_value})
                if trait.condition:
                    tube.on_trait_change(self._try_multiedit, trait_name)

            tube.trait_set(file=path, parent=self.model)

            if '$SRC' in tube_meta:
                self._add_metadata("$SRC", "$SRC", Str(condition=False))
                tube.trait_set(**{"$SRC": tube_meta['$SRC']})

            if 'TUBE NAME' in tube_meta:
                self._add_metadata("TUBE NAME", "TUBE NAME",
                                   Str(condition=False))
                tube.trait_set(**{"TUBE NAME": tube_meta['TUBE NAME']})

            if '$SMNO' in tube_meta:
                self._add_metadata("$SMNO", "$SMNO", Str(condition=False))
                tube.trait_set(**{"$SMNO": tube_meta['$SMNO']})

            if 'WELL ID' in tube_meta:
                self._add_metadata("Row", "Row", Str(condition=False))
                self._add_metadata("Col", "Col", Int(condition=False))

                pos = tube_meta['WELL ID']
                row = pos[0]
                col = int(pos[1:3])

                tube.trait_set(**{"Row": row, "Col": col})

            new_tubes.append(tube)

        self.model.tubes.extend(new_tubes)
Esempio n. 44
0
    def _ps_error(e):
        """Display a message to the user after a PolicyStorageError exception
        has been raised."""

        error(None, str(e))
Esempio n. 45
0
def error(msg, parent=None):
    """Handle an error message.
    """
    logger.error(msg)
    if pyface is not None:
        pyface.error(parent, msg)