def _get_raw(self): if not self.sqd_file: return try: return RawKIT(self.sqd_file, stim=None, allow_unknown_format=self.allow_unknown_format) except UnsupportedKITFormat as exception: warning( None, "The selected SQD file is written in an old file format (%s) " "that is not officially supported. Confirm that the results " "are as expected. This warning is displayed only once per " "session." % (exception.sqd_version, ), "Unsupported SQD File Format") self.allow_unknown_format = True return self._get_raw() except Exception as err: self.reset_traits(['sqd_file']) 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
def request_new_simulation_group(self, sim=None): """ Create a new SimulationGroup around a center point simulation that already exists. """ from kromatography.ui.simulation_group_builder import \ SimulationGroupBuilder builder = SimulationGroupBuilder(center_point_simulation=sim, target_study=self) ui = builder.edit_traits(kind='livemodal') if not ui.result: return group = builder.build_group() if group.size == 0: msg = "No parameter was chosen. No grid created." logger.warning(msg) warning(None, msg) return if group.type == SIM_GROUP_GRID_TYPE: self.analysis_tools.simulation_grids.append(group) elif group.type == SIM_GROUP_MC_TYPE: self.analysis_tools.monte_carlo_explorations.append(group) else: msg = "Group type {} not supported" logger.exception(msg) raise NotImplementedError(msg) return group
def to_simulation(self): """ Returns a new Simulation object from current builder. """ from kromatography.model.factories.method import \ build_sim_method_from_method sim_method = build_sim_method_from_method( self.method, self.first_simulated_step_name, self.last_simulated_step_name, initial_buffer=self.initial_buffer, ) simulation = Simulation( name=self.simulation_name, column=self.column, method=sim_method, first_simulated_step=self.first_simulated_step_name, last_simulated_step=self.last_simulated_step_name, transport_model=self.transport_model, binding_model=self.binding_model, solver=Solver(), discretization=Discretization(), sensitivity=Sensitivity(), ) # Product is a property of a simulation, which isn't set until we set # the method. if not is_has_traits_almost_equal(simulation.product, self.product): msg = ("The simulation's product (read in the method) doesn't " "match the selected product. Please review the product and" " method selected.") logger.info(msg) warning(None, msg, "Review simulation data") return simulation
def velocity(self,tempo): tempo=round(tempo,3) if tempo<0.010 or tempo>666.666: warning(parent=None, title="warning", message="falscher Wert fuer die velocity: sie muss zwischen 0.010 und 666.666 nm/min liegen") #main.input_nm=500.0 else: self.write(str(tempo)+ " NM/MIN \r") print self.readline()
def _check_backend(): from pyface.api import warning backend = _get_pyface_backend() if backend == 'qt4': _check_pyqt5_version() else: msg = ("Using the currently selected Pyface backend %s is not " "recommended, and it might not work properly. We recommend " "using 'qt4' which can be enabled by installing the PyQt5" "package." % backend) warn(msg) warning(None, msg, "Pyface Backend Warning")
def _n_scale_params_changed(self, new): if not new: return # Make sure that MNE_ROOT environment variable is set if not set_mne_root(True): err = ( "MNE_ROOT environment variable could not be set. " "You will be able to scale MRIs, but the " "mne_prepare_bem_model tool will fail. Please install " "MNE." ) warning(None, err, "MNE_ROOT Not Set")
def _on_exit(self): """ Called when the exit action is invoked. """ parent = self.control information(parent, 'Going...') warning(parent, 'Going......') error(parent, 'Gone!') if confirm(parent, 'Should I exit?') == YES: self.close() return
def _on_exit(self): """ Called when the exit action is invoked. """ parent = self.control print((choose_one(parent, "Make a choice", ['one', 'two', 'three']))) information(parent, 'Going...') warning(parent, 'Going......') error(parent, 'Gone!') if confirm(parent, 'Should I exit?') == YES: self.close()
def _on_exit(self): """ Called when the exit action is invoked. """ parent = self.control print(choose_one(parent, "Make a choice", ["one", "two", "three"])) information(parent, "Going...") warning(parent, "Going......") error(parent, "Gone!") if confirm(parent, "Should I exit?") == YES: self.close()
def _on_exit(self): """ Called when the exit action is invoked. """ parent = self.control print(choose_one(parent, "Make a choice", ['one', 'two', 'three'])) information(parent, 'Going...') warning(parent, 'Going......') error(parent, 'Gone!') if confirm(parent, 'Should I exit?') == YES: self.close()
def _on_import(self): """ Import format: CSV, first column is filename, path relative to CSV. others are conditions, type is autodetected. first row is header with names. """ file_dialog = FileDialog() file_dialog.wildcard = "CSV files (*.csv)|*.csv|" file_dialog.action = 'open' file_dialog.open() if file_dialog.return_code != PyfaceOK: return csv = pandas.read_csv(file_dialog.path) csv_folder = Path(file_dialog.path).parent if self.model.tubes or self.model.tube_traits: if confirm( parent=None, message="This will clear the current conditions and tubes! " "Are you sure you want to continue?", title="Clear tubes and conditions?") != YES: return for col in csv.columns[1:]: self.model.tube_traits.append( TubeTrait(model=self.model, name=util.sanitize_identifier(col), type='category')) for _, row in csv.iterrows(): filename = csv_folder / row[0] try: metadata, _ = parse_tube(str(filename), metadata_only=True) except Exception as e: warning( None, "Had trouble loading file {}: {}".format(filename, str(e))) continue metadata['CF_File'] = Path(filename).stem new_tube = Tube(file=str(filename), parent=self.model, metadata=sanitize_metadata(metadata)) self.model.tubes.append(new_tube) for col in csv.columns[1:]: new_tube.trait_set(**{util.sanitize_identifier(col): row[col]})
def raise_dlg_if_failed_plots(self): """ If some plots couldn't be rebuilt in the model, issue a warning. """ if self.model.failed_plots: error_msgs = [] for desc in self.model.failed_plots: msg = "Failed to recreate plot number {} ({} of '{}' vs '{" \ "}', z_col '{}'). It will need to be recreated manually." msg = msg.format(desc.id, desc.plot_type, desc.x_col_name, desc.y_col_name, desc.z_col_name) error_msgs.append(msg) msg = "\n\n".join(error_msgs) warning(None, msg)
def warn_if_selection_hidden(self): """ Pop up warning msg if some of the selected rows aren't displayed. """ if not self.warn_if_sel_hidden: return if not self.model.selected_idx: return truncated = len(self.model.displayed_df) < len(self.model.filtered_df) max_displayed = self.model.displayed_df.index.max() some_selection_hidden = max(self.model.selected_idx) > max_displayed if truncated and some_selection_hidden: warning(None, self.hidden_selection_msg, "Hidden selection")
def _check_backend(): from pyface.api import warning backend = _get_pyface_backend() if backend == 'qt4': _check_pyqt5_version() # QT 5 macOS 11 compatibility: if sys.platform == 'darwin' and 'QT_MAC_WANTS_LAYER' not in os.environ: os.environ['QT_MAC_WANTS_LAYER'] = '1' else: msg = ("Using the currently selected Pyface backend %s is not " "recommended, and it might not work properly. We recommend " "using 'qt4' which can be enabled by installing the PyQt5" "package." % backend) warn(msg) warning(None, msg, "Pyface Backend Warning")
def init(self, import_op): if 'CF_File' not in import_op.conditions: self.tube_traits.append( TubeTrait(model=self, type='metadata', name='CF_File')) for name, condition in import_op.conditions.items(): if condition == "category" or condition == "object": self.tube_traits.append( TubeTrait(model=self, name=name, type='category')) elif condition == "int" or condition == "float": self.tube_traits.append( TubeTrait(model=self, name=name, type='float')) elif condition == "bool": self.tube_traits.append( TubeTrait(model=self, name=name, type='bool')) self.dummy_experiment = None if import_op.tubes: try: self.dummy_experiment = import_op.apply(metadata_only=True, force=True) except Exception as e: warning( None, "Had trouble loading some of the experiment's FCS " "files. You will need to re-add them.\n\n{}".format( str(e))) return for op_tube in import_op.tubes: metadata = self.dummy_experiment.metadata['fcs_metadata'][ op_tube.file] tube = Tube(file=op_tube.file, parent=self, metadata=sanitize_metadata(metadata)) self.tubes.append(tube) # adds the dynamic traits to the tube tube.trait_set(**op_tube.conditions) for trait in self.tube_traits: if trait.type == 'metadata': tube.trait_set( **{trait.name: tube.metadata[trait.name]}) else: tube.conditions[trait.name] = tube.trait_get()[ trait.name]
def dialog_multi_import(self, parent_window=None): """Multi file import Open dialog for selecting multiple files. Shows a settings dialog for each selected file return a list of imported DataSet's """ self._last_open_path = conf.get_option('work_dir') logger.debug('Last imported file: %s', self._last_open_path) # Show info about legal data format if not self._notice_shown: notice = ImportNotice() notice.edit_traits() self._notice_shown = True # Select files status = self._show_file_selector() if status == CANCEL: logger.info('Cancel file imports') return [] datasets = [] logger.debug('File(s) to import: \n%s', '\n'.join(self._files_path)) for file_n in self._files_path: importer = self._make_importer(file_n) logger.info('Attempting to import %s with %s', file_n, type(importer)) ui = importer.edit_traits() if ui.result: ds = importer.import_data() if ds.values.dtype.type is _np.object_: logger.warning( 'Importing matrix with non-numeric values: {}'.format( ds.display_name)) if parent_window is not None: warning( parent_window, 'This matrix contains non-numeric values. The statistical methods is not able to handle non-numeric categorical variables' ) datasets.append(ds) else: continue conf.set_option('work_dir', file_n) return datasets
def open_project_from_file(self, path): """ Open a saved task from a project file. """ from kromatography.io.task import load_project path = os.path.abspath(path) self.add_to_recent_files(path) already_open = self.activate_window_if_already_open(path) if already_open: msg = "Project {} already loaded.".format(path) logger.info(msg) else: try: task, legacy_file = load_project(path) except Exception as e: msg = ("The object found in {} didn't load successfully. Error" " was {}".format(path, e)) logger.exception(msg) error(None, msg) raise IOError(msg) if not isinstance(task, KromatographyTask): msg = "The object found in {} is not a {} project but a {}" msg = msg.format(path, APP_TITLE, type(task)) logger.exception(msg) error(None, msg) raise IOError(msg) self._finalize_task_and_open_task_window(task) if legacy_file and self.warn_if_old_file: from pyface.api import warning from ..ui.tasks.kromatography_task import KROM_EXTENSION msg = "The file {} doesn't use the newest {} format. It is " \ "recommended to re-save the project to ensure future " \ "readability." msg = msg.format(path, KROM_EXTENSION) warning(None, msg) if self.auto_close_empty_windows_on_open: self.close_empty_windows() return task
def to_simulations(self): """ Returns a list of simulations built from each experiment selected. """ fstep, lstep = (self.first_simulated_step_name, self.last_simulated_step_name) new_simulations = [] for exp_name, sim_name in zip(self.experiment_selected, self.simulation_names): experiment = self.target_study.search_experiment_by_name(exp_name) try: sim_method = build_sim_method_from_method( experiment.method, fstep, lstep, initial_buffer=self.initial_buffer, ) except StepLookupError as e: msg = "Failed to find the start/stop method steps for " \ "simulation {}. Its experiment doesn't seem to contain" \ " {} or {}. Please review these step names or treat " \ "this simulation separately from the others. Aborting..." msg = msg.format(sim_name, fstep, lstep) details = " Details: error was {}".format(e) logger.error(msg + details) warning(None, msg) return [] simulation = Simulation( name=sim_name, column=experiment.column.clone_traits(copy="deep"), method=sim_method, first_simulated_step=self.first_simulated_step_name, last_simulated_step=self.last_simulated_step_name, transport_model=self.transport_model, binding_model=self.binding_model, source_experiment=experiment, solver=Solver(), discretization=Discretization(), sensitivity=Sensitivity(), ) new_simulations.append(simulation) return new_simulations
def _check_backend(): try: from pyface.api import warning except ImportError: def warning(a, msg, title): warn(msg) backend, status = _check_pyface_backend() if status == 0: return elif status == 1: msg = ("The currently selected Pyface backend %s has not been " "extensively tested. We recommend using qt4 which can be " "enabled by installing the pyside package. If you proceed with " "the current backend pease let the developers know your " "experience." % backend) elif status == 2: msg = ("The currently selected Pyface backend %s has known issues. We " "recommend using qt4 which can be enabled by installing the " "pyside package." % backend) warning(None, msg, "Pyface Backend Warning")
def _check_backend(): from ..utils import _check_pyface_backend try: from pyface.api import warning except ImportError: warning = None backend, status = _check_pyface_backend() if status == 0: return elif status == 1: msg = ("The currently selected Pyface backend %s has not been " "extensively tested. We recommend using qt4 which can be " "enabled by installing the pyside package. If you proceed with " "the current backend pease let the developers know your " "experience." % backend) elif status == 2: msg = ("The currently selected Pyface backend %s has known issues. We " "recommend using qt4 which can be enabled by installing the " "pyside package." % backend) warning(None, msg, "Pyface Backend Warning")
def update_import_op(self, import_op): if not self.tubes: return assert self.dummy_experiment is not None conditions = { trait.name: trait.type for trait in self.tube_traits if trait.type != 'metadata' } tubes = [] events = 0 for tube in self.tubes: op_tube = CytoflowTube(file=tube.file, conditions=tube.trait_get( list(conditions.keys()))) tubes.append(op_tube) events += tube.metadata['TOT'] import_op.ret_events = events import_op.conditions = conditions import_op.tubes = tubes import_op.original_channels = channels = self.dummy_experiment.channels all_present = len(import_op.channels_list) > 0 if len(import_op.channels_list) > 0: for c in import_op.channels_list: if c.name not in channels: all_present = False if not all_present: warning( None, "Some of the operation's channels weren't found in " "these FCS files. Resetting all channel names.", "Resetting channel names") if not all_present: import_op.reset_channels()
def _get_raw(self): if not self.sqd_file: return try: return RawKIT(self.sqd_file, stim=None, allow_unknown_format=self.allow_unknown_format) except UnsupportedKITFormat as exception: warning( None, "The selected SQD file is written in an old file format (%s) " "that is not officially supported. Confirm that the results " "are as expected. This warning is displayed only once per " "session." % (exception.sqd_version,), "Unsupported SQD File Format") self.allow_unknown_format = True return self._get_raw() except Exception as err: self.reset_traits(['sqd_file']) 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
def check_dependencies(): ''' check the dependencies and ''' from pyface.api import warning try: mod = __import__('uncertainties', fromlist=['__version__'] ) __version__ = mod.__version__ except ImportError: warning(None, 'Install "{}" package. required version>={} '.format('uncertainties', '2.1')) return vargs = __version__.split('.') maj = vargs[0] if int(maj) < 2: warning(None, 'Update "{}" package. your version={}. required version>={} '.format('uncertainties', __version__, '2.1' )) return return True
def check_dependencies(): """ check the dependencies and """ from pyface.api import warning for mod, req in (('uncertainties', '2.1'), ('pint', '0.5')): try: mod = __import__(mod) ver = mod.__version__ except ImportError: warning(None, 'Install "{}" package. required version>={} '.format(mod, req)) return vargs = ver.split('.') maj = int(vargs[0]) if maj < int(float(req)): warning(None, 'Update "{}" package. your version={}. required version>={} '.format(mod, maj, req)) return return True
def warning(msg, parent=None): """Handle a warning message. """ logger.warn(msg) if pyface is not None: pyface.warning(parent, msg)
def save_data_file(sourceFile, destination=None, subdirectory=None, user=None, verbose=True): """ Function used to save (i.e copy) a data file into a directory of choice after an experimental session Parameters: sourceFile - the path of the file that was generated by the experimental session and that resides in the local file system. destination - An optional destination path where to save the file. File name may be included or not at the end of the path. subdirectory - An optional subdirectory, i.e folder, to add to the destination path. For example, if the destination path is a folder called "experiments", the subdirectory can be a child folder of "experiments", named after the experiment type ("behaviour" for instance). user - An optional parameter to indicate which user is conducting the experiments. If supplied, and if no destination is passed, a configuration file is looked up to retrieve the folder into which the user is usually copying data files. If no destination and no user is provided, a default directory is looked up in the configuration file as the default destination of the file to be copied. Either way, a save as dialog box will appear and the user will have final say. """ # Validate file parameter passed. Also check to see if the path provided is lacking the default .h5 extension if not os.path.exists(sourceFile): if not os.path.exists(sourceFile + ".h5"): # Error message if the source file path could not be found in the system error(None,"Woah there!\n\n1. Couldn't find the file that you want to copy.\ \n2. Check to see if it exists in the file system and the path provided is correct"\ , "File Finding Police report") return else: # File exists but has an extension and one was not provided in the path given. # Add it to file path descriptor sourceFile += ".h5" # information(None, "the filename of source provided lacked the \".h5\" extension.\ # \n\nA file with the extension was found and presumed to be the source meant"\ # ,"Path Police report") # Get file extension fileExtension = os.path.splitext(sourceFile)[-1] # Get the destination file name from the path provided destinationFile = os.path.split(sourceFile)[-1] destinationFolder = "" # If file has no extension, add the default .h5 extension to destination file name if fileExtension == "": warning(None, "The file you are trying to save has no extension\n\nAdding \".h5\" to the name of destination file"\ , ".h5 Extension Police") destinationFile = file + ".h5" # The file provided has different extension. Display a warning but do nothing. elif fileExtension != ".h5": warning(None, "Your file to be copied does not have an \".h5\" extension\n\nNo action taken."\ , "h5 Extension Police") # Display confirmation dialog for copying the file dlg = ConfirmationDialog( title="You there!", yes_label="Yes Please!", no_label="Nah...", message= "Would you like to copy the data file generated after the session?\ \n\nIf you say Nah... and change your mind, you'll have to copy it manually later" ) # Open the dialog GUI dlg.open() # User provided a destination path if destination: # Check to see if destination is a file name with an extension. destinationExtension = os.path.splitext(destination)[-1] if destinationExtension: # Is it .h5? If not, warn but don't override. if destinationExtension != ".h5": warning(None, "Your destination filename does not have an \".h5\" extension\n\nNo action taken."\ , "h5 Extension Police") destinationFolder, destinationFile = os.path.split(destination) # Assume destination is directory since there is no extension. else: destinationFolder = destination # Look up a default destination from the config file since no <destination> parameter was provided. else: configFile = os.environ.get("Voyeur_config") config = ConfigObj(configFile) # A user specific folder was provided. if user: destinationFolder = config['server']['folder']['data']['user'] # Use default data folder as read from the config file. else: destinationFolder = config['server']['folder']['data']['default'] # User provided a subdirectory, i.e subfolder, into which to place the file. if subdirectory: # The subdirectory provided has common path with the directory provided. Display warning but do nothing. if os.path.commonprefix((destination, subdirectory)): warning(None, "Friendly warning!\n<subdirectory> parameter provided has a common path with the <destination>\ path parameter\n\n1. No action taken.\n2. Check your final destination path to make sure it is what you want"\ , "Path Police report") destinationFolder = os.path.join(destinationFolder, subdirectory) # Path of the destination of file to be copied. destinationPath = os.path.join(destinationFolder, destinationFile) if dlg.return_code == YES: # A file with same name exists. if os.path.isfile(destinationPath): warning( None, "A file with given path already exists!\n\n1. No action taken\ \n2. Make sure to either rename file or choose different folder", "Path Police report") # Provided folder does not exist. Make one and inform the user. elif not os.path.isdir(destinationFolder): information(None, "Making a new folder to put the file into...", "Information Transparency report") # TODO: What if this results in an exception? Catch and do something? # TODO: Keep track of made directories so we may delete them later os.makedirs(os.path.abspath(destinationFolder)) # The save as dialog box. # TODO: change wildcard to current extension wildcard dialog = FileDialog(action="save as", title = "Select directory into which the data file will be copied",\ wildcard = "*.*", default_directory = destinationFolder, default_filename = destinationFile) #*.h5||| elif dlg.return_code == NO and verbose: information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\ , "Information Transparency report") return dialog.open() # User clicked Save and successful input received. if dialog.return_code == OK: # The actual copying of the file. TODO: See if the copy2 function throws an exception copy2(sourceFile, dialog.path) # The user clicked Cancel. elif dialog.return_code == CANCEL: information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\ , "Information Transparency report") #TODO: update the Voyeur config file after asking user return dialog.path
def save_data_file(sourceFile, destination = None, subdirectory = None, user = None, verbose = True): """ Function used to save (i.e copy) a data file into a directory of choice after an experimental session Parameters: sourceFile - the path of the file that was generated by the experimental session and that resides in the local file system. destination - An optional destination path where to save the file. File name may be included or not at the end of the path. subdirectory - An optional subdirectory, i.e folder, to add to the destination path. For example, if the destination path is a folder called "experiments", the subdirectory can be a child folder of "experiments", named after the experiment type ("behaviour" for instance). user - An optional parameter to indicate which user is conducting the experiments. If supplied, and if no destination is passed, a configuration file is looked up to retrieve the folder into which the user is usually copying data files. If no destination and no user is provided, a default directory is looked up in the configuration file as the default destination of the file to be copied. Either way, a save as dialog box will appear and the user will have final say. """ # Validate file parameter passed. Also check to see if the path provided is lacking the default .h5 extension if not os.path.exists(sourceFile): if not os.path.exists(sourceFile+".h5"): # Error message if the source file path could not be found in the system error(None,"Woah there!\n\n1. Couldn't find the file that you want to copy.\ \n2. Check to see if it exists in the file system and the path provided is correct"\ , "File Finding Police report") return else: # File exists but has an extension and one was not provided in the path given. # Add it to file path descriptor sourceFile += ".h5" # information(None, "the filename of source provided lacked the \".h5\" extension.\ # \n\nA file with the extension was found and presumed to be the source meant"\ # ,"Path Police report") # Get file extension fileExtension = os.path.splitext(sourceFile)[-1] # Get the destination file name from the path provided destinationFile = os.path.split(sourceFile)[-1] destinationFolder = "" # If file has no extension, add the default .h5 extension to destination file name if fileExtension == "": warning(None, "The file you are trying to save has no extension\n\nAdding \".h5\" to the name of destination file"\ , ".h5 Extension Police") destinationFile = file + ".h5" # The file provided has different extension. Display a warning but do nothing. elif fileExtension != ".h5": warning(None, "Your file to be copied does not have an \".h5\" extension\n\nNo action taken."\ , "h5 Extension Police") # Display confirmation dialog for copying the file dlg = ConfirmationDialog(title = "You there!", yes_label = "Yes Please!", no_label = "Nah...", message = "Would you like to copy the data file generated after the session?\ \n\nIf you say Nah... and change your mind, you'll have to copy it manually later") # Open the dialog GUI dlg.open() # User provided a destination path if destination: # Check to see if destination is a file name with an extension. destinationExtension = os.path.splitext(destination)[-1] if destinationExtension: # Is it .h5? If not, warn but don't override. if destinationExtension != ".h5": warning(None, "Your destination filename does not have an \".h5\" extension\n\nNo action taken."\ , "h5 Extension Police") destinationFolder, destinationFile = os.path.split(destination) # Assume destination is directory since there is no extension. else: destinationFolder = destination # Look up a default destination from the config file since no <destination> parameter was provided. else: configFile = os.environ.get("Voyeur_config") config = ConfigObj(configFile) # A user specific folder was provided. if user: destinationFolder = config['server']['folder']['data']['user'] # Use default data folder as read from the config file. else: destinationFolder = config['server']['folder']['data']['default'] # User provided a subdirectory, i.e subfolder, into which to place the file. if subdirectory: # The subdirectory provided has common path with the directory provided. Display warning but do nothing. if os.path.commonprefix((destination,subdirectory)): warning(None, "Friendly warning!\n<subdirectory> parameter provided has a common path with the <destination>\ path parameter\n\n1. No action taken.\n2. Check your final destination path to make sure it is what you want"\ , "Path Police report") destinationFolder = os.path.join(destinationFolder,subdirectory) # Path of the destination of file to be copied. destinationPath = os.path.join(destinationFolder,destinationFile) if dlg.return_code == YES: # A file with same name exists. if os.path.isfile(destinationPath): warning(None, "A file with given path already exists!\n\n1. No action taken\ \n2. Make sure to either rename file or choose different folder", "Path Police report") # Provided folder does not exist. Make one and inform the user. elif not os.path.isdir(destinationFolder): information(None, "Making a new folder to put the file into...", "Information Transparency report") # TODO: What if this results in an exception? Catch and do something? # TODO: Keep track of made directories so we may delete them later os.makedirs(os.path.abspath(destinationFolder)) # The save as dialog box. # TODO: change wildcard to current extension wildcard dialog = FileDialog(action="save as", title = "Select directory into which the data file will be copied",\ wildcard = "*.*", default_directory = destinationFolder, default_filename = destinationFile) #*.h5||| elif dlg.return_code == NO and verbose: information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\ , "Information Transparency report") return dialog.open() # User clicked Save and successful input received. if dialog.return_code == OK: # The actual copying of the file. TODO: See if the copy2 function throws an exception copy2(sourceFile, dialog.path) # The user clicked Cancel. elif dialog.return_code == CANCEL: information(None, "No file was copied.\n\nIf you change your mind, you will have to transfer the data file manually."\ , "Information Transparency report") #TODO: update the Voyeur config file after asking user return dialog.path
def wavelength_uncontrolled_nm(self,aim): aim=round(aim,3) # rundet auf die 3. Nachkommastelle if aim <0 or aim >1000: warning(parent=None, title="warning", message="falsche Wert fuer die Wellenlaenge: sie muss zwischen 0 und 1000 nm liegen ") else: self.write(str(aim)+" NM \r")
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 .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()