Ejemplo n.º 1
0
    def _save_target_and_recoils(self, thread=False):
        """
        Save target and element simulations.

        Args:
            thread: Whether saving happens in a thread or by pressing the
            button.
        """
        if not thread and self.statusbar is not None:
            sbh = StatusBarHandler(self.statusbar)
            reporter = sbh.reporter
        else:
            reporter = None

        if self.target.name:
            target_name = self.target.name
        else:
            target_name = "temp"

        target_path = Path(self.simulation.directory, f"{target_name}.target")
        self.target.to_file(target_path)

        if not thread and reporter is not None:
            reporter.report(50)
            sub_reporter = reporter.get_sub_reporter(lambda x: 50 + 0.5 * x)
        else:
            sub_reporter = None

        self.recoil_distribution_widget.save_mcsimu_rec_profile(
            self.simulation.directory, progress=sub_reporter)

        if reporter is not None:
            reporter.report(100)
Ejemplo n.º 2
0
 def measurement_save_cuts(self):
     """Save measurement selections to cut files.
     """
     sbh = StatusBarHandler(self.statusbar)
     self.obj.save_cuts(progress=sbh.reporter)
     # Do for all slaves if master.
     self.obj.request.save_cuts(self.obj)
Ejemplo n.º 3
0
    def __calculate_selected_spectra(self, *_):
        """Calculate selected spectra.
        """
        EnergySpectrumParamsDialog.bin_width = self.used_bin_width

        sbh = StatusBarHandler(self.statusbar)

        # Get all
        used_simulations = self.get_selected_simulations()
        used_measurements = self.get_selected_measurements()
        used_externals = self.external_files

        sbh.reporter.report(33)

        # Calculate espes for simulations
        for elem_sim, lst in used_simulations.items():
            for d in lst:
                _, espe_file = elem_sim.calculate_espe(**d,
                                                       write_to_file=True,
                                                       ch=self.bin_width)
                self.result_files.append(espe_file)

        sbh.reporter.report(66)

        # Calculate espes for measurements. 'no_foil' parameter is used to
        # make the results comparable with simulation espes. Basically
        # this increases the calculated energy values, shifting the espe
        # histograms to the right on the x axis.
        for mesu, lst in used_measurements.items():
            self.result_files.extend(d["result_file"] for d in lst)
            # TODO use the return values instead of reading the files further
            #   down the execution path
            EnergySpectrum.calculate_measured_spectra(
                mesu, [d["cut_file"] for d in lst],
                self.bin_width,
                use_efficiency=self.use_efficiency,
                no_foil=True)

        # Add external files
        self.result_files.extend(used_externals)

        sbh.reporter.report(100)

        simulation_name = self.element_simulation.simulation.name
        msg = f"Created Energy Spectrum. " \
              f"Bin width: {self.bin_width} " \
              f"Used files: {', '.join(str(f) for f in self.result_files)}"

        logging.getLogger("request").info(f"[{simulation_name}] {msg}")
        logging.getLogger(simulation_name).info(msg)
        self.close()
Ejemplo n.º 4
0
    def load_selections(self):
        """Show dialog to load selections.
        """
        filename = open_file_dialog(self, self.measurement.directory,
                                    "Load Element Selection",
                                    "Selection file (*.selections)")
        if filename:
            sbh = StatusBarHandler(self.statusbar)
            sbh.reporter.report(40)

            self.measurement.load_selection(
                filename,
                progress=sbh.reporter.get_sub_reporter(lambda x: 40 + 0.6 * x))
            self.on_draw()
            self.elementSelectionSelectButton.setEnabled(True)

            sbh.reporter.report(100)

        self.__emit_selections_changed()
Ejemplo n.º 5
0
    def __import_files(self):
        """Import binary files.
        """
        sbh = StatusBarHandler(self.__statusbar)
        sbh.reporter.report(10)
        
        root = self.treeWidget.invisibleRootItem()
        root_child_count = root.childCount()

        for i in range(root_child_count):
            item = root.child(i)
            input_file = item.file

            output_file = df.import_new_measurement(
                self.request, self.parent, item)
            self.__convert_file(input_file, output_file)

            sbh.reporter.report(10 + (i + 1 / root_child_count) * 90)

        sbh.reporter.report(100)
        self.imported = True

        self.close()
Ejemplo n.º 6
0
    def _accept_params(self, *_):
        """Accept given parameters.

        Args:
            *_: unused event args
        """
        self.status_msg = ""
        sbh = StatusBarHandler(self.statusbar)
        sbh.reporter.report(10)

        try:
            output_dir = self.measurement.get_depth_profile_dir()

            # Get the filepaths of the selected items
            used_cuts = self.used_cuts
            DepthProfileDialog.checked_cuts[self.measurement.name] = set(
                used_cuts)
            # TODO could take care of RBS selection here
            elements = [
                Element.from_string(fp.name.split(".")[1]) for fp in used_cuts
            ]

            x_unit = self.x_axis_units

            DepthProfileDialog.x_unit = x_unit
            DepthProfileDialog.line_zero = self.show_zero_line
            DepthProfileDialog.line_scale = self.show_scale_line
            DepthProfileDialog.systerr = self.systematic_error
            DepthProfileDialog.used_eff = self.show_used_eff

            DepthProfileDialog.eff_files_str = self.eff_files_str

            sbh.reporter.report(20)

            # If items are selected, proceed to generating the depth profile
            if used_cuts:
                self.status_msg = "Please wait. Creating depth profile."
                if self.parent.depth_profile_widget:
                    self.parent.del_widget(self.parent.depth_profile_widget)

                # If reference density changed, update value to measurement
                if x_unit == DepthProfileUnit.NM:
                    _, _, _, profile, measurement = \
                        self.measurement.get_used_settings()
                    if profile.reference_density != self.reference_density:
                        profile.reference_density = self.reference_density
                        measurement.to_file()

                self.parent.depth_profile_widget = DepthProfileWidget(
                    self.parent,
                    output_dir,
                    used_cuts,
                    elements,
                    x_unit,
                    DepthProfileDialog.line_zero,
                    DepthProfileDialog.used_eff,
                    DepthProfileDialog.line_scale,
                    DepthProfileDialog.systerr,
                    DepthProfileDialog.eff_files_str,
                    progress=sbh.reporter.get_sub_reporter(
                        lambda x: 30 + 0.6 * x))

                sbh.reporter.report(90)

                icon = self.parent.icon_manager.get_icon(
                    "depth_profile_icon_2_16.png")
                self.parent.add_widget(self.parent.depth_profile_widget,
                                       icon=icon)
                self.close()
            else:
                self.status_msg = "Please select .cut file[s] to create " \
                                  "depth profiles."
        except Exception as e:
            error_log = f"Exception occurred when trying to create depth " \
                        f"profiles: {e}"
            self.measurement.log_error(error_log)
        finally:
            sbh.reporter.report(100)
Ejemplo n.º 7
0
    def __import_files(self):
        """Import listed files with settings defined in the dialog.
        """
        sbh = StatusBarHandler(self.statusbar)
        string_columns = []

        for i in range(self.grid_column.rowCount()):
            item = self.grid_column.itemAtPosition(i, 0)
            if not item.isEmpty():
                combo_widget = self.grid_column.itemAtPosition(i, 1).widget()
                # combo_widget = combo_item
                cur_index = combo_widget.currentIndex()
                cur_text = combo_widget.currentText()
                adc = int(re.sub(r"ADC ([0-9]+).*", r"\1", cur_text))
                # + 1 since actual column, not index
                column_index = adc * 2 + cur_index % 2 + 1
                string_columns.append("${0}".format(column_index))
        string_column = ",".join(string_columns)

        root = self.treeWidget.invisibleRootItem()
        root_child_count = root.childCount()
        timing = dict()
        for coinc_timing in self.__added_timings.values():
            if coinc_timing.is_not_trigger:
                timing[coinc_timing.adc] = (coinc_timing.low.value(),
                                            coinc_timing.high.value())
        start_time = timer()

        sbh.reporter.report(10)

        filename_list = []
        for i in range(root_child_count):
            item = root.child(i)
            filename_list.append(item.filename)

            output_file = df.import_new_measurement(self.request, self.parent,
                                                    item)
            gf.coinc(Path(item.file),
                     output_file=output_file,
                     skip_lines=self.spin_skiplines.value(),
                     tablesize=10,
                     trigger=self.spin_adctrigger.value(),
                     adc_count=self.spin_adccount.value(),
                     timing=timing,
                     columns=string_column,
                     nevents=self.spin_eventcount.value())

            sbh.reporter.report(10 + (i + 1) / root_child_count * 90)

        filenames = ", ".join(filename_list)
        elapsed = timer() - start_time
        log = "Imported measurements to request: {0}".format(filenames)
        log_var = "Variables used: {0} {1} {2} {3} {4}".format(
            "Skip lines: " + str(self.spin_skiplines.value()),
            "ADC trigger: " + str(self.spin_adctrigger.value()),
            "ADC count: " + str(self.spin_adccount.value()),
            "Timing: " + str(timing),
            "Event count: " + str(self.spin_eventcount.value()))
        log_elapsed = "Importing finished {0} seconds".format(int(elapsed))
        logging.getLogger("request").info(log)
        logging.getLogger("request").info(log_var)
        logging.getLogger("request").info(log_elapsed)

        sbh.reporter.report(100)
        self.imported = True
        self.close()
Ejemplo n.º 8
0
 def __save_splits(self):
     sbh = StatusBarHandler(self.statusbar)
     self.losses.save_splits(progress=sbh.reporter.get_sub_reporter(
         lambda x: 0.9 * x
     ))
     sbh.reporter.report(100)
Ejemplo n.º 9
0
    def __accept_params(self, *_):
        """Called when OK button is pressed. Creates a elementlosses widget and
        adds it to the parent (mdiArea).

        Args:
            *_: unused event args
        """
        self.status_msg = ""
        sbh = StatusBarHandler(self.statusbar)

        y_axis_0_scale = self.radioButton_0max.isChecked()
        reference_cut = self.used_reference_cut
        split_count = self.partitionCount.value()
        m_name = self.measurement.name
        used_cuts = self.used_cuts
        ElementLossesDialog.checked_cuts[m_name] = set(used_cuts)

        if y_axis_0_scale:
            y_scale = 0
        else:
            y_scale = 1

        ElementLossesDialog.reference_cut[m_name] = \
            self.referenceCut.currentText()
        ElementLossesDialog.split_count = split_count
        ElementLossesDialog.y_scale = y_scale

        sbh.reporter.report(25)

        if used_cuts:
            if self.parent.elemental_losses_widget:
                self.parent.del_widget(self.parent.elemental_losses_widget)

            self.parent.elemental_losses_widget = ElementLossesWidget(
                self.parent, self.measurement, reference_cut, used_cuts,
                split_count, y_scale, statusbar=self.statusbar,
                progress=sbh.reporter.get_sub_reporter(
                    lambda x: 25 + 0.70 * x
                ))
            icon = self.parent.icon_manager \
                .get_icon("elemental_losses_icon_16.png")
            self.parent.add_widget(self.parent.elemental_losses_widget,
                                   icon=icon)

            msg = f"Created Element Losses. Splits: {split_count} " \
                  f"Reference cut: {reference_cut} " \
                  f"List of cuts: {used_cuts}"
            self.measurement.log(msg)

            log_info = "Elemental Losses split counts:\n"

            split_counts = self.parent.elemental_losses_widget.split_counts
            splitinfo = "\n".join(
                ["{0}: {1}".format(
                    key, ", ".join(str(v) for v in split_counts[key]))
                    for key in split_counts])
            self.measurement.log(log_info + splitinfo)

            sbh.reporter.report(100)
            self.close()
        else:
            self.status_msg = "Please select .cut file[s] to create element " \
                              "losses."
        sbh.reporter.report(100)
Ejemplo n.º 10
0
    def __init__(self,
                 parent: BaseTab,
                 spectrum_type: str = MEASUREMENT,
                 use_cuts=None,
                 bin_width=0.025,
                 use_efficiency=False,
                 save_file_int=0,
                 statusbar=None,
                 spectra_changed=None):
        """Inits widget.
        
        Args:
            parent: A TabWidget.
            use_cuts: A string list representing Cut files.
            bin_width: A float representing Energy Spectrum histogram's bin
                width.
            use_efficiency: whether efficiency is taken into account when
                measured spectra is calculated
            save_file_int: n integer to have unique save file names for
                simulation energy spectra combinations.
            spectra_changed: pyqtSignal that indicates a change in energy
                spectra.
        """
        sbh = None
        super().__init__()
        uic.loadUi(gutils.get_ui_dir() / "ui_energy_spectrum.ui", self)
        try:
            self.parent = parent
            self.icon_manager = parent.icon_manager
            self.progress_bar = None
            if use_cuts is None:
                use_cuts = []
            self.use_cuts = use_cuts
            self.bin_width = bin_width
            self.energy_spectrum_data = {}
            self.spectrum_type = spectrum_type
            rbs_list = {}

            title = f"{self.windowTitle()} - Bin Width: {bin_width}"
            self.setWindowTitle(title)

            if isinstance(self.parent.obj, Measurement):
                self.measurement = self.parent.obj

                # Removal is done in the finally block so autoremove
                # is set to False
                sbh = StatusBarHandler(statusbar, autoremove=False)

                # Do energy spectrum stuff on this
                self.energy_spectrum_data = \
                    EnergySpectrum.calculate_measured_spectra(
                        self.measurement, use_cuts, bin_width,
                        progress=sbh.reporter, use_efficiency=use_efficiency
                    )

                # Check for RBS selections.
                rbs_list = cut_file.get_rbs_selections(self.use_cuts)
            else:
                self.simulation = self.parent.obj
                self.save_file_int = save_file_int
                self.save_file = f"widget_energy_spectrum_{save_file_int}.save"
                for file in use_cuts:
                    self.energy_spectrum_data[file] = GetEspe.read_espe_file(
                        file)

            # Graph in matplotlib widget and add to window
            self.matplotlib = MatplotlibEnergySpectrumWidget(
                self,
                self.energy_spectrum_data,
                rbs_list,
                spectrum_type,
                spectra_changed=spectra_changed,
                channel_width=bin_width)
        except (PermissionError, IsADirectoryError, FileNotFoundError) as e:
            # If the file path points to directory, this will either raise
            # PermissionError (Windows) or IsADirectoryError (Mac)
            msg = f"Could not create Energy Spectrum graph: {e}"
            self.parent.obj.log_error(msg)

            if hasattr(self, "matplotlib"):
                self.matplotlib.delete()
            self.matplotlib = None
        finally:
            if sbh is not None:
                sbh.remove_progress_bar()
Ejemplo n.º 11
0
 def save_cuts(self):
     """Save measurement cuts.
     """
     sbh = StatusBarHandler(self.statusbar)
     self.measurement.save_cuts(progress=sbh.reporter)
     self.__emit_save_cuts()