예제 #1
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
예제 #2
0
 def load_config_file(self, ui_info):
     dialog = FileDialog(action="open", wildcard="*.ini")
     dialog.open()
     if dialog.return_code == OK:
         if dialog.path != ui_info.ui.context["object"].project_info.config_file:
             shutil.copy(dialog.path, ui_info.ui.context["object"].project_info.config_file)
         load_config(self.pipeline, ui_info.ui.context["object"].project_info.config_file)
예제 #3
0
def OpenFileDialog(action, wildcard, self):
    from pyface.api import FileDialog, OK
    doaction = action
    if action == "new":
        doaction = "save as"
    dialog = FileDialog(action=doaction, wildcard=wildcard)
    dialog.open()
    if dialog.return_code == OK:
        self.filedir = dialog.directory
        self.filename = dialog.filename
        self.Configuration_File = os.path.join(dialog.directory, dialog.filename)
        if action == "open":
            self._config = load_config(dialog.path, self.config_class)
            self._config.configure_traits(view=self.config_view())
            self.saved = False
            self.config_changed = True
        if action == "new":
            self._config = self.config_class()
            self._config.configure_traits(view=self.config_view())
            self._save_to_file()
            self.saved = False
            self.config_changed = True
        if action == "save as":
            self._save_to_file()
            self.saved = True
            self.config_changed = False
예제 #4
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
예제 #5
0
def OpenFileDialog(action, wildcard, self):
    from pyface.api import FileDialog, OK
    doaction = action
    if action == "new":
        doaction = "save as"
    dialog = FileDialog(action=doaction, wildcard=wildcard)
    dialog.open()
    if dialog.return_code == OK:
        self.filedir = dialog.directory
        self.filename = dialog.filename
        self.Configuration_File = os.path.join(dialog.directory,
                                               dialog.filename)
        if action == "open":
            self._config = load_config(dialog.path, self.config_class)
            self._config.configure_traits(view=self.config_view())
            self.saved = False
            self.config_changed = True
        if action == "new":
            self._config = self.config_class()
            self._config.configure_traits(view=self.config_view())
            self._save_to_file()
            self.saved = False
            self.config_changed = True
        if action == "save as":
            self._save_to_file()
            self.saved = True
            self.config_changed = False
예제 #6
0
    def action_save(self, info):
        # First make a copy of the frame we will save
        save_frame = info.object.camera.frame.copy()

        # Then find out where to save it
        dialog = FileDialog(parent=info.ui.control, action="save as", modal=True, title="Save Image")
        try:
            dialog.default_directory = info.object._current_folder
        except TraitError:
            pass  # thrown if _current_folder is None
        dialog.open()
        path = dialog.path

        # Store the directory for the next time
        info.object._current_folder = dialog.directory

        if dialog.return_code != OK:
            return

        # Default is PNG
        if "." not in path:
            path += ".png"

        # Save it
        scipy.misc.imsave(path, save_frame)
예제 #7
0
파일: task.py 프로젝트: rmkatti/surf_2012
 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()
예제 #8
0
 def save_config_file(self, ui_info):
     dialog = FileDialog(action="save as", default_filename="config.ini")
     dialog.open()
     if dialog.return_code == OK:
         save_config(self.pipeline, ui_info.ui.context["object"].project_info.config_file)
         if dialog.path != ui_info.ui.context["object"].project_info.config_file:
             shutil.copy(ui_info.ui.context["object"].project_info.config_file, dialog.path)
예제 #9
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
예제 #10
0
 def save_as(self):
     dlg = FileDialog( action='save as', wildcard='*.rep')
     dlg.open()
     if dlg.filename!='':
         fi = file(dlg.filename,'w')
         dump(self,fi)
         fi.close()
