Пример #1
0
    def test_reading_empty_or_half_file(self):
        """If the ini file is empty or keys are missing, GlobalSettings
        reverts to default values."""
        with tempfile.TemporaryDirectory() as tmp_dir:
            ini_file = Path(tmp_dir, "potku2.ini")
            open(ini_file, "a").close()
            gs = GlobalSettings(tmp_dir, save_on_creation=False)
            # Update directories
            self.gs.set_config_dir(tmp_dir)
            self.gs.set_request_directory(Path(tmp_dir, "requests"))
            self.gs.set_request_directory_last_open(Path(tmp_dir, "requests"))
            self.assert_settings_equal(self.gs, gs)

            # Save the file
            self.gs.save_config()
            # Remove every second line from the ini file
            with open(ini_file, "r") as f:
                lines = f.readlines()
            self.assertTrue(1 < len(lines))
            with open(ini_file, "w") as f:
                for line in lines[::2]:
                    f.write(line)

            gs = GlobalSettings(tmp_dir, save_on_creation=False)
            self.assert_settings_equal(self.gs, gs, only_check_same_size=True)
Пример #2
0
    def __init__(self,
                 parent: BaseTab,
                 measurement: Measurement,
                 global_settings: GlobalSettings,
                 statusbar: Optional[QtWidgets.QStatusBar] = None):
        """Inits depth profile dialog.
        
        Args:
            parent: a MeasurementTabWidget.
            measurement: a Measurement object
            global_settings: a GlobalSettings object
            statusbar: a QStatusBar object
        """
        super().__init__()
        uic.loadUi(gutils.get_ui_dir() / "ui_depth_profile_params.ui", self)

        self.parent = parent
        self.measurement = measurement
        self.statusbar = statusbar

        # Connect buttons
        self.OKButton.clicked.connect(self._accept_params)
        self.cancelButton.clicked.connect(self.close)

        locale = QLocale.c()
        self.spin_systerr.setLocale(locale)
        self.sbox_reference_density.setLocale(locale)

        m_name = self.measurement.name
        if m_name not in DepthProfileDialog.checked_cuts:
            DepthProfileDialog.checked_cuts[m_name] = set()

        gutils.fill_cuts_treewidget(self.measurement,
                                    self.treeWidget.invisibleRootItem(),
                                    use_elemloss=True)
        self.used_cuts = DepthProfileDialog.checked_cuts[m_name]

        gutils.set_btn_group_data(self.group_x_axis_units, DepthProfileUnit)
        self.x_axis_units = DepthProfileDialog.x_unit
        if self.x_axis_units == DepthProfileUnit.NM:
            self._show_reference_density()
        else:
            self._hide_reference_density()

        self.radioButtonNm.clicked.connect(self._show_reference_density)
        self.radioButtonAtPerCm2.clicked.connect(self._hide_reference_density)

        self.systematic_error = DepthProfileDialog.systerr
        self.show_scale_line = DepthProfileDialog.line_scale
        self.show_zero_line = DepthProfileDialog.line_zero

        self.cross_sections = global_settings.get_cross_sections()

        self._show_measurement_settings()
        self._show_efficiency_files()
        self.exec_()
Пример #3
0
    def test_reading_bad_values(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            self.gs.set_config_dir(tmp_dir)
            self.gs.set_request_directory(Path(tmp_dir, "requests"))
            self.gs.set_request_directory_last_open(Path(tmp_dir, "requests"))
            self.gs.save_config()

            ini_file = self.gs.get_config_file()
            with ini_file.open("r") as f:
                lines = f.readlines()
            self.assertTrue(1 < len(lines))
            with ini_file.open("w") as f:
                for line in lines:
                    if line.strip().startswith("compression_y"):
                        line = "compression_y = True\n"
                    elif line.strip().startswith("transpose"):
                        line = "transpose =\n"
                    f.write(line)
                f.write("foo = bar\n")
                f.write("bar\n")

            gs = GlobalSettings(config_dir=tmp_dir, save_on_creation=False)
            self.assert_settings_equal(self.gs, gs)
Пример #4
0
    def test_initialization(self):
        """Upon initialization, global settings creates a directory containing
        an ini file and request directory if save on creation is True.
        """
        with tempfile.TemporaryDirectory() as tmp_dir:
            path = Path(tmp_dir, "settings")
            file = path / "potku2.ini"
            global_settings = GlobalSettings(config_dir=path,
                                             save_on_creation=False)

            self.assertFalse(path.exists())
            self.assertFalse(file.exists())
            self.assertFalse(global_settings.get_request_directory().exists())

            global_settings = GlobalSettings(config_dir=path,
                                             save_on_creation=True)

            self.assertTrue(path.exists())
            self.assertTrue(file.exists())
            # Request directory is not created
            self.assertFalse(global_settings.get_request_directory().exists())
Пример #5
0
    def test_element_simulation_settings(self):
        """This tests that ElementSimulation is run with the correct settings
        depending on how 'use_default_settings' and 'use_request_settings'
        have been set.
        """
        with tempfile.TemporaryDirectory() as tmp_dir:
            # File paths
            tmp_dir = Path(tmp_dir).resolve()
            req_dir = tmp_dir / "req"
            sim_dir = req_dir / "Sample_01-foo" / \
                f"{Simulation.DIRECTORY_PREFIX}01-bar"
            simu_file = sim_dir / "bar.simulation"

            # Request
            request = Request(
                req_dir, "test_req", GlobalSettings(config_dir=tmp_dir), {},
                enable_logging=False)

            self.assertEqual(req_dir, request.directory)
            self.assertEqual("test_req", request.request_name)

            # Sample
            sample = request.samples.add_sample(name="foo")
            self.assertIs(sample, request.samples.samples[0])
            self.assertIsInstance(sample, Sample)
            self.assertEqual("foo", sample.name)
            self.assertEqual(request, sample.request)
            self.assertEqual("Sample_01-foo", sample.directory)

            # Simulation
            sim = sample.simulations.add_simulation_file(
                sample, simu_file, 0)
            # Disable logging so the logging file handlers do not cause
            # an exception when the tmp dir is removed
            sim.close_log_files()

            self.assertIs(sim, sample.simulations.get_key_value(0))
            self.assertIsInstance(sim.detector, Detector)
            self.assertIsInstance(sim.run, Run)
            self.assertEqual("bar", sim.name)
            self.assertEqual(request, sim.request)
            self.assertEqual(sample, sim.sample)

            # ElementSimulation
            rec_elem = RecoilElement(
                Element.from_string("Fe"), [Point((1, 1))], name="recoil_name")
            elem_sim = sim.add_element_simulation(rec_elem)
            self.assertIs(elem_sim, sim.element_simulations[0])
            elem_sim.number_of_preions = 2
            elem_sim.number_of_ions = 3
            self.assertEqual(request, elem_sim.request)
            self.assertEqual("Fe-Default", elem_sim.get_full_name())

            # Some pre-simulation checks
            self.assertIsNot(sim.target, request.default_target)
            self.assertIsNot(elem_sim, request.default_element_simulation)
            self.assertIsNot(sim.detector, request.default_detector)
            self.assertIsNot(sim.run, request.default_run)
            self.assertIsNot(sim.run.beam, request.default_run.beam)
            self.assertNotEqual(
                elem_sim.number_of_ions,
                request.default_element_simulation.number_of_ions)

            self.assert_expected_settings(elem_sim, request, sim)
Пример #6
0
 def setUp(self) -> None:
     self.gs = GlobalSettings(tempfile.gettempdir(), save_on_creation=False)
Пример #7
0
class TestGlobalSettings(unittest.TestCase):
    def setUp(self) -> None:
        self.gs = GlobalSettings(tempfile.gettempdir(), save_on_creation=False)

    def test_initialization(self):
        """Upon initialization, global settings creates a directory containing
        an ini file and request directory if save on creation is True.
        """
        with tempfile.TemporaryDirectory() as tmp_dir:
            path = Path(tmp_dir, "settings")
            file = path / "potku2.ini"
            global_settings = GlobalSettings(config_dir=path,
                                             save_on_creation=False)

            self.assertFalse(path.exists())
            self.assertFalse(file.exists())
            self.assertFalse(global_settings.get_request_directory().exists())

            global_settings = GlobalSettings(config_dir=path,
                                             save_on_creation=True)

            self.assertTrue(path.exists())
            self.assertTrue(file.exists())
            # Request directory is not created
            self.assertFalse(global_settings.get_request_directory().exists())

    def test_boolean_getters(self):
        self.gs.set_tofe_transposed(False)
        self.assertFalse(self.gs.get_tofe_transposed())
        self.gs.set_tofe_transposed(True)
        self.assertTrue(self.gs.get_tofe_transposed())

        self.gs.set_tofe_invert_y(False)
        self.assertFalse(self.gs.get_tofe_invert_y())
        self.gs.set_tofe_invert_y(True)
        self.assertTrue(self.gs.get_tofe_invert_y())

    def test_int_getters(self):
        self.gs.set_import_coinc_count(555)
        self.assertEqual(555, self.gs.get_import_coinc_count())

        # Some keys have default values in case conversion fails
        self.gs.set_import_coinc_count("seven")
        self.assertEqual(10000, self.gs.get_import_coinc_count())

    def test_cross_section(self):
        self.assertEqual(CrossSection.ANDERSEN, self.gs.get_cross_sections())
        self.gs.set_cross_sections(CrossSection.LECUYER)
        self.assertEqual(CrossSection.LECUYER, self.gs.get_cross_sections())
        self.gs.set_cross_sections(CrossSection.RUTHERFORD)
        self.assertEqual(CrossSection.RUTHERFORD, self.gs.get_cross_sections())

    def test_ion_division(self):
        self.gs.set_ion_division(IonDivision.BOTH)
        self.assertEqual(IonDivision.BOTH, self.gs.get_ion_division())

        self.gs.set_ion_division(IonDivision.SIM)
        self.assertEqual(IonDivision.SIM, self.gs.get_ion_division())

        self.gs.set_ion_division(IonDivision.NONE)
        self.assertEqual(IonDivision.NONE, self.gs.get_ion_division())

    def test_color_scheme(self):
        self.gs.set_tofe_color(ToFEColorScheme.DEFAULT)
        self.assertEqual(ToFEColorScheme.DEFAULT, self.gs.get_tofe_color())

        self.gs.set_tofe_color(ToFEColorScheme.INV_GREYSCALE)
        self.assertEqual(ToFEColorScheme.INV_GREYSCALE,
                         self.gs.get_tofe_color())

        self.gs.set_tofe_color(ToFEColorScheme.GREYSCALE)
        self.assertEqual(ToFEColorScheme.GREYSCALE, self.gs.get_tofe_color())

    def test_element_colors(self):
        self.gs.set_element_color("B", "black")
        # This is case insensitive
        self.assertEqual("black", self.gs.get_element_color("B"))
        self.assertEqual("black", self.gs.get_element_color("b"))

        # Unknown color returns a default value
        self.assertEqual("red", self.gs.get_element_color("foo"))

        # New elements can be added
        self.gs.set_element_color("foo", "green")
        self.assertEqual("green", self.gs.get_element_color("foo"))

    def test_minimum_concentration(self):
        self.assertEqual(0.0001, self.gs.get_minimum_concentration())
        self.gs.set_minimum_concentration(1)
        self.assertEqual(1, self.gs.get_minimum_concentration())
        self.gs.set_minimum_concentration(0)
        # The absolute minimum
        self.assertEqual(0.000001, self.gs.get_minimum_concentration())

    def test_serialiazation(self):
        """Deserialized GlobalSettings object should have the same
        values as the serialized object.
        """
        with tempfile.TemporaryDirectory() as tmp_dir:
            path = Path(tmp_dir, "settings")
            gs1 = GlobalSettings(config_dir=path, save_on_creation=False)
            gs1.set_cross_sections(CrossSection.LECUYER)
            gs1.set_element_color("He", "blue")
            gs1.set_tofe_transposed(False)
            gs1.set_request_directory(Path(tmp_dir, "requests2"))
            gs1.set_tofe_bin_range_x(444, 555)
            gs1.set_num_iterations(13)
            gs1.save_config()

            gs2 = GlobalSettings(config_dir=path, save_on_creation=False)
            self.assert_settings_equal(gs1, gs2)

    def test_reading_empty_or_half_file(self):
        """If the ini file is empty or keys are missing, GlobalSettings
        reverts to default values."""
        with tempfile.TemporaryDirectory() as tmp_dir:
            ini_file = Path(tmp_dir, "potku2.ini")
            open(ini_file, "a").close()
            gs = GlobalSettings(tmp_dir, save_on_creation=False)
            # Update directories
            self.gs.set_config_dir(tmp_dir)
            self.gs.set_request_directory(Path(tmp_dir, "requests"))
            self.gs.set_request_directory_last_open(Path(tmp_dir, "requests"))
            self.assert_settings_equal(self.gs, gs)

            # Save the file
            self.gs.save_config()
            # Remove every second line from the ini file
            with open(ini_file, "r") as f:
                lines = f.readlines()
            self.assertTrue(1 < len(lines))
            with open(ini_file, "w") as f:
                for line in lines[::2]:
                    f.write(line)

            gs = GlobalSettings(tmp_dir, save_on_creation=False)
            self.assert_settings_equal(self.gs, gs, only_check_same_size=True)

    def test_reading_bad_values(self):
        with tempfile.TemporaryDirectory() as tmp_dir:
            self.gs.set_config_dir(tmp_dir)
            self.gs.set_request_directory(Path(tmp_dir, "requests"))
            self.gs.set_request_directory_last_open(Path(tmp_dir, "requests"))
            self.gs.save_config()

            ini_file = self.gs.get_config_file()
            with ini_file.open("r") as f:
                lines = f.readlines()
            self.assertTrue(1 < len(lines))
            with ini_file.open("w") as f:
                for line in lines:
                    if line.strip().startswith("compression_y"):
                        line = "compression_y = True\n"
                    elif line.strip().startswith("transpose"):
                        line = "transpose =\n"
                    f.write(line)
                f.write("foo = bar\n")
                f.write("bar\n")

            gs = GlobalSettings(config_dir=tmp_dir, save_on_creation=False)
            self.assert_settings_equal(self.gs, gs)

    def assert_settings_equal(self,
                              gs1: GlobalSettings,
                              gs2: GlobalSettings,
                              only_check_same_size=False):
        """Asserts that the two GlobalSettings objects return same values.
        If only_check_same_size is True, the return values of
        get_element_colors are only checked if they are the same size.
        """
        getters = [
            method for method in dir(gs1)
            if method.startswith("get") or method.startswith("is")
        ]

        for getter in getters:
            if getter == "get_element_color":
                args = mo.get_element(randomize=True).symbol,
            elif getter == "get_import_timing":
                args = random.randint(0, 2),
            else:
                args = ()

            val1 = getattr(gs1, getter)(*args)
            val2 = getattr(gs2, getter)(*args)

            if only_check_same_size:
                if getter == "get_element_colors":
                    if len(val1) != len(val2):
                        continue

            self.assertEqual(val1, val2)
Пример #8
0
    def test_serialiazation(self):
        """Deserialized GlobalSettings object should have the same
        values as the serialized object.
        """
        with tempfile.TemporaryDirectory() as tmp_dir:
            path = Path(tmp_dir, "settings")
            gs1 = GlobalSettings(config_dir=path, save_on_creation=False)
            gs1.set_cross_sections(CrossSection.LECUYER)
            gs1.set_element_color("He", "blue")
            gs1.set_tofe_transposed(False)
            gs1.set_request_directory(Path(tmp_dir, "requests2"))
            gs1.set_tofe_bin_range_x(444, 555)
            gs1.set_num_iterations(13)
            gs1.save_config()

            gs2 = GlobalSettings(config_dir=path, save_on_creation=False)
            self.assert_settings_equal(gs1, gs2)
Пример #9
0
def get_global_settings() -> GlobalSettings:
    """Returns a GlobalSettings object.
    """
    return GlobalSettings(config_dir=_TEMP_DIR, save_on_creation=False)