Пример #1
0
        def accepted():
            try:
                shift, n = intintinput_dialog.sbOffset.value(
                ), intintinput_dialog.sbn.value()
                shift = shift % n
                i = 0

                self.selecting = True

                flags = QItemSelectionModel.Select
                selection = QItemSelection()

                for item in self.myModel.iterate_selected_items(
                        skip_groups=True,
                        skip_childs_in_selected_groups=False,
                        clear_selection=True):
                    if i % n == shift:
                        start_index = self.myModel.createIndex(
                            item.row(), 0, item)
                        end_index = self.myModel.createIndex(
                            item.row(), 1, item)

                        selection.select(start_index, end_index)

                    i += 1
                self.selectionModel().select(selection, flags)

            except Exception as ex:
                Logger.message(ex.__str__())
                QMessageBox.warning(self, 'Error', ex.__str__(),
                                    QMessageBox.Ok)
            finally:
                self.selecting = False
Пример #2
0
        def accepted():
            path, ext, delimiter, decimal_sep = dialog.result

            sp_list = get_hierarchic_list(
                self.myModel.iterate_selected_items(
                    skip_groups=True, skip_childs_in_selected_groups=False))

            try:
                list_to_files(
                    sp_list,
                    path,
                    ext,
                    include_group_name=self.
                    sett['/Public settings/Export/Files/Include group name'],
                    include_header=self.
                    sett['/Public settings/Export/Files/Include header'],
                    delimiter=delimiter,
                    decimal_sep=decimal_sep,
                    x_data_name=self.
                    sett['/Public settings/Plotting/Graph/X axis label'])

            except Exception as ex:
                QMessageBox.warning(self, 'Error', ex.__str__(),
                                    QMessageBox.Ok)

            Logger.message(f"Data were saved to {path}")
Пример #3
0
    def fit(self):

        try:
            self._fit()
        except Exception as e:
            Logger.message(e.__str__())
            QMessageBox.warning(self, 'Fitting Error', e.__str__(),
                                QMessageBox.Ok)
Пример #4
0
    def plot_function(self):

        # self._plot_function()
        try:

            self._plot_function()
        except Exception as e:
            Logger.message(e.__str__())
            QMessageBox.warning(self, 'Plotting Error', e.__str__(),
                                QMessageBox.Ok)
Пример #5
0
    def print_report(self):
        if self.fit_result is None:
            return
        try:
            report = "Fitting of '{}' succeeded. " \
                     "You can find fit results in variable " \
                     "'fit'.\n{}\n".format(self.spectrum.name,
                                           self.fit_result.report(print=False))

            Logger.console_message(report)
            Console.push_variables({'fit': self.fit_result})

        except Exception as e:
            Logger.message(e.__str__())
            QMessageBox.warning(self, 'Printing Error', e.__str__(),
                                QMessageBox.Ok)
Пример #6
0
        def accepted():

            if rename_dialog.cbTakeNamesFromList.isChecked():
                import csv
                splitted_list = csv.reader([rename_dialog.leList.text()],
                                           doublequote=True,
                                           skipinitialspace=True,
                                           delimiter=',').__next__()

                if len(splitted_list) == 0:
                    return
            expression, offset, c_mult_factor = rename_dialog.leExpression.text(
            ), rename_dialog.sbOffset.value(
            ), rename_dialog.leCounterMulFactor.text()

            try:
                i = 0
                for item in self.myModel.iterate_selected_items(
                        skip_groups=True,
                        skip_childs_in_selected_groups=False):
                    name = item.name
                    if not rename_dialog.cbTakeNamesFromList.isChecked():
                        name = rename(expression, name,
                                      float(offset) * float(c_mult_factor))
                        offset += 1
                    else:
                        try:
                            name = splitted_list[i].strip()
                            i += 1
                        except IndexError:
                            pass
                    item.name = name

                self.redraw_spectra.emit()
                self.update_view()
                self.state_changed.emit()

                self.sett[
                    '/Private settings/Last rename expression'] = expression
                self.sett[
                    '/Private settings/Last rename name taken from list'] = rename_dialog.cbTakeNamesFromList.isChecked(
                    )
                self.sett.save()
            except Exception as ex:
                Logger.message(ex.__str__())
                QMessageBox.warning(self, 'Error', ex.__str__(),
                                    QMessageBox.Ok)
Пример #7
0
    def save(cls):

        sett_dict = cls.get_attributes()

        try:

            with open(cls.get_config_filepath(), "w") as file:
                json.dump(sett_dict,
                          file,
                          sort_keys=False,
                          indent=4,
                          separators=(',', ': '))

        except Exception as ex:
            Logger.message(
                "Error saving settings to file {}. Error message:\n{}".format(
                    Settings._config_filename, ex.__str__()))
Пример #8
0
    def serialize(self, filepath):
        try:
            with open(filepath, 'bw') as file:
                pickle.dump(self, file)

            # try:
            # except:
            #     pass

            # with bz2.BZ2File(filepath, 'w', compresslevel=COMPRESS_LEVEL) as file:
            #     pickle.dump(self, file)

        # except pickle.PicklingError as err:
        #     Logger.console_message("Unable to save current project:\n{}\n{}".format(err.__str__(), err.__traceback__))
        #     raise Exception
        except Exception as err:
            Logger.message("Unable to save current project:\n{}".format(
                err.__str__()))
            raise
Пример #9
0
    def load(cls):
        # basically static constructor method, set up default settings instance
        if Settings._inst_default_settings is None:
            Settings._inst_default_settings = Settings()

        try:
            with open(cls.get_config_filepath(), "r") as file:
                data = json.load(file)

            # instance = object.__new__(cls)

            for key, value in data.items():
                setattr(cls, key, value)

        except Exception as ex:
            Logger.message(
                "Error loading settings from file {}, setting up default settings. Error message:\n{}"
                .format(Settings._config_filename, ex.__str__()))
            Settings.save()
Пример #10
0
        def accepted():
            # Logger.status_message("Baseline correcting...")
            x0, x1 = rng_dialog.returned_range
            try:
                items = []
                for item in self.myModel.iterate_selected_items(
                        skip_groups=True,
                        skip_childs_in_selected_groups=False):
                    item.baseline_correct_no_update(x0, x1)
                    items.append(item)

                self.data_modified(items)
                self.state_changed.emit()
            except ValueError as ex:
                Logger.message(ex.__str__())
                QMessageBox.warning(self, 'Warning', ex.__str__(),
                                    QMessageBox.Ok)
                return

            Logger.status_message("Done")
Пример #11
0
    def copy_selected_items_to_clipboard(self):

        sp_list = get_hierarchic_list(
            self.myModel.iterate_selected_items(
                skip_groups=True, skip_childs_in_selected_groups=False))

        if len(sp_list) == 0:
            return

        Logger.status_message("Copying selected items to clipboard...")
        try:

            delimiter = get_delimiter_from_idx(
                self.sett['/Public settings/Export/Clipboard/Delimiter'])

            output = list_to_string(
                sp_list,
                include_group_name=self.
                sett['/Public settings/Export/Clipboard/Include group name'],
                include_header=self.
                sett['/Public settings/Export/Clipboard/Include header'],
                delimiter=delimiter,
                decimal_sep=self.
                sett['/Public settings/Export/Clipboard/Decimal separator'],
                x_data_name=self.
                sett['/Public settings/Plotting/Graph/X axis label'])
            cb = QApplication.clipboard()
            cb.clear(mode=cb.Clipboard)
            cb.setText(output, mode=cb.Clipboard)

        except Exception as ex:
            Logger.message(ex.__str__())
            return

        Logger.status_message("Done")
Пример #12
0
    def save_general_model_as(self):
        if self.current_general_model is None:
            return
        curr_model_path = self.gen_models_paths[
            self.cbGenModels.currentIndex()]
        fil = "Json (*.json)"

        filepath = QFileDialog.getSaveFileName(
            caption="Save Custom Kinetic Model",
            directory=curr_model_path,
            filter=fil,
            initialFilter=fil)
        if filepath[0] == '':
            return

        try:
            init, _, rates, _ = self.get_params_from_fields()
            self.current_general_model.scheme = self.pteScheme.toPlainText()
            self.current_general_model.set_rates(rates)
            self.current_general_model.initial_conditions = dict(
                zip(self.current_general_model.get_compartments(), init))
            self.current_general_model.save(filepath[0])
        except Exception as e:
            Logger.message(e.__str__())
            QMessageBox.critical(self, 'Saving error',
                                 'Error, first build the model.',
                                 QMessageBox.Ok)
            return

        self.update_general_models()
        k = 0
        for k, fpath in enumerate(self.gen_models_paths):
            fname = os.path.splitext(os.path.split(fpath)[1])[0]
            if fname == os.path.splitext(os.path.split(filepath[0])[1])[0]:
                break

        # set saved model as current index
        self.cbGenModels.setCurrentIndex(k)
Пример #13
0
    def parse_XML_Spreadsheet(self, byte_data):

        Logger.status_message(
            "Parsing XML Spreadsheet from clipboard Mime data...")
        try:
            # get bytes from QMimeData, remove the last character and convert to string
            xml_data = byte_data[:-1].decode("utf-8")

            spectra = parse_XML_Spreadsheet(xml_data)
            self.import_spectra(spectra)
        except Exception as ex:
            Logger.message(
                "Error reading XML Spreadsheet from clipboard Mime data.\n{}".
                format(ex.__str__()))
            return

        Logger.status_message("Done")
Пример #14
0
    def build_gen_model(self, load_scheme=True):
        if load_scheme:
            try:
                self.current_general_model = GeneralModel.from_text(
                    self.pteScheme.toPlainText())
            except Exception as e:
                Logger.message(e.__str__())
                QMessageBox.critical(self, 'Build failed',
                                     f'Invalid model:\n\n{e.__str__()}',
                                     QMessageBox.Ok)
                return

        self.current_general_model.build_func()

        comps = self.current_general_model.get_compartments()
        init_comps_names = list(map(lambda n: f'[{n}]0', comps))
        rates = self.current_general_model.get_rates(
            self.cbShowBackwardRates.isChecked(), append_values=True)

        n_params = 2 * len(comps) + len(rates) + 1  # + intercept
        self.set_field_visible(n_params, 1)

        self.general_model_params = Parameters()

        k = 0
        # initial conditions
        for init in self.current_general_model.initial_conditions.values():
            self.general_model_params.add(f'param{k}',
                                          value=init,
                                          vary=False,
                                          min=0,
                                          max=np.inf)
            k += 1
        # coefficients
        for i in range(len(comps)):
            self.general_model_params.add(f'param{k}',
                                          value=1 if i == 0 else 0,
                                          vary=True if i == 0 else False,
                                          min=-np.inf,
                                          max=np.inf)
            k += 1

        # rates
        rates_names = []
        for name, value in rates:
            rates_names.append(name)
            self.general_model_params.add(f'param{k}',
                                          value=value,
                                          vary=True,
                                          min=0,
                                          max=np.inf)
            k += 1

        # add intercept
        self.general_model_params.add('y0',
                                      value=0,
                                      vary=True,
                                      min=-np.inf,
                                      max=np.inf)

        for i, (p, name) in enumerate(
                zip(self.general_model_params.values(),
                    init_comps_names + comps + rates_names + ['y0'])):
            self.params_list[i][1].setText(name)
            self.value_list[i][1].setText(f"{p.value:.5g}")
            self.lower_bound_list[i][1].setText(str(p.min))
            self.upper_bound_list[i][1].setText(str(p.max))
            self.fixed_list[i][1].setChecked(not p.vary)

        self.set_lower_upper_enabled()