예제 #11
0
    def export(self):
        dialog = FileDialog(action='save as', title='Export Experiment',
                                wildcard='csv files (*.csv)|*.csv')
        dialog.open()
        path = dialog.path
        if not path.endswith('.csv'):
            path += '.csv'
        with open(path, 'w') as f:
            fieldnames = [
                'well',
                'led',
                'program',
                'program_id',
                'total_steps',
                'step',
                'step_no',
                'step_id',
                'step_start_time',
                'step_duration',
                'step_intensity',
                'step_pulsed',
                'step_pulse_on',
                'step_pulse_off',
                'step_repeat']
            writer = csv.DictWriter(f, fieldnames=fieldnames, restval='None')
            writer.writeheader()

            for well_group in self.plate.well_groups:
                led_row = {'well': well_group.position}
                well = well_group.wells[0]
                for led in well.leds:
                    led_row['led'] = led.name
                    if led.program:
                        program_row = {}
                        program_row['program'] = led.program.name
                        program_row['program_id'] = led.program.ID
                        program_row['total_steps'] = len(led.program.steps)
                        prg_does_repeat = led.program._after_end == 'repeat'
                        program_row.update(led_row)
                        if len(led.program.steps) == 0:
                            # Program has no Steps, write now
                            writer.writerow(program_row)
                        for step_no, step in enumerate(led.program.steps):
                            program_row['step'] = step.name
                            program_row['step_no'] = step_no + 1
                            program_row['step_id'] = step.ID
                            step_start = sum(step.duration for step in led.program.steps[:step_no])
                            program_row['step_start_time'] = step_start
                            program_row['step_duration'] = step.duration
                            program_row['step_intensity'] = step.intensity
                            program_row['step_pulsed'] = ['no', 'yes'][step.is_pulsed]
                            program_row['step_pulse_on'] = step.pulse_on
                            program_row['step_pulse_off'] = step.pulse_off
                            is_last_step = step_no == len(led.program.steps) - 1
                            step_does_repeat = prg_does_repeat and is_last_step
                            program_row['step_repeat'] = ['no', 'yes'][step_does_repeat]
                            writer.writerow(program_row)
                    else:
                        writer.writerow(led_row)
예제 #12
0
 def load(self):
     dlg = FileDialog( action='open', wildcard='*.rep')
     dlg.open()
     if dlg.filename!='':
         fi = file(dlg.filename,'rb')
         s = load(fi)
         self.copy_traits(s)
         fi.close()
예제 #13
0
 def load(self):
     dlg = FileDialog(action='open', wildcard='*.rep')
     dlg.open()
     if dlg.filename != '':
         fi = file(dlg.filename, 'rb')
         s = load(fi)
         self.copy_traits(s)
         fi.close()
예제 #14
0
 def run_script(self):
     dlg = FileDialog(action='open', wildcard='*.py')
     dlg.open()
     if dlg.filename != '':
         #~ try:
         rx = self
         b = rx.Beamformer
         script = dlg.path
         execfile(dlg.path)
예제 #15
0
 def _out_to_mat_fired(self):
     dialog = FileDialog(default_filename = self.filename+"_MATLAB_Phase"+str(self.plotA["notes"]["start"][2]), action="save as", wildcard=self.file_wildcard3)
     dialog.open()
     if dialog.return_code == OK:
         savefiledir = dialog.directory
         savefilename = dialog.filename
         path = os.path.join(savefiledir, savefilename)
         dataset = {self.plotA, self.plotB, self.plotC, self.plotD}
         scio.savemat(path, dataset, True)
예제 #16
0
 def _choose_local_file_fired(self):
     dialog = FileDialog(
         label='Choose local_file',
         action='open')
     dialog.open()
     if dialog.return_code == OK:
         self.local_file_for_fileio = dialog.path
     else:
         self._write('Error while selecting local file.')
예제 #17
0
 def _logAnalyserSelectButton_fired(self):
     """open a fast file editor for selecting many files """
     fileDialog = FileDialog(action="open files")
     fileDialog.open()
     if fileDialog.return_code == pyface.constant.OK:
         self.logAnalysers = fileDialog.paths
         logger.info("selected log analysers: %s " % self.logAnalysers)
     self.logAnalyserDisplayString = str(
         [os.path.split(path)[1] for path in self.logAnalysers])
 def _open():
     if open_show_dialog:
         open_dlg = FileDialog(action='open')
         open_dlg.open()
         self.editor_area.active_tabwidget = self
         if open_dlg.return_code == OK:
             open_file_action(open_dlg.path)
     else:
         open_file_action()
예제 #19
0
 def _open():
     if open_show_dialog:
         open_dlg = FileDialog(action='open')
         open_dlg.open()
         self.editor_area.active_tabwidget = self
         if open_dlg.return_code == OK:
             open_file_action(open_dlg.path)
     else:
         open_file_action()
예제 #20
0
 def _open_settings(self):
     logger.debug("_open_settings call . Opening a settings file")
     dialog = FileDialog(action="open",
                         default_directory=self.default_directory,
                         wildcard=self.file_wildcard)
     dialog.open()
     if dialog.return_code == OK:
         self.settingsFile = dialog.path
         self._load_settings(self.settingsFile)
예제 #21
0
 def _choose_fw_fired(self):
   dialog = FileDialog(label='Choose Firmware File',
                       action='open', wildcard=self.file_wildcard)
   dialog.open()
   if dialog.return_code == OK:
     filepath = os.path.join(dialog.directory, dialog.filename)
     self.load_ihx(filepath)
   else:
     self.set_status('Error while selecting file')
예제 #22
0
 def run_script(self):
     dlg = FileDialog( action='open', wildcard='*.py')
     dlg.open()
     if dlg.filename!='':
         #~ try:
         rx = self
         b = rx.Beamformer
         script = dlg.path
         execfile(dlg.path)
예제 #23
0
파일: utils.py 프로젝트: kingjr/gselu
def ask_user_for_loadfile(title=None):
    from pyface.api import FileDialog, OK
    dialog = FileDialog(action='open')
    if title is not None:
        dialog.title = title
    dialog.open()
    if dialog.return_code != OK:
        return

    return os.path.join( dialog.directory, dialog.filename )
예제 #24
0
 def _choose_fw_fired(self):
   """ Activate file dialog window to choose IntelHex firmware file. """
   dialog = FileDialog(label='Choose Firmware File',
                       action='open', wildcard=self.file_wildcard)
   dialog.open()
   if dialog.return_code == OK:
     filepath = os.path.join(dialog.directory, dialog.filename)
     self.load_ihx(filepath)
   else:
     self.clear('Error while selecting file')
예제 #25
0
def ask_user_for_loadfile(title=None):
    from pyface.api import FileDialog, OK
    dialog = FileDialog(action='open')
    if title is not None:
        dialog.title = title
    dialog.open()
    if dialog.return_code != OK:
        return

    return os.path.join(dialog.directory, dialog.filename)
예제 #26
0
 def _save_as_settings(self):
     """Called when user presses save as in Menu bar """
     dialog = FileDialog(action="save as",
                         default_directory=self.default_directory,
                         wildcard=self.file_wildcard)
     dialog.open()
     if dialog.return_code == OK:
         self.settingsFile = dialog.path
         if self.settingsFile[-4:] != ".csv":
             self.settingsFile += ".csv"
         self._save_settings(self.settingsFile)
예제 #27
0
    def add_data(self, info):
        fileDialog = FileDialog(action='save as',
                                title='Save As',
                                wildcard=self.wildcard,
                                parent=info.ui.control)

        fileDialog.open()
        if fileDialog.path == '' or fileDialog.return_code == CANCEL:
            return False
        else:
            info.object.load_from_file(fileDialog.path)
예제 #28
0
def filedialog():
    """
    Open a simple file dialog to pick a file
    """
    from pyface.api import FileDialog, OK, confirm, YES
    dialog = FileDialog(action="open")
    dialog.open()
    if dialog.return_code == OK:
        return dialog.path
    else:
        quit()
예제 #29
0
 def _save_LineScans_button_fired(self):
     dialog = FileDialog(default_filename = self.filename+"_LineScan_", action="save as", wildcard=self.file_wildcard2)
     dialog.open()
     if dialog.return_code == OK:
         savefiledir = dialog.directory
         savefilename = dialog.filename
         path = os.path.join(savefiledir, savefilename)
         self.LineScans.do_layout(force=True)
         plot_gc = PlotGraphicsContext(self.LineScans.outer_bounds)
         plot_gc.render_component(self.LineScans)
         plot_gc.save(path)
예제 #30
0
 def _choose_fw_fired(self):
     """ Activate file dialog window to choose IntelHex firmware file. """
     dialog = FileDialog(label='Choose Firmware File',
                         action='open',
                         wildcard=self.file_wildcard)
     dialog.open()
     if dialog.return_code == OK:
         filepath = os.path.join(dialog.directory, dialog.filename)
         self.load_ihx(filepath)
     else:
         self.clear('Error while selecting file')
    def _on_open(self, info):
        """ Menu action to load a script from file.  """
        file_dialog = FileDialog(action='open',
                                 default_directory=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.load_code_from_file(file_dialog.path)
            
        return
예제 #32
0
    def object_export_dataframe_changed(self, info):
        fileDialog = FileDialog(action='save as', title='Save As',
                                wildcard=self.wildcard,
                                parent=info.ui.control,
                                default_filename=info.object.name.replace(' ','_') + '_dataframe')

        fileDialog.open()
        if fileDialog.path == '' or fileDialog.return_code == CANCEL:
            return False
        df = info.object.make_db_dataframe()
        df.to_csv(fileDialog.path)
예제 #33
0
 def load_config_file(self, ui_info):
     dialog = FileDialog(action="open", wildcard="*.ini")
     dialog.open()
     if dialog.return_code == OK:
         if dialog.path != ui_info.ui.context[
                 "object"].project_info.config_file:
             shutil.copy(
                 dialog.path,
                 ui_info.ui.context["object"].project_info.config_file)
         load_config(self.pipeline,
                     ui_info.ui.context["object"].project_info.config_file)
예제 #34
0
 def save_config_file(self, ui_info):
     dialog = FileDialog(action="save as", default_filename="config.ini")
     dialog.open()
     if dialog.return_code == OK:
         save_config(self.pipeline,
                     ui_info.ui.context["object"].project_info.config_file)
         if dialog.path != ui_info.ui.context[
                 "object"].project_info.config_file:
             shutil.copy(
                 ui_info.ui.context["object"].project_info.config_file,
                 dialog.path)
예제 #35
0
    def _on_open(self, info):
        """ Menu action to load a script from file.  """
        file_dialog = FileDialog(action='open',
                                 default_directory=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.load_code_from_file(file_dialog.path)

        return
예제 #36
0
 def _load_trans_fired(self):
     # find trans file destination
     raw_dir = os.path.dirname(self.model.hsp.file)
     subject = self.model.mri.subject
     trans_file = trans_fname.format(raw_dir=raw_dir, subject=subject)
     dlg = FileDialog(action="open", wildcard=trans_wildcard, default_path=trans_file)
     dlg.open()
     if dlg.return_code != OK:
         return
     trans_file = dlg.path
     self.model.load_trans(trans_file)
예제 #37
0
def ask_user_for_savefile(title=None):
    #from traitsui.file_dialog import save_file
    from pyface.api import FileDialog, OK

    dialog = FileDialog(action='save as')
    if title is not None:
        dialog.title = title
    dialog.open()
    if dialog.return_code != OK:
        return

    return os.path.join(dialog.directory, dialog.filename)
예제 #38
0
파일: utils.py 프로젝트: kingjr/gselu
def ask_user_for_savefile(title=None):
    #from traitsui.file_dialog import save_file
    from pyface.api import FileDialog, OK
    
    dialog = FileDialog(action='save as')
    if title is not None:
        dialog.title = title
    dialog.open()
    if dialog.return_code != OK:
        return

    return os.path.join( dialog.directory, dialog.filename )
예제 #39
0
    def _save_fired(self):
        if self.n_scale_params:
            subjects_dir = self.model.mri.subjects_dir
            subject_from = self.model.mri.subject
            subject_to = self.model.raw_subject or self.model.mri.subject
        else:
            subject_to = self.model.mri.subject

        # ask for target subject
        if self.n_scale_params:
            mridlg = NewMriDialog(subjects_dir=subjects_dir, subject_from=subject_from, subject_to=subject_to)
            ui = mridlg.edit_traits(kind="modal")
            if ui.result != True:
                return
            subject_to = mridlg.subject_to

        # find bem file to run mne_prepare_bem_model
        if self.can_prepare_bem_model and self.prepare_bem_model:
            bem_job = self.model.get_prepare_bem_model_job(subject_to)
        else:
            bem_job = None

        # find trans file destination
        raw_dir = os.path.dirname(self.model.hsp.file)
        trans_file = trans_fname.format(raw_dir=raw_dir, subject=subject_to)
        dlg = FileDialog(action="save as", wildcard=trans_wildcard, default_path=trans_file)
        dlg.open()
        if dlg.return_code != OK:
            return
        trans_file = dlg.path
        if not trans_file.endswith(".fif"):
            trans_file = trans_file + ".fif"
            if os.path.exists(trans_file):
                answer = confirm(None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?")
                if answer != YES:
                    return

        # save the trans file
        try:
            self.model.save_trans(trans_file)
        except Exception as e:
            error(None, str(e), "Error Saving Trans File")
            return

        # save the scaled MRI
        if self.n_scale_params:
            job = self.model.get_scaling_job(subject_to)
            self.queue.put(job)
            self.queue_len += 1

            if bem_job is not None:
                self.queue.put(bem_job)
                self.queue_len += 1
    def _on_run_custom_ui(self, info):
        """ Run a custom UI on top of the context.
        """
        wildcard = FileDialog.WILDCARD_PY.rstrip('|')
        file_dialog = FileDialog(action='open',
                                 default_directory=info.object.file_directory,
                                 wildcard=wildcard)
        file_dialog.open()

        if file_dialog.path != '':
            info.object.run_custom_ui(file_dialog.path, live=False)
        return
    def _on_save_as(self, info):
        """ Menu action to save script to file of different name """
        file_dialog = FileDialog(action='save as',
                                 default_path=info.object.file_path,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.save_code_to_file(file_dialog.path)
            msg = 'Saving script at ', file_dialog.path
            logger.debug(msg)
        return
예제 #42
0
    def _on_save_as(self, info):
        """ Menu action to save script to file of different name """
        file_dialog = FileDialog(action='save as',
                                 default_path=info.object.file_directory,
                                 wildcard='All files (*.*)|*.*')
        file_dialog.open()

        if file_dialog.path != '':
            info.object.save_code_to_file(file_dialog.path)
            msg = 'Saving script at ', file_dialog.path
            logger.debug(msg)
        return
예제 #43
0
    def _on_import_data_file(self, info):
        """ Loading data files to import data for data contexts.

            File formats supported are ASCII, LAS, CSV, pickled files.
            ASCII files can be tab- or whitespace- delimited.
            If geo cannot be imported, only the pickled files can be
            used.
        """

        try:
            import geo
            wildcard = 'All files (*.*)|*.*|' + \
                       'ASCII files (*.asc)|*.asc|' + \
                       'Text files (*.txt)|*.txt|' + \
                       'CSV files (*.csv)|*.csv|' + \
                       'LAS files (*.las)|*.las|' + \
                       'Pickled files (*.pickle)|*.pickle|'+ \
                       'Segy files (*.segy)|*.segy'
        except ImportError:
            wildcard = 'Pickled files (*.pickle)|*.pickle'

        app = info.object
        file_dialog = FileDialog(
            action='open',
            default_directory=app.data_directory,
            wildcard=wildcard,
        )
        file_dialog.open()

        data_context, filename = None, file_dialog.path
        if file_dialog.path != '':
            filesplit = os.path.splitext(filename)
            if filesplit[1] != '':
                configurable_import = ConfigurableImportUI(filename=filename,
                                                           wildcard=wildcard)
                ui = configurable_import.edit_traits(kind='livemodal')
                if ui.result and isinstance(configurable_import.context,
                                            DataContext):
                    data_context = configurable_import.context
                    app.load_context(data_context,
                                     mode=configurable_import.save_choice_)

                    filename = configurable_import.filename

        if isinstance(data_context, DataContext):
            logger.debug('Loading data from %s' % filename)
        else:
            logger.error('Unidentified file format for data import: %s' %
                         filename)
        return
예제 #44
0
    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]})
예제 #45
0
 def object_export_data_changed(self, info):
     fileDialog = FileDialog(action='save as',
                             title='Save As',
                             wildcard=self.wildcard,
                             parent=info.ui.control,
                             default_filename=info.object.name)
     if info.object.export_format == 'Clipboard':
         info.object.save_pandas()
     else:
         fileDialog.open()
         if fileDialog.path == '' or fileDialog.return_code == CANCEL:
             return False
         else:
             info.object.save_pandas(fileDialog.path)
    def _on_import_data_file(self, info):
        """ Loading data files to import data for data contexts.

            File formats supported are ASCII, LAS, CSV, pickled files.
            ASCII files can be tab- or whitespace- delimited.
            If geo cannot be imported, only the pickled files can be
            used.
        """

        try:
            import geo
            wildcard = 'All files (*.*)|*.*|' + \
                       'ASCII files (*.asc)|*.asc|' + \
                       'Text files (*.txt)|*.txt|' + \
                       'CSV files (*.csv)|*.csv|' + \
                       'LAS files (*.las)|*.las|' + \
                       'Pickled files (*.pickle)|*.pickle|'+ \
                       'Segy files (*.segy)|*.segy'
        except ImportError:
            wildcard = 'Pickled files (*.pickle)|*.pickle'
        
        app = info.object
        file_dialog = FileDialog(action = 'open',
                                 default_directory = app.data_directory,
                                 wildcard = wildcard,
                                 )
        file_dialog.open()

        data_context, filename = None, file_dialog.path
        if file_dialog.path != '':
            filesplit = os.path.splitext(filename)
            if filesplit[1] != '': 
                configurable_import = ConfigurableImportUI(filename = filename,
                                                           wildcard = wildcard)
                ui = configurable_import.edit_traits(kind='livemodal')
                if ui.result and configurable_import.context:
                    data_context = configurable_import.context
                    app.load_context(
                        data_context, mode=configurable_import.save_choice_)

                    filename = configurable_import.filename

        if data_context:
            logger.debug('Loading data from %s' % filename)
        else:
            logger.error('Unidentified file format for data import: %s' %
                         filename)
        return
예제 #47
0
 def _on_add_tubes(self):
     """
     Handle "Add tubes..." button.  Add tubes to the experiment.
     """
     
     # TODO - adding a set of files, then a condition, then another
     # set doesn't work.
     
     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
     
     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))
             
         tube = Tube()
         
         for trait_name, trait in self.model.tube_traits.items():
             # TODO - do we still need to check for transient?
             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(Source = tube_meta['$SRC'],
                        _file = path,
                        _parent = self.model)
         
         if 'TUBE NAME' in tube_meta:
             tube.Tube = tube_meta['TUBE NAME']
         elif '$SMNO' in tube_meta:
             tube.Tube = tube_meta['$SMNO']
         
         self.model.tubes.append(tube)
예제 #48
0
    def _on_add_tubes(self):
        """
        Handle "Add tubes..." button.  Add tubes to the experiment.
        """

        # TODO - adding a set of files, then a condition, then another
        # set doesn't work.

        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

        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))

            tube = Tube()

            for trait_name, trait in self.model.tube_traits.items():
                # TODO - do we still need to check for transient?
                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(Source=tube_meta['$SRC'],
                           _file=path,
                           _parent=self.model)

            if 'TUBE NAME' in tube_meta:
                tube.Tube = tube_meta['TUBE NAME']
            elif '$SMNO' in tube_meta:
                tube.Tube = tube_meta['$SMNO']

            self.model.tubes.append(tube)
예제 #49
0
파일: actions.py 프로젝트: arkyaC/mayavi
    def perform(self, event):
        """ Performs the action. """

        extensions = [
            '*.png', '*.jpg', '*.jpeg', '*.tiff', '*.bmp', '*.ps', '*.eps',
            '*.tex', '*.rib', '*.wrl', '*.oogl', '*.pdf', '*.vrml', '*.obj',
            '*.iv', '*.pov', '*x3d'
        ]

        descriptions = [
            'PNG', 'JPG', 'JPEG', 'TIFF', 'Bitmap', 'PostScript', 'EPS',
            'TeX', 'RIB', 'WRL', 'Geomview', 'PDF', 'VRML', 'Wavefront',
	    'Povray', 'X3D'
        ]

        wildcard = ''

        for description, extension in zip(descriptions, extensions):
            wildcard += '{} ({})|{}|'.format(description, extension, extension)
        
        wildcard += 'Determine by extension (*.*)|(*.*)'

        dialog = FileDialog(
            parent   = self.window.control,
            title    = 'Save scene to image',
            action   = 'save as',
            wildcard = wildcard
        )
        if dialog.open() == OK:
            scene = self.scene_manager.current_scene
            if scene is not None:
                scene.save(dialog.path)

        return
예제 #50
0
파일: utils.py 프로젝트: enthought/mayavi
def popup_save(parent=None):
    """Popup a dialog asking for an image name to save the scene to.
    This is used mainly to save a scene in full screen mode. Returns a
    filename, returns empty string if action was cancelled. `parent` is
    the parent widget over which the dialog will be popped up.
    """
    from pyface.api import FileDialog, OK

    extensions = ['*.png', '*.jpg', '*.tiff', '*.bmp', '*.ps',
                  '*.eps', '*.pdf', '*.tex', '*.rib', '*.wrl',
                  '*.oogl', '*.vrml', '*.obj', '*.iv', '*.pov',
                  '*.x3d']
    descriptions = ["PNG", "JPG", "TIFF", "Bitmap", "PostScript",
                    "EPS", "PDF", "Tex", "RIB", "WRL",
                    "Geomview", "VRML", "Wavefront", "Open Inventor",
                    "Povray", "X3D"]
    wildcard = ""
    for description, extension in zip(descriptions, extensions):
        wildcard += "{} ({})|{}|".format(description,
                                         extension,
                                         extension)
    wildcard += "Determine by extension (*.*)|(*.*)"

    dialog = FileDialog(
        parent=parent, title='Save scene to image',
        action='save as', default_filename="snapshot.png",
        wildcard=wildcard
    )
    if dialog.open() == OK:
        return dialog.path
    else:
        return ''
예제 #51
0
파일: manager.py 프로젝트: jirhiker/pychron
    def _file_dialog_(self, action, **kw):
        '''
        '''
#         print 'file_dialog', kw
        dlg = FileDialog(action=action, **kw)
        if dlg.open() == OK:
            return dlg.path
예제 #52
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()
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
예제 #54
0
 def on_export(self):
     """
     Shows a dialog to export a file
     """
     dialog = FileDialog(parent=self.window.control, action='save as')
     if dialog.open() == OK:
         self.view.export(dialog.path)
예제 #55
0
파일: graph.py 프로젝트: jirhiker/pychron
    def _save_(self, type_='pic', path=None):
        """
        """
        if path is None:
            dlg = FileDialog(action='save as')
            if dlg.open() == OK:
                path = dlg.path
                self.status_text = 'Image Saved: %s' % path

        if path is not None:
            if type_ == 'pdf':
                self._render_to_pdf(filename=path)
            else:
                # auto add an extension to the filename if not present
                # extension is necessary for PIL compression
                # set default save type_ DEFAULT_IMAGE_EXT='.png'

                # see http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html
                saved = False
                for ei in IMAGE_EXTENSIONS:
                    if path.endswith(ei):
                        self._render_to_pic(path)
                        saved = True
                        break

                if not saved:
                    self._render_to_pic(path + DEFAULT_IMAGE_EXT)
예제 #56
0
 def save(self):
     """ Save the current file.
     
     If needed, this code prompts for a path.
     
     Returns
     -------
     saved : bool
         Whether or not the file was saved.
     """
     editor = self.active_editor
     try:
         editor.save()
     except IOError:
         # If you are trying to save to a file that doesn't exist, open up a
         # FileDialog with a 'save as' action.
         dialog = FileDialog(
             parent=self.window.control,
             action='save as',
             wildcard='*.py',
         )
         if dialog.open() == OK:
             editor.save(dialog.path)
         else:
             return False
     return True
예제 #57
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()
예제 #58
0
파일: yasso.py 프로젝트: JariLiski/Yasso15
def save_file():
    wildcard='*.txt'
    dialog = FileDialog(title='Select the file to save as...',
        action='save as', wildcard=wildcard)
    if dialog.open() == Pyface_OK:
        return dialog.path
    return ''