def _window_length_changed(self, new):
        if new <= self.polynomial_order:
            dialog = MessageDialog(
                title='Attention!',
                message='Window length must be bigger than polynomial order.')
            dialog.open()

        if new % 2 == 0 or new <= 0:
            dialog = MessageDialog(
                title='Attention!',
                message='Window length must be odd positive integer.')
            dialog.open()
    def _polynomial_order_changed(self, new):

        if new >= self.window_length:
            dialog = MessageDialog(
                title='Attention!',
                message='Polynomial order must be less than window length.')
            dialog.open()
Beispiel #3
0
    def _add_creep_plot_fired(self):

        plt = self.figure
        if (len(self.plot_list) >= self.plots_num):
            dialog = MessageDialog(
                title='Attention!', message='Max plots number is {}'.format(self.plots_num))
            dialog.open()
            return

        disp_max = self.x_axis_multiplier * \
            np.load(os.path.join(self.npy_folder_path,
                                 self.file_name + '_' + self.x_axis + '_max.npy'))
        disp_min = self.x_axis_multiplier * \
            np.load(os.path.join(self.npy_folder_path,
                                 self.file_name + '_' + self.x_axis + '_min.npy'))

        print('Adding creep plot...')
        mpl.rcParams['agg.path.chunksize'] = 50000

        self.apply_new_subplot()
        plt.xlabel('Cycles number')
        plt.ylabel('mm')
        plt.title('Fatigue creep curve', fontsize=20)
        plt.plot(np.arange(0, disp_max.size), disp_max,
                 'k', linewidth=0.8, color='red')
        plt.plot(np.arange(0, disp_min.size), disp_min,
                 'k', linewidth=0.8, color='green')

        self.plot_list.append('Plot {}'.format(len(self.plot_list) + 1))

        print('Finished adding creep plot!')
 def max_plots_number_is_reached(self):
     if len(self.plot_list) >= self.plots_num:
         dialog = MessageDialog(title='Attention!',
                                message='Max plots number is {}'.format(
                                    self.plots_num))
         dialog.open()
         return True
     else:
         return False
 def npy_files_exist(self, path):
     if os.path.exists(path) == True:
         return True
     else:
         dialog = MessageDialog(
             title='Attention!',
             message='Please parse csv file to generate npy files first.'.
             format(self.plots_num))
         dialog.open()
         return False
 def filtered_and_creep_npy_files_exist(self, path):
     if os.path.exists(path) == True:
         return True
     else:
         dialog = MessageDialog(
             title='Attention!',
             message='Please generate filtered and creep npy files first.'.
             format(self.plots_num))
         dialog.open()
         return False
Beispiel #7
0
    def _get_h5_tree(self):

        if self.filename is None:
            return None
        try:
            self.h5file = openFile(self.filename, "a")
            return _hdf5_tree(self.h5file)
        except Exception, exc:
            dlg = MessageDialog(title='Could not open file %s' % self.filename,
                                message=str(exc))
            dlg.open()
            return None
    def test_text_format(self):
        dialog = MessageDialog(
            parent=None,
            title="Dialog title",
            message="Printer on fire",
            informative="Your printer is on fire",
            details="Temperature exceeds 1000 degrees",
            severity="error",
            text_format="plain",
            size=(600, 400),
        )

        with self.create_dialog(dialog):
            text_format = dialog.control.textFormat()
            self.assertEqual(text_format, QtCore.Qt.TextFormat.PlainText)
    def test_on_message_dialog(self):
        dialog = MessageDialog()
        tester = ModalDialogTester(dialog.open)

        # accept
        tester.open_and_run(when_opened=lambda x: x.close(accept=True))
        self.assertTrue(tester.value_assigned())
        self.assertEqual(tester.result, OK)
        self.assertTrue(tester.dialog_was_opened)

        # reject
        tester.open_and_run(when_opened=lambda x: x.close())
        self.assertTrue(tester.value_assigned())
        self.assertEqual(tester.result, CANCEL)
        self.assertTrue(tester.dialog_was_opened)
    def test_escape_button_no_details(self):
        dialog = MessageDialog(
            parent=None,
            title="Dialog title",
            message="Printer on fire",
            informative="Your printer is on fire",
            severity="error",
            size=(600, 400),
        )

        with self.create_dialog(dialog):
            escape_button = dialog.control.escapeButton()
            ok_button = dialog.control.button(QtGui.QMessageBox.Ok)
            # It's possible for both the above to be None, so double check.
            self.assertIsNotNone(escape_button)
            self.assertIs(escape_button, ok_button)
Beispiel #11
0
    def exception_handler(self, exc_type, exc_value, exc_traceback):
        """ Handle un-handled exceptions """
        if not isinstance(exc_value, Exception):
            # defer to usual exception handler
            sys.__excepthook__(exc_type, exc_value, exc_traceback)

        logging.error('Unhandled exception:', exc_info=(exc_type, exc_value, exc_traceback))

        from traceback import format_tb
        from pyface.api import MessageDialog

        informative = "{0}: {1}".format(exc_type.__name__, str(exc_value))
        detail = '\n'.join(format_tb(exc_traceback))
        dlg = MessageDialog(severity='error', message="Unhandled Exception",
                            informative=informative, detail=detail,
                            size=(800,600))
        dlg.open()
    def test_capture_errors_on_failure(self):
        dialog = MessageDialog()
        tester = ModalDialogTester(dialog.open)

        def failure(tester):
            try:
                with tester.capture_error():
                    # this failure will appear in the console and get recorded
                    self.fail()
            finally:
                tester.close()

        with self.assertRaises(AssertionError):
            alt_stderr = io.StringIO
            with silence_output(err=alt_stderr):
                tester.open_and_run(when_opened=failure)
            self.assertIn('raise self.failureException(msg)', alt_stderr)
    def test_capture_errors_on_error(self):
        dialog = MessageDialog()
        tester = ModalDialogTester(dialog.open)

        def raise_error(tester):
            try:
                with tester.capture_error():
                    # this error will appear in the console and get recorded
                    1 / 0
            finally:
                tester.close()

        with self.assertRaises(ZeroDivisionError):
            alt_stderr = io.StringIO
            with silence_output(err=alt_stderr):
                tester.open_and_run(when_opened=raise_error)
            self.assertIn('ZeroDivisionError', alt_stderr)
    def close(self, info, is_ok):
        """ Handles the user attempting to close the dialog.

        If it is via the OK dialog button, try to create an account before
        closing. If this fails, display an error message and veto the close
        by returning false.
        """
        if is_ok:
            success, message = info.model.create_account()
            if not success:
                dlg = MessageDialog(message="Cannot create account",
                                    informative=message,
                                    severity='error')
                dlg.open()
                return False

        return True
Beispiel #15
0
    def _add_plot_fired(self):

        if False:  # (len(self.plot_list) >= self.plots_num):
            dialog = MessageDialog(
                title='Attention!', message='Max plots number is {}'.format(self.plots_num))
            dialog.open()
            return

        print('Loading npy files...')

        if self.apply_filters:
            x_axis_name = self.x_axis + '_filtered'
            y_axis_name = self.y_axis + '_filtered'
            x_axis_array = self.x_axis_multiplier * \
                np.load(os.path.join(self.npy_folder_path,
                                     self.file_name + '_' + self.x_axis + '_filtered.npy'))
            y_axis_array = self.y_axis_multiplier * \
                np.load(os.path.join(self.npy_folder_path,
                                     self.file_name + '_' + self.y_axis + '_filtered.npy'))
        else:
            x_axis_name = self.x_axis
            y_axis_name = self.y_axis
            x_axis_array = self.x_axis_multiplier * \
                np.load(os.path.join(self.npy_folder_path,
                                     self.file_name + '_' + self.x_axis + '.npy'))
            y_axis_array = self.y_axis_multiplier * \
                np.load(os.path.join(self.npy_folder_path,
                                     self.file_name + '_' + self.y_axis + '.npy'))

        print('Adding Plot...')
        mpl.rcParams['agg.path.chunksize'] = 50000

#        plt.figure(self.plot_figure_num)
        ax = self.figure.add_subplot(1, 1, 1)

        ax.set_xlabel('Displacement [mm]')
        ax.set_ylabel('kN')
        ax.set_title('Original data', fontsize=20)
        ax.plot(x_axis_array, y_axis_array, 'k', linewidth=0.8)

        self.plot_list.append('{}, {}'.format(x_axis_name, y_axis_name))
        self.data_changed = True
        print('Finished adding plot!')
Beispiel #16
0
 def _batch_proc_fired(self):
     new_dir = DirectoryDialog(
         new_directory=True,
         message='Choose a directory to save batch-processed files')
     if new_dir.open() != OK:
         return
     if new_dir.path == self.file_dir:
         MessageDialog(
             message=
             'Not letting you over-write the current directory!! Choose another'
         ).open()
         return
     file_names = self.working_files
     file_objs = [self._file_map[f] for f in file_names]
     print('Batch path:', new_dir.path)
     if self.batch_with_handoff:
         handoff_filter_hdf5_files(file_objs, new_dir.path, self.filters)
     else:
         batch_filter_hdf5_files(file_objs, new_dir.path, self.filters)
     self.filters.save_pipeline(os.path.join(new_dir.path, 'filters.txt'))
Beispiel #17
0
    def launch(self):
        if not os.path.exists(self.file_data.file):
            return

        # Logic to normalize channel mapping
        # TODO: handle reference channels correctly
        if self.chan_map == 'unknown':
            try:
                nc = np.array(list(map(int, self.skip_chan.split(','))))
            except:
                nc = []
            geo = list(map(int, self.elec_geometry.split(',')))
            n_sig_chan = self.n_chan - len(nc)
            chan_map = ChannelMap(np.arange(n_sig_chan), geo)
        elif self.chan_map == 'active':
            chan_map, nc = self.file_data.make_channel_map()
        elif self.chan_map in _subset_chan_maps:
            cnx = self.chan_map_connectors.split(',')
            cnx = [c.strip() for c in cnx]
            chan_map, nc, rf = get_electrode_map(self.chan_map, connectors=cnx)
            nc = list(set(nc).union(rf))
        elif self.chan_map in _subset_shortcuts:
            cnx = _subset_shortcuts[self.chan_map]
            map_name, shortcut = self.chan_map.split('/')
            chan_map, nc, rf = get_electrode_map(map_name, connectors=cnx)
            nc = list(set(nc).union(rf))
        elif self.chan_map == 'settable':
            chan_map = self.set_chan_map
            nc = []
        elif self.chan_map == 'pickled':
            try:
                chan_map = find_pickled_map(self.file_data.file)
                nc = []
            except NoPickleError:
                MessageDialog(message='No pickled ChannelMap').open()
                return
        else:
            chan_map, nc, rf = get_electrode_map(self.chan_map)
            nc = list(set(nc).union(rf))

        # Check for transposed active data (coming from matlab)
        if isinstance(self.file_data,
                      ActiveArrayFileData) and self.file_data.is_transpose:
            self.file_data.create_transposed()
            print(self.file_data.file)

        with h5py.File(self.file_data.file, 'r') as h5:
            #x_scale = h5[self.file_data.fs_field].value ** -1.0
            x_scale = self.file_data.Fs**-1.0
            array_size = h5[self.file_data.data_field].shape[0]
        num_vectors = len(chan_map) + len(nc)

        data_channels = [
            self.file_data.data_channels[i] for i in range(num_vectors)
            if i not in nc
        ]

        # permute  channels to stack rows
        chan_idx = list(zip(*chan_map.to_mat()))
        chan_order = chan_map.lookup(*list(zip(*sorted(chan_idx)[::-1])))
        data_channels = [data_channels[i] for i in chan_order]
        cls = type(chan_map)
        chan_map = cls([chan_map[i] for i in chan_order],
                       chan_map.geometry,
                       pitch=chan_map.pitch,
                       col_major=chan_map.col_major)

        filters = self.filters.make_pipeline(x_scale**-1.0)
        array = self.file_data._compose_arrays(filters)
        if self.screen_channels:
            data_channels, chan_map = \
              self._get_screen(array, data_channels, chan_map, x_scale**-1.0)

        rm = np.zeros((array_size, ), dtype='?')
        rm[data_channels] = True

        nav = h5mean(array.file_array, 0, rowmask=rm)
        nav *= self.file_data.y_scale

        modules = [ana_modules[k] for k in self.module_set]
        new_vis = FastScroller(array,
                               self.file_data.y_scale,
                               self.offset * 1e-6,
                               chan_map,
                               nav,
                               x_scale=x_scale,
                               load_channels=data_channels,
                               max_zoom=self.max_window_width)
        file_name = os.path.split(self.file_data.file)[1]
        file_name = os.path.splitext(file_name)[0]
        v_win = VisWrapper(new_vis,
                           x_scale=x_scale,
                           chan_map=chan_map,
                           y_spacing=self.offset,
                           modules=modules,
                           recording=file_name)
        view = v_win.default_traits_view()
        # TODO: it would be nice to be able to directly call launch() without first showing *this* object's panel
        view.kind = 'live'
        ui = v_win.edit_traits(view=view)
        return v_win