def on_problem(self): log = str(self._get_package_versions()) + "\n" + self.application.application_log.getvalue() msg = "The best way to report a problem is send an application log to " \ "the developers. If you click 'Yes' below, you will be given then " \ "opportunity to save the log to a file and then file a " \ "new issue on GitHub at " \ "https://github.com/cytoflow/cytoflow/issues/new" dialog = ConfirmationDialog(message = msg, informative = "Would you like to report an issue to the developers?") if dialog.open() == YES: dialog = DefaultFileDialog(parent = self.window.control, action = 'save as', default_suffix = "log", wildcard = (FileDialog.create_wildcard("Log files", "*.log") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable if dialog.open() == OK: with open(dialog.path, 'w') as f: f.write(log) webbrowser.open_new_tab("https://github.com/cytoflow/cytoflow/issues/new") return
def on_open(self): """ Shows a dialog to open a file. """ if self.model.modified: ret = confirm( parent=None, message= "Are you sure you want to discard the current workflow?", title="Clear workflow?") if ret != YES: return dialog = FileDialog( parent=self.window.control, action='open', wildcard=( FileDialog.create_wildcard("Cytoflow workflow", "*.flow") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable if dialog.open() == OK: self.open_file(dialog.path) self.filename = dialog.path self.window.title = "Cytoflow - " + self.filename
def on_notebook(self): """ Shows a dialog to export the workflow to an Jupyter notebook """ dialog = FileDialog(parent = self.window.control, action = 'save as', default_suffix = "ipynb", wildcard = (FileDialog.create_wildcard("Jupyter notebook", "*.ipynb") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) # @UndefinedVariable if dialog.open() == OK: save_notebook(self.model.workflow, dialog.path)
def on_save_as(self): dialog = DefaultFileDialog(parent = self.window.control, action = 'save as', default_suffix = "flow", wildcard = (FileDialog.create_wildcard("Cytoflow workflow", "*.flow") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable if dialog.open() == OK: save_yaml(self.model.workflow, dialog.path) self.filename = dialog.path self.model.modified = False self.window.title = "Cytoflow - " + self.filename
def export_line(self): """ Export data for current line. """ dialog = FileDialog( title='Export Line Data', action='save as', parent=self.window.control, wildcard='' + FileDialog.create_wildcard('Excel Files', ['*.xlsx']) + FileDialog.create_wildcard('CSV Files', ['*.csv', '*.txt']) + FileDialog.WILDCARD_ALL) if dialog.open() == OK: self.line_figure.export_line(dialog.path)
def _on_export(self): dialog = DefaultFileDialog(parent = None, action = 'save as', default_suffix = "csv", wildcard = (FileDialog.create_wildcard("CSV", "*.csv") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable if dialog.open() != OK: return data = pd.DataFrame(index = self.result.index) data[self.result.name] = self.result self._export_data(data, self.result.name, dialog.path)
def on_export(self): """ Shows a dialog to export a file """ information( None, "This will save exactly what you see on the screen " "to a file.", "Export") f = "" filetypes_groups = self.plot_pane.canvas.get_supported_filetypes_grouped( ) filename_exts = [] for name, ext in filetypes_groups.iteritems(): if f: f += ";" f += FileDialog.create_wildcard(name, " ".join(["*." + e for e in ext ])) #@UndefinedVariable filename_exts.append(ext) dialog = FileDialog(parent=self.window.control, action='save as', wildcard=f) if dialog.open() == OK: filetypes = self.plot_pane.canvas.get_supported_filetypes().keys() if not filter(lambda ext: dialog.path.endswith(ext), ["." + ext for ext in filetypes]): selected_exts = filename_exts[dialog.wildcard_index] ext = sorted(selected_exts, key=len)[0] dialog.path += "." dialog.path += ext self.plot_pane.export(dialog.path)
def _savePlot_fired(self): dialog = FileDialog(title='Save plot as...', action='save as', wildcard = FileDialog.create_wildcard('Portable Network Graphics', '*.png')) if not dialog.open(): self.add_line("ERROR opening save file.") return self.plotRU(save=True,filename=dialog.path)
def resize_and_save_matplotlib_figure(figure): ''' To save a matplotlib figure with custom width and height in pixels requires changing the bounding box while is being rendered! ''' # get figure size figure_size = MatplotlibFigureSize(figure=figure) old_dpi = figure_size.dpi old_width_inches = figure_size.width_inches old_height_inches = figure_size.height_inches ui = figure_size.edit_traits(kind='modal') widget = ui.control # maybe change figure size if ui.result: figure.dpi = figure_size.dpi # set new dpi figure.bbox_inches.p1 = figure_size.width_inches, figure_size.height_inches # set new width and height in inches else: return # get file name with (correct choice of formats) fd = FileDialog( action='save as', wildcard=FileDialog.create_wildcard('All available formats', ['*.eps', '*.png', '*.pdf', '*.ps', '*.svg']), ) if fd.open() != OK: return file_name = fd.path # save it figure.savefig(file_name) # restore original figure size figure.dpi = old_dpi # restore old dpi figure.bbox_inches.p1 = old_width_inches, old_height_inches # restore old width and height in inches
def save(self): extensions = [ '*.bmp', '*.gif', '*.jpg', '*.pdf', '*.png', '*.svg', '*.tif', '*.xbm' ] wildcard = FileDialog.create_wildcard('From file name', extensions) dialog = FileDialog(action = 'save as', default_directory = self.default_directory, parent = self.window.control, wildcard = wildcard) if dialog.open() == OK: filename = dialog.path extension = os.path.splitext(filename)[1] if not extension: extension = '.png' filename += extension try: # FIXME: Expose size and background color? self.editor_area.active_editor.save(filename, bgcolor='white') except Exception as exc: msg = 'Failed to save image in %s format' % extension.upper() dialog = MessageDialog(title = 'Error saving', message = msg, detail = str(exc), parent = self.window.control, severity = 'error') dialog.open()
def _do_convert_fired(self): dialog = FileDialog(action='open files', wildcard=(FileDialog.create_wildcard( "FCS files", "*.fcs"))) #@UndefinedVariable if dialog.open() == OK: self.model.input_files = dialog.paths
def import_points(self, event): """ Import points from a file. Parameters ---------- event : A :py:class:`traits.observation.events.TraitChangeEvent` instance The trait change handler for import_button. """ dialog = FileDialog( title='Import Line Points', action='open', parent=self.task.window.control, wildcard='' + FileDialog.create_wildcard('Text Files', ['*.txt']) + FileDialog.WILDCARD_ALL) if dialog.open() == OK: with open(dialog.path, 'r') as in_file: point_string = in_file.read() pat = r'(\([^\)]+\))' new_points = [ np.array([float(s) for s in x.strip("()").split(',')]) for x in re.findall(pat, point_string) ] new_points = [ArrayClass(value=arr) for arr in new_points] self.points = new_points
def _savePlot_fired(self): dialog = FileDialog(title='Save plot as...', action='save as', wildcard=FileDialog.create_wildcard( 'Portable Network Graphics', '*.png')) if not dialog.open(): self.add_line("ERROR opening save file.") return self.plotRU(save=True, filename=dialog.path)
def open(self): wildcard = FileDialog.create_wildcard('JSON files', '*.json') dialog = FileDialog(action = 'open', default_directory = self.default_directory, parent = self.window.control, wildcard = wildcard) if dialog.open() == OK: runner = load(dialog.path) runner.outfile = dialog.path self.editor_area.edit(runner)
def save_as_action(self, info): dlg = FileDialog(parent=info.ui.control, action='save as', wildcard=FileDialog.create_wildcard( "Raytrace model", ["*.raymod"])) ret = dlg.open() if ret == FD_OK: fname = dlg.path model = info.ui.context['object'] model.save_as_yaml(filename=fname) info.ui.title = fname
def change_cord_model(self): """ Change the spinal cord model file used for the 3D display. """ dialog = FileDialog( title='Choose Spinal Cord Model', parent=self.window.control, wildcard=FileDialog.create_wildcard('VTK Model', ['*.vtk']) + FileDialog.WILDCARD_ALL) if dialog.open() == OK: self.mayavi_scene.csf_model = dialog.path
def open(self): """ Show a dialog to open a new data source. """ dialog = FileDialog( title='Choose Data File', parent=self.window.control, wildcard=FileDialog.create_wildcard('Data Files', ['*.mat']) + FileDialog.WILDCARD_ALL) if dialog.open() == OK: if not self.model_initialized: self._new_file(dialog.path)
def open_file_action(self, info): dlg = FileDialog(parent=info.ui.control, action='open', wildcard=FileDialog.create_wildcard( "Raytrace model", ["*.raymod"])) ret = dlg.open() if ret == FD_OK: fname = dlg.path if os.path.exists(fname): model = info.ui.context['object'] model.load_from_yaml(fname) info.ui.title = fname
def _saveLog_fired(self): dialog = FileDialog(title='Save plot as...', action='save as', wildcard = FileDialog.create_wildcard('Text file', '*.txt')) if not dialog.open(): self.add_line("ERROR opening save file.") return try: out = open(dialog.path,'w') out.write(self.results) out.close() except IOError: self.add_line("I failed to open "+str(dialog.path)) return
def perform(self, event=None): fd = FileDialog( wildcard=FileDialog.create_wildcard('PModelChecker results files', ['*.psm', '*.mc2']), title='Select a PModelChecker results file', ) if fd.open() != OK: return commons.edit_pmodelchecker_results_file( file=fd.path, # application=self.application, # application=self.window.application, application=self.window.workbench.application, )
def on_export(self): """ Shows a dialog to export a file """ f = "" filetypes_groups = self.application.plot_pane.canvas.get_supported_filetypes_grouped( ) filename_exts = [] for name, ext in filetypes_groups.items(): if f: f += ";" f += FileDialog.create_wildcard(name, " ".join(["*." + e for e in ext ])) #@UndefinedVariable filename_exts.append(ext) dialog = FileDialog(parent=self.window.control, action='save as', wildcard=f) if dialog.open() == OK: filetypes = list(self.application.plot_pane.canvas. get_supported_filetypes().keys()) if not [ ext for ext in ["." + ext for ext in filetypes] if dialog.path.endswith(ext) ]: selected_exts = filename_exts[dialog.wildcard_index] ext = sorted(selected_exts, key=len)[0] dialog.path += "." dialog.path += ext if (self.export_pane.width * self.export_pane.dpi > 2**16 or \ self.export_pane.height * self.export_pane.dpi > 2**16 or \ self.export_pane.width * self.export_pane.height * self.export_pane.dpi ** 2 > 2 ** 30) and \ pathlib.Path(dialog.path).suffix in ['png', 'pgf', 'raw', 'rgba', 'jpg', 'jpeg', 'bmp', 'pcx', 'tif', 'tiff', 'xpm']: error( None, "Can't export raster images with a height or width larger than 65535 pixels, " "or a total image size of greater than 2**30 pixels. " "Decrease your image size or DPI, or use a vector format (like PDF or SVG)." ) return self.application.plot_pane.export(dialog.path, width=self.export_pane.width, height=self.export_pane.height, dpi=self.export_pane.dpi)
def _saveLog_fired(self): dialog = FileDialog(title='Save plot as...', action='save as', wildcard=FileDialog.create_wildcard( 'Text file', '*.txt')) if not dialog.open(): self.add_line("ERROR opening save file.") return try: out = open(dialog.path, 'w') out.write(self.results) out.close() except IOError: self.add_line("I failed to open " + str(dialog.path)) return
def save_as(self): ''' Saves the file to disk after prompting for the file name. ''' dialog = FileDialog( parent=self.window.control, action='save as', default_filename=self.name, wildcard='\n'.join([FileDialog.create_wildcard(wildcard[0], ', '.join(wildcard[1])) for wildcard in self.wildcards]) if len(self.wildcards) > 0 else FileDialog.create_wildcard('All files', '*') ) if dialog.open() != CANCEL: # update this editor self.id = dialog.path self.name = os.path.basename(dialog.path) self.obj.path = dialog.path # update obj (an apptools.io.api.File) self.save() # save it now it has a path
def click ( self ): """ Handles the user left clicking on the feature image. """ # Create the file dialog: fd = FileDialog() # Set up the default path based on the current value (if any): default_path = getattr( self.dock_control.object, self.name, None ) if default_path is not None: fd.default_path = default_path # Set up the appropriate extension filters (if any): if len( self.extensions ) > 0: fd.wildcard = '\n'.join([ FileDialog.create_wildcard('', '*' + ext) for ext in self.extensions ]) # Display the file dialog, and if successful, set the new file name: if fd.open() == OK: self.drop( fd.path )
def _save_btn_changed(self): dlg = FileDialog(action="save as", wildcard=FileDialog.create_wildcard( "Scene model", ["*.stp", "*.step", "*.wrl", "*.vrml"])) ret = dlg.open() if ret != FD_OK: return filename = dlg.path fmap = { ".stp": self.write_to_STEP, ".step": self.write_to_STEP, ".wrl": self.write_to_VRML, ".vrml": self.write_to_VRML } ext = os.path.splitext(filename)[-1].lower() try: fmap[ext](filename) except KeyError: self.write_to_STEP(filename)
def export_points(self, event): """ Export points from a file. Parameters ---------- event : A :py:class:`traits.observation.events.TraitChangeEvent` instance The trait change handler for export_button. """ point_string = str([tuple(x.value) for x in self.points]) dialog = FileDialog( title='Export Line Points', action='save as', parent=self.task.window.control, wildcard='' + FileDialog.create_wildcard('Text Files', ['*.txt']) + FileDialog.WILDCARD_ALL) if dialog.open() == OK: with open(dialog.path, 'w') as out_file: out_file.write(point_string)
def click(self): """ Handles the user left clicking on the feature image. """ # Create the file dialog: fd = FileDialog() # Set up the default path based on the current value (if any): default_path = getattr(self.dock_control.object, self.name, None) if default_path is not None: fd.default_path = default_path # Set up the appropriate extension filters (if any): if len(self.extensions) > 0: fd.wildcard = '\n'.join([ FileDialog.create_wildcard('', '*' + ext) for ext in self.extensions ]) # Display the file dialog, and if successful, set the new file name: if fd.open() == OK: self.drop(fd.path)
def on_export(self): """ Shows a dialog to export a file """ f = "" filetypes_groups = self.application.plot_pane.canvas.get_supported_filetypes_grouped( ) filename_exts = [] for name, ext in filetypes_groups.items(): if f: f += ";" f += FileDialog.create_wildcard(name, " ".join(["*." + e for e in ext ])) #@UndefinedVariable filename_exts.append(ext) dialog = FileDialog(parent=self.window.control, action='save as', wildcard=f) if dialog.open() == OK: filetypes = list(self.application.plot_pane.canvas. get_supported_filetypes().keys()) if not [ ext for ext in ["." + ext for ext in filetypes] if dialog.path.endswith(ext) ]: selected_exts = filename_exts[dialog.wildcard_index] ext = sorted(selected_exts, key=len)[0] dialog.path += "." dialog.path += ext self.application.plot_pane.export(dialog.path, width=self.export_pane.width, height=self.export_pane.height, dpi=self.export_pane.dpi)
def _on_export(self): dialog = DefaultFileDialog( parent=None, action='save as', default_suffix="csv", wildcard=( FileDialog.create_wildcard("CSV", "*.csv") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable if dialog.open() != OK: return data = pd.DataFrame(index=self.result.index) data[self.result.name] = self.result if self.subset: data = data.query(self.subset) names = list(data.index.names) for name in names: unique_values = data.index.get_level_values(name).unique() if len(unique_values) == 1: data.index = data.index.droplevel(name) facets = [ x for x in [ self.row_facet, self.subrow_facet, self.column_facet, self.subcolumn_facet ] if x ] if set(facets) != set(data.index.names): raise util.CytoflowViewError( "Must use all the statistic indices as variables or facets: {}" .format(data.index.names)) row_groups = data.index.get_level_values(self.row_facet).unique() \ if self.row_facet else [None] subrow_groups = data.index.get_level_values(self.subrow_facet).unique() \ if self.subrow_facet else [None] col_groups = data.index.get_level_values(self.column_facet).unique() \ if self.column_facet else [None] subcol_groups = data.index.get_level_values(self.subcolumn_facet).unique() \ if self.subcolumn_facet else [None] row_offset = (self.column_facet != "") + (self.subcolumn_facet != "") col_offset = (self.row_facet != "") + (self.subrow_facet != "") num_rows = len(row_groups) * len(subrow_groups) + row_offset num_cols = len(col_groups) * len(subcol_groups) + col_offset t = np.empty((num_rows, num_cols), dtype=np.object_) # make the main table for (ri, r) in enumerate(row_groups): for (rri, rr) in enumerate(subrow_groups): for (ci, c) in enumerate(col_groups): for (cci, cc) in enumerate(subcol_groups): row_idx = ri * len(subrow_groups) + rri + row_offset col_idx = ci * len(subcol_groups) + cci + col_offset # agg_idx = [x for x in (r, rr, c, cc) if x is not None] # agg_idx = tuple(agg_idx) # if len(agg_idx) == 1: # agg_idx = agg_idx[0] # t[row_idx, col_idx] = self.result.get(agg_idx) # this is not pythonic, but i'm tired agg_idx = [] for data_idx in data.index.names: if data_idx == self.row_facet: agg_idx.append(r) elif data_idx == self.subrow_facet: agg_idx.append(rr) elif data_idx == self.column_facet: agg_idx.append(c) elif data_idx == self.subcolumn_facet: agg_idx.append(cc) agg_idx = tuple(agg_idx) if len(agg_idx) == 1: agg_idx = agg_idx[0] try: text = "{:g}".format( data.loc[agg_idx][self.result.name]) except ValueError: text = data.loc[agg_idx][self.result.name] t[row_idx, col_idx] = self.result.get(agg_idx) # row headers if self.row_facet: for (ri, r) in enumerate(row_groups): row_idx = ri * len(subrow_groups) + row_offset text = "{0} = {1}".format(self.row_facet, r) t[row_idx, 0] = text # subrow headers if self.subrow_facet: for (ri, r) in enumerate(row_groups): for (rri, rr) in enumerate(subrow_groups): row_idx = ri * len(subrow_groups) + rri + row_offset text = "{0} = {1}".format(self.subrow_facet, rr) t[row_idx, 1] = text # column headers if self.column_facet: for (ci, c) in enumerate(col_groups): col_idx = ci * len(subcol_groups) + col_offset text = "{0} = {1}".format(self.column_facet, c) t[0, col_idx] = text # column headers if self.subcolumn_facet: for (ci, c) in enumerate(col_groups): for (cci, cc) in enumerate(subcol_groups): col_idx = ci * len(subcol_groups) + cci + col_offset text = "{0} = {1}".format(self.subcolumn_facet, c) t[1, col_idx] = text np.savetxt(dialog.path, t, delimiter=",", fmt="%s")
def on_problem(self): log = str(self._get_package_versions()) + "\n" + self.application.application_log.getvalue() msg = "The best way to report a problem is send an application log to " \ "the developers. You can do so by either sending us an email " \ "with the log in it, or saving the log to a file and filing a " \ "new issue on GitHub at " \ "https://github.com/bpteague/cytoflow/issues/new" dialog = ConfirmationDialog(message = msg, informative = "Which would you like to do?", yes_label = "Send an email...", no_label = "Save to a file...") if dialog.open() == NO: dialog = DefaultFileDialog(parent = self.window.control, action = 'save as', default_suffix = "log", wildcard = (FileDialog.create_wildcard("Log files", "*.log") + ';' + #@UndefinedVariable FileDialog.create_wildcard("All files", "*"))) #@UndefinedVariable if dialog.open() == OK: with open(dialog.path, 'w') as f: f.write(log) webbrowser.open_new_tab("https://github.com/bpteague/cytoflow/issues/new") return information(None, "I'll now try to open your email client and create a " "new message to the developer. Debugging logs are " "attached. Please fill out the template bug report and " "send -- thank you for reporting a bug!") log = self.application.application_log.getvalue() versions = ["{0} {1}".format(key, value) for key, value in self._get_package_versions().items()] body = """ Thank you for your bug report! Please fill out the following template. PLATFORM (Mac, PC, Linux, other): OPERATING SYSTEM (eg OSX 10.7, Windows 8.1): SEVERITY (Critical? Major? Minor? Enhancement?): DESCRIPTION: - What were you trying to do? - What happened? - What did you expect to happen? PACKAGE VERSIONS: {0} DEBUG LOG: {1} """.format(versions, log) mailto("*****@*****.**", subject = "Cytoflow bug report", body = body)
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()