From 7dcf029299afaa837d8f4a296884c39426bd040e Mon Sep 17 00:00:00 2001 From: glass-ships Date: Mon, 27 Jan 2025 11:47:23 -0500 Subject: [PATCH 1/6] Switch to using ruff, re: python project template --- .pre-commit-config.yaml | 30 +++++++++------ RefRed/reduction/live_reduction_handler.py | 36 ++++++++--------- environment.yml | 3 +- pyproject.toml | 45 +++++++++++----------- 4 files changed, 59 insertions(+), 55 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b55e602f..4769afae 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,15 +16,23 @@ repos: # args: ['--maxkb=4096'] - id: check-yaml - - repo: https://github.com/psf/black - rev: 24.10.0 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.9.3 hooks: - - id: black - exclude: test/data - - - repo: https://github.com/PyCQA/flake8 - rev: 7.1.1 - hooks: - - id: flake8 - exclude: dev-docs|docs|versioneer.py|RefRed/_version.py|create_graph.py|test/data - args: ['--extend-ignore=E999,F821,E402,E127'] + - id: ruff + args: [--fix, --exit-non-zero-on-fix] + exclude: | + dev-docs + docs + versioneer.py + RefRed/_version.py + create_graph.py + test/data + - id: ruff-format + exclude: | + dev-docs + docs + versioneer.py + RefRed/_version.py + create_graph.py + test/data diff --git a/RefRed/reduction/live_reduction_handler.py b/RefRed/reduction/live_reduction_handler.py index a6eab912..c7ccbf42 100644 --- a/RefRed/reduction/live_reduction_handler.py +++ b/RefRed/reduction/live_reduction_handler.py @@ -5,12 +5,11 @@ import sys import time -# third-party imports -from lr_reduction import template -from lr_reduction import reduction_template_reader import numpy as np -from qtpy.QtWidgets import QFileDialog -from qtpy.QtWidgets import QApplication + +# third-party imports +from lr_reduction import reduction_template_reader, template +from qtpy.QtWidgets import QApplication, QFileDialog # RefRed imports from RefRed.gui_handling.progressbar_handler import ProgressBarHandler @@ -24,7 +23,6 @@ class LiveReductionHandler(object): - big_table_data = None list_reduced_workspace = [] nbr_reduction_process = -1 @@ -60,14 +58,14 @@ def run(self): if _data_0_0 is None: return - StatusMessageHandler(parent=self.parent, message='Running reduction ...', is_threaded=False) + StatusMessageHandler(parent=self.parent, message="Running reduction ...", is_threaded=False) self.parent.ui.reduceButton.setEnabled(False) self.cleanup() o_reduction_progressbar_handler = ProgressBarHandler(parent=self.parent) - o_reduction_progressbar_handler.setup(nbr_reduction=self.nbr_reduction_process, label='Reduction Process ') + o_reduction_progressbar_handler.setup(nbr_reduction=self.nbr_reduction_process, label="Reduction Process ") common_pars = GlobalReductionSettingsHandler(parent=self.parent).to_dict() @@ -81,17 +79,18 @@ def run(self): template_data = reduction_template_reader.ReductionParameters() template_data.from_dict(reduction_pars, permissible=True) q, r, dr, info = template.process_from_template( - reduction_pars['data_files'], + reduction_pars["data_files"], template_data, - q_summing=reduction_pars['const_q'], # const Q binning + q_summing=reduction_pars["const_q"], # const Q binning info=True, - normalize=reduction_pars['apply_normalization'], + normalize=reduction_pars["apply_normalization"], ) self.save_reduction(row_index, refl=[q, r, dr], info=info) - except: + # TODO: catch specific exceptions + except: # noqa: E722 logging.error(sys.exc_info()[1]) self.parent.ui.reduceButton.setEnabled(True) - StatusMessageHandler(parent=self.parent, message='Failed!', is_threaded=True) + StatusMessageHandler(parent=self.parent, message="Failed!", is_threaded=True) return # scale @@ -114,7 +113,7 @@ def run(self): # save size of view for home button self.save_stitching_plot_view() - StatusMessageHandler(parent=self.parent, message='Done!', is_threaded=True) + StatusMessageHandler(parent=self.parent, message="Done!", is_threaded=True) def export(self): """ @@ -147,7 +146,7 @@ def export(self): script += "template_data.from_dict(reduction_pars)\n" script += "q, r, dr, info = template.process_from_template(reduction_pars['data_files'], template_data, q_summing=reduction_pars['const_q'], info=True, normalize=reduction_pars['apply_normalization'])\n\n" # noqa: E501 - with open(filename, 'w') as fd: + with open(filename, "w") as fd: fd.write(script) def save_stitching_plot_view(self): @@ -160,7 +159,6 @@ def save_stitching_plot_view(self): self.parent.big_table_data = big_table_data def save_reduction(self, row=-1, refl=None, info=None): - big_table_data = self.big_table_data _config = big_table_data[row, 2] if _config is None: @@ -174,15 +172,15 @@ def save_reduction(self, row=-1, refl=None, info=None): _config.y_axis_for_display = refl[1] _config.e_axis_for_display = refl[2] _config.sf_auto_found_match = True - if info['scaling_factors']['a'] == 1 and info['scaling_factors']['err_a'] == 0: + if info["scaling_factors"]["a"] == 1 and info["scaling_factors"]["err_a"] == 0: _config.sf_auto_found_match = False big_table_data[row, 2] = _config self.big_table_data = big_table_data def print_message(self, title, value): - print('> %s ' % title) - print('-> value: ', value, '-> type: ', type(value)) + print("> %s " % title) + print("-> value: ", value, "-> type: ", type(value)) def calculate_nbr_reduction_process(self): _big_table_data = self.big_table_data diff --git a/environment.yml b/environment.yml index c059d229..197ca8cc 100644 --- a/environment.yml +++ b/environment.yml @@ -19,8 +19,7 @@ dependencies: - sphinx - sphinx_rtd_theme # development - - black - - flake8 + - ruff - mypy - pre-commit - pytest diff --git a/pyproject.toml b/pyproject.toml index 042467d6..9e889120 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,26 +1,25 @@ -[tool.black] -line-length = 119 -target-version = ['py36', 'py37', 'py38'] -skip-string-normalization = true -extend-exclude = ''' -^/( - ( - \.eggs # exclude a few common directories in the - | \.git # root of the project - | \.hg - | \.mypy_cache - | \.tox - | \.venv - | _build - | buck-out - | build - | dist - | versioneer.py - | test/data/*.py - )/ -) -''' +[tool.ruff] +line-length = 120 +extend-exclude = [ + ".eggs", + ".git", + ".hg", + ".mypy_cache", + ".tox", + ".venv", + "_build", + "buck-out", + "build", + "dist", + "versioneer.py", + "test/data/*.py", +] + +[tool.ruff.lint] +select = ["A", "ARG", "ASYNC", "BLE", "C90", "E", "F", "I", "N", "UP032", "W"] +ignore = ["F821", "E402"] + [tool.mypy] ignore_missing_imports = true allow_untyped_globals = true -ignore = ["test/data",] +# ignore = ["test/data"] From 839ebac636fce8a5e5f4b6166980589cd88ad557 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 27 Jan 2025 16:48:05 +0000 Subject: [PATCH 2/6] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- RefRed/__init__.py | 8 +- RefRed/_version.py | 6 +- RefRed/about_dialog.py | 19 +- .../auto_fill_widgets_handler.py | 9 +- .../extract_lconfigdataset_runs.py | 12 +- ...pulate_reduction_table_from_list_lrdata.py | 2 - .../reductiontable_auto_fill.py | 46 ++-- RefRed/browsing_runs.py | 3 +- RefRed/calculations/add_list_nexus.py | 11 +- .../check_if_same_nxs_property.py | 3 +- ...heck_list_run_compatibility_and_display.py | 8 +- .../check_list_run_compatibility_thread.py | 20 +- RefRed/calculations/compare_two_lrdata.py | 7 +- RefRed/calculations/load_list_nexus.py | 5 +- RefRed/calculations/locate_list_run.py | 1 - RefRed/calculations/lr_data.py | 68 +++--- RefRed/calculations/run_sequence_breaker.py | 10 +- RefRed/calculations/sort_lrdata_list.py | 9 +- .../update_reduction_table_metadata.py | 1 - RefRed/colors.py | 14 +- RefRed/config/__init__.py | 117 +++++------ RefRed/config/baseconfig.py | 133 ++++++------ RefRed/config/export.py | 6 +- RefRed/config/gui.py | 18 +- RefRed/config/instrument.py | 23 +- RefRed/config/metadataSelected.py | 8 +- RefRed/config/misc.py | 22 +- RefRed/config/output_templates.py | 38 ++-- RefRed/config/plotting.py | 12 +- RefRed/config/ref_l.py | 20 +- RefRed/config/refllastloadedfiles.py | 48 ++--- RefRed/configuration/export_xml_config.py | 134 ++++++------ ...oad_reduction_table_from_lconfigdataset.py | 26 +-- RefRed/configuration/loading_configuration.py | 3 +- ...ate_reduction_table_from_lconfigdataset.py | 1 - RefRed/configuration/saving_configuration.py | 19 +- RefRed/configuration/user_configuration.py | 1 - .../user_configuration_handler.py | 22 +- RefRed/decorators.py | 38 ++-- RefRed/export/ascii_loader.py | 1 - RefRed/export/export_plot_ascii.py | 15 +- RefRed/export/reduced_ascii_loader.py | 3 +- RefRed/file_loading_utility.py | 4 +- .../auto_tof_range_radio_button_handler.py | 3 +- RefRed/gui_handling/data_norm_spinboxes.py | 42 ++-- RefRed/gui_handling/fill_stitching_table.py | 7 +- .../first_angle_range_gui_handler.py | 9 +- RefRed/gui_handling/gui_utility.py | 28 ++- RefRed/gui_handling/progressbar_handler.py | 6 +- .../gui_handling/refred_interface_handler.py | 7 +- .../scaling_factor_widgets_handler.py | 2 +- .../gui_handling/update_plot_widget_status.py | 10 +- RefRed/initialization/gui.py | 12 +- RefRed/interfaces/deadtime_entry.py | 8 +- RefRed/interfaces/deadtime_settings.py | 11 +- RefRed/interfaces/mplwidgets.py | 14 +- RefRed/interfaces/mytablewidget.py | 1 - RefRed/lconfigdataset.py | 16 +- .../load_reduced_data_set_handler.py | 5 +- .../reduced_ascii_data_right_click.py | 3 +- .../reduced_ascii_table_handler.py | 1 - .../stitching_ascii_widget.py | 16 +- .../low_res_finder.py | 6 +- RefRed/main.py | 196 +++++++++--------- RefRed/metadata/metadata_finder.py | 32 +-- RefRed/nexus_utilities.py | 11 +- .../peak_finder_derivation.py | 6 +- RefRed/plot/all_plot_axis.py | 1 - RefRed/plot/background_settings.py | 9 +- RefRed/plot/clear_plots.py | 31 ++- RefRed/plot/display_plots.py | 7 +- RefRed/plot/home_plot_button_clicked.py | 13 +- RefRed/plot/launch_stitching_manual_axis.py | 21 +- RefRed/plot/log_plot_toggle.py | 17 +- RefRed/plot/mouse_leave_plot.py | 39 ++-- RefRed/plot/popup_plot_1d.py | 11 +- RefRed/plot/popup_plot_2d.py | 8 +- RefRed/plot/single_click_plot.py | 25 +-- RefRed/preview_config/preview_config.py | 9 +- .../reduction/calculate_sf_overlap_range.py | 43 ++-- .../global_reduction_settings_handler.py | 2 +- .../individual_reduction_settings_handler.py | 13 +- RefRed/reduction/live_calculate_sf.py | 28 ++- RefRed/reduction/live_reduced_data_handler.py | 21 +- RefRed/reduction/normalization_stitching.py | 32 +-- RefRed/reduction/reduced_data_handler.py | 17 +- .../check_list_run_compatibility.py | 5 +- .../reduction_table_check_box.py | 1 - .../reduction_table_handler.py | 1 - .../update_reduction_table.py | 11 +- RefRed/settings/initialize_settings.py | 5 +- RefRed/settings/list_settings.py | 1 - RefRed/settings/settings_editor.py | 8 +- RefRed/settings/settings_password_editor.py | 4 +- .../check_sf_run_reduction_button_status.py | 5 +- .../compare_two_nxsdata_for_sfcalculator.py | 16 +- RefRed/sf_calculator/fill_sf_gui_table.py | 18 +- .../incident_medium_list_editor.py | 5 +- ...load_and_sort_nxsdata_for_sf_calculator.py | 28 +-- RefRed/sf_calculator/lr_data.py | 63 +++--- .../sf_calculator/reduction_sf_calculator.py | 32 +-- RefRed/sf_calculator/sf_calculator.py | 32 +-- RefRed/sf_calculator/sort_nxsdata.py | 2 +- RefRed/sf_preview/sf_file_handler.py | 2 +- RefRed/sf_preview/sf_preview.py | 8 +- RefRed/status_message_handler.py | 12 +- RefRed/thread/locate_run.py | 5 +- RefRed/utilities.py | 16 +- create_graph.py | 77 +++---- docs/conf.py | 70 +++---- scripts/start_refred.py | 17 +- scripts/sync_dependencies.py | 4 +- setup.py | 66 +++--- test/conftest.py | 10 +- test/test_fixtures.py | 10 +- test/test_template.py | 12 +- test/ui/test_basic_startup.py | 8 +- test/ui/test_compute_scaling_factors.py | 20 +- test/ui/test_plot2d_dialog.py | 2 +- test/ui/test_popup_plot_1d.py | 5 +- test/ui/test_reduce_and_export_data.py | 19 +- test/ui/test_scaling_factors_preview.py | 9 +- .../RefRed/calculations/test_load_nexus.py | 4 +- .../calculations/test_run_sequence_breaker.py | 5 +- .../configuration/test_export_xml_config.py | 4 +- .../test_loading_configuration.py | 99 ++++----- test/unit/RefRed/export/test_ascii_loader.py | 10 +- .../RefRed/export/test_export_plot_ascii.py | 14 +- .../export/test_reduced_ascii_loader.py | 12 +- .../RefRed/interfaces/test_deadtime_entry.py | 2 +- .../interfaces/test_deadtime_settings.py | 24 +-- .../RefRed/interfaces/test_mytablewidget.py | 9 +- .../test_low_res_finder.py | 39 ++-- .../test_peak_finder_derivation.py | 72 +++---- ...t_individual_reduction_settings_handler.py | 5 +- .../test_const_q_checkbox_handler.py | 6 +- .../test_reduction_table_handling.py | 4 +- .../test_update_reduction_table.py | 9 +- .../RefRed/settings/test_edit_settings.py | 29 +-- .../settings/test_initialize_settings.py | 32 +-- .../test_reduction_sf_calculator.py | 38 ++-- .../sf_calculator/test_sf_calculator.py | 16 +- test/unit/RefRed/test_file_loading_utility.py | 14 +- test/unit/RefRed/test_main.py | 38 ++-- test/unit/RefRed/test_tabledata.py | 8 +- test/unit/RefRed/test_utilities.py | 17 +- 146 files changed, 1425 insertions(+), 1467 deletions(-) diff --git a/RefRed/__init__.py b/RefRed/__init__.py index 4e6bb897..784b5833 100644 --- a/RefRed/__init__.py +++ b/RefRed/__init__.py @@ -1,9 +1,9 @@ from ._version import get_versions # set by versioneer -__version__ = get_versions()['version'] +__version__ = get_versions()["version"] del get_versions -ORGANIZATION = 'neutrons' -APPNAME = 'RefRed' -WINDOW_TITLE = 'Liquids Reflectometer Reduction - ' +ORGANIZATION = "neutrons" +APPNAME = "RefRed" +WINDOW_TITLE = "Liquids Reflectometer Reduction - " diff --git a/RefRed/_version.py b/RefRed/_version.py index d6d50c98..71bd5ded 100644 --- a/RefRed/_version.py +++ b/RefRed/_version.py @@ -192,7 +192,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose): # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". - tags = set([r for r in refs if re.search(r'\d', r)]) + tags = set([r for r in refs if re.search(r"\d", r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: @@ -273,7 +273,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): if "-" in git_describe: # TAG-NUM-gHEX - mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) + mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out @@ -502,7 +502,7 @@ def get_versions(): # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. - for i in cfg.versionfile_source.split('/'): + for i in cfg.versionfile_source.split("/"): root = os.path.dirname(root) except NameError: return { diff --git a/RefRed/about_dialog.py b/RefRed/about_dialog.py index 81beeb5f..7831da18 100644 --- a/RefRed/about_dialog.py +++ b/RefRed/about_dialog.py @@ -1,14 +1,15 @@ -from numpy.version import version as numpy_version_str -from matplotlib import __version__ as matplotlib_version_str -from RefRed import __version__ as RefRed_version_str -from qtpy import QtWidgets, QT_VERSION, PYQT_VERSION import sys -import mantid + import lr_reduction +import mantid +from matplotlib import __version__ as matplotlib_version_str +from numpy.version import version as numpy_version_str +from qtpy import PYQT_VERSION, QT_VERSION, QtWidgets +from RefRed import __version__ as RefRed_version_str -class AboutDialog(object): +class AboutDialog(object): parent = None def __init__(self, parent=None): @@ -22,7 +23,7 @@ def display(self): qt_version = QT_VERSION pyqt_version = PYQT_VERSION - message = '''RefRed - Liquids Reflectrometry Reduction program + message = """RefRed - Liquids Reflectrometry Reduction program RefRed version %s Reduction version %s @@ -33,7 +34,7 @@ def display(self): - Mantid: %s - Matplotlib: %s - Qt: %s - - PyQt: %s''' % ( + - PyQt: %s""" % ( RefRed_version_str, lr_reduction.__version__, python_version, @@ -44,7 +45,7 @@ def display(self): pyqt_version, ) - QtWidgets.QMessageBox.about(self.parent, 'About RefRed', message) + QtWidgets.QMessageBox.about(self.parent, "About RefRed", message) def get_python_version(self): str_version = sys.version_info diff --git a/RefRed/autopopulatemaintable/auto_fill_widgets_handler.py b/RefRed/autopopulatemaintable/auto_fill_widgets_handler.py index ac1a5763..bb2e4b2f 100644 --- a/RefRed/autopopulatemaintable/auto_fill_widgets_handler.py +++ b/RefRed/autopopulatemaintable/auto_fill_widgets_handler.py @@ -1,7 +1,8 @@ -from qtpy.QtWidgets import QApplication -from qtpy import QtCore, QtGui import time +from qtpy import QtCore, QtGui +from qtpy.QtWidgets import QApplication + class AutoFillWidgetsHandler(object): def __init__(self, parent=None): @@ -14,7 +15,7 @@ def setup(self): self.parent.ui.progressBar_check5.setValue(0) self.parent.ui.progressBar_check2.setVisible(False) self.parent.ui.progressBar_check5.setVisible(False) - pixmap = QtGui.QPixmap(':/General/check_icon.png') + pixmap = QtGui.QPixmap(":/General/check_icon.png") self.parent.ui.check1.setPixmap(pixmap) self.parent.ui.check2.setPixmap(pixmap) self.parent.ui.check3.setPixmap(pixmap) @@ -48,7 +49,7 @@ def step1(self): QApplication.processEvents() def error_step1(self): - pixmap = QtGui.QPixmap(':/General/clear_icon.png') + pixmap = QtGui.QPixmap(":/General/clear_icon.png") self.parent.ui.check1.setFixedWidth(25) self.parent.ui.check1.setFixedHeight(25) self.parent.ui.check1.setPixmap(pixmap) diff --git a/RefRed/autopopulatemaintable/extract_lconfigdataset_runs.py b/RefRed/autopopulatemaintable/extract_lconfigdataset_runs.py index 647f6704..dc0f4405 100644 --- a/RefRed/autopopulatemaintable/extract_lconfigdataset_runs.py +++ b/RefRed/autopopulatemaintable/extract_lconfigdataset_runs.py @@ -1,11 +1,11 @@ class ExtractLConfigDataSetRuns(object): - '''This class get an array of LConfigDataSet and extract the data sets + """This class get an array of LConfigDataSet and extract the data sets and append them in a list that is returned #TODO: this doesn't need to be a class - ''' + """ - def __init__(self, lconfigdataset=None, data_type='data'): + def __init__(self, lconfigdataset=None, data_type="data"): self.lconfigdataset = lconfigdataset self.data_type = data_type @@ -14,14 +14,14 @@ def list_runs(self): for _lconfig in self.lconfigdataset: if _lconfig is not None: - if self.data_type == 'data': + if self.data_type == "data": _list_run = _lconfig.data_sets else: _list_run = _lconfig.norm_sets - if _list_run is not ['']: + if _list_run != [""]: for _run in _list_run: - if _run != '': + if _run != "": int_run = int(_run) full_list_runs.append(int_run) diff --git a/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py b/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py index e0422f14..e022abd2 100644 --- a/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py +++ b/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py @@ -10,7 +10,6 @@ class PopulateReductionTableFromListLRData(object): - list_lrdata_sorted = None list_wks_sorted = None list_runs_sorted = None @@ -20,7 +19,6 @@ class PopulateReductionTableFromListLRData(object): THI_TOLERANCE = 0.015 def __init__(self, parent=None, list_lrdata=None, list_wks=None, list_run=None, list_nexus=None, is_data=True): - self.parent = parent self.list_run = list_run self.list_lrdata = list_lrdata diff --git a/RefRed/autopopulatemaintable/reductiontable_auto_fill.py b/RefRed/autopopulatemaintable/reductiontable_auto_fill.py index 134dcfbc..167c93d7 100644 --- a/RefRed/autopopulatemaintable/reductiontable_auto_fill.py +++ b/RefRed/autopopulatemaintable/reductiontable_auto_fill.py @@ -1,25 +1,25 @@ # import sys import time -import numpy as np from itertools import chain + +import numpy as np from qtpy.QtWidgets import QApplication -from RefRed.calculations.run_sequence_breaker import RunSequenceBreaker +from RefRed.autopopulatemaintable.auto_fill_widgets_handler import AutoFillWidgetsHandler from RefRed.autopopulatemaintable.extract_lconfigdataset_runs import ExtractLConfigDataSetRuns -from RefRed.thread.locate_run import LocateRunThread -from RefRed.calculations.load_list_nexus import LoadListNexus -from RefRed.calculations.sort_lrdata_list import SortLRDataList -from RefRed.calculations.lr_data import LRData from RefRed.autopopulatemaintable.populate_reduction_table_from_list_lrdata import PopulateReductionTableFromListLRData from RefRed.calculations.check_list_run_compatibility_and_display import CheckListRunCompatibilityAndDisplay +from RefRed.calculations.load_list_nexus import LoadListNexus +from RefRed.calculations.lr_data import LRData +from RefRed.calculations.run_sequence_breaker import RunSequenceBreaker +from RefRed.calculations.sort_lrdata_list import SortLRDataList from RefRed.mantid_utility import MantidUtility -from RefRed.utilities import format_to_list -from RefRed.autopopulatemaintable.auto_fill_widgets_handler import AutoFillWidgetsHandler from RefRed.nexus_utilities import get_run_number +from RefRed.thread.locate_run import LocateRunThread +from RefRed.utilities import format_to_list class ReductionTableAutoFill(object): - list_full_file_name = [] list_nxs = [] list_lrdata = [] @@ -29,14 +29,13 @@ class ReductionTableAutoFill(object): list_wks_sorted = [] list_nexus_sorted = [] - data_type_selected = 'data' + data_type_selected = "data" o_auto_fill_widgets_handler = None - def __init__(self, parent=None, list_of_run_from_input='', data_type_selected='data', reset_table=False): - + def __init__(self, parent=None, list_of_run_from_input="", data_type_selected="data", reset_table=False): self.parent = parent - if data_type_selected == 'data': + if data_type_selected == "data": # add to norm box, previous loaded norm _str_old_runs = self.retrieve_list_norm_previously_loaded() if not _str_old_runs == "": @@ -48,16 +47,16 @@ def __init__(self, parent=None, list_of_run_from_input='', data_type_selected='d self.parent.ui.norm_sequence_lineEdit.setText(new_str) self.browsing_files_flag = False - if not (self.parent.browsed_files[data_type_selected] is None): + if self.parent.browsed_files[data_type_selected] is not None: self.browsing_files_flag = True - if list_of_run_from_input == '': + if list_of_run_from_input == "": self.sorted_list_of_runs = [] if not self.browsing_files_flag: return - if data_type_selected != 'data': - data_type_selected = 'norm' + if data_type_selected != "data": + data_type_selected = "norm" self.data_type_selected = data_type_selected self.init_variable() @@ -85,13 +84,12 @@ def __init__(self, parent=None, list_of_run_from_input='', data_type_selected='d self.run() def merge_list_of_runs(self, new_runs=None): - # manual entry of the runs self.raw_run_from_input = new_runs self.calculate_discrete_list_of_runs() # step1 -> list_of_runs_from_input self.big_table_data = None - if (not self.reset_table) and (self.data_type_selected == 'data'): + if (not self.reset_table) and (self.data_type_selected == "data"): self.retrieve_bigtable_list_data_loaded() # step2 -> list_of_runs_from_lconfig _full_list_of_runs = [] @@ -151,7 +149,7 @@ def loading_full_reductionTable(self): _list_nexus_sorted = self.list_nexus_sorted _list_runs_sorted = self.list_runs_sorted # _data_type_selected = self.data_type_selected - _is_working_with_data_column = True if self.data_type_selected == 'data' else False + _is_working_with_data_column = True if self.data_type_selected == "data" else False self.parent.ui.progressBar_check5.setMinimum(0) self.parent.ui.progressBar_check5.setValue(0) @@ -275,7 +273,7 @@ def updating_reductionTable(self): list_runs_sorted = self.list_runs_sorted list_wks_sorted = self.list_wks_sorted list_nexus_sorted = self.list_nexus_sorted - is_data = True if self.data_type_selected == 'data' else False + is_data = True if self.data_type_selected == "data" else False o_pop_reduction_table = PopulateReductionTableFromListLRData( parent=self.parent, list_lrdata=list_lrdata_sorted, @@ -297,7 +295,7 @@ def init_filename_thread_array(self, sz): _list_full_file_name = [] for i in range(sz): _filename_thread_array.append(LocateRunThread()) - _list_full_file_name.append('') + _list_full_file_name.append("") self.filename_thread_array = _filename_thread_array self.list_nxs = _list_full_file_name @@ -320,7 +318,7 @@ def retrieve_list_norm_previously_loaded(self): if parent is None: return _big_table_data = parent.big_table_data - _extract_runs = ExtractLConfigDataSetRuns(_big_table_data[:, 2], data_type='norm') + _extract_runs = ExtractLConfigDataSetRuns(_big_table_data[:, 2], data_type="norm") _runs = _extract_runs.list_runs() _str_runs = ",".join([str(run) for run in _runs]) return _str_runs @@ -332,7 +330,7 @@ def remove_duplicate_runs(self): def check_minimum_requirements(self): _data_type_selected = self.data_type_selected - if _data_type_selected == 'data': + if _data_type_selected == "data": return True big_table_data = self.parent.big_table_data diff --git a/RefRed/browsing_runs.py b/RefRed/browsing_runs.py index a47e0c80..3aea1361 100644 --- a/RefRed/browsing_runs.py +++ b/RefRed/browsing_runs.py @@ -1,10 +1,11 @@ import os + from qtpy import QtWidgets + from RefRed import nexus_utilities class BrowsingRuns(object): - list_files = None list_runs = None diff --git a/RefRed/calculations/add_list_nexus.py b/RefRed/calculations/add_list_nexus.py index 30f268cb..39986b65 100644 --- a/RefRed/calculations/add_list_nexus.py +++ b/RefRed/calculations/add_list_nexus.py @@ -1,17 +1,17 @@ from mantid.simpleapi import Plus + +from RefRed.calculations.check_if_same_nxs_property import CheckIfSameNxsProperty from RefRed.calculations.load_list_nexus import LoadListNexus from RefRed.calculations.load_nexus import LoadNexus -from RefRed.calculations.check_if_same_nxs_property import CheckIfSameNxsProperty class AddListNexus(object): - wks = None addition_worked = True - prefix = 'data' + prefix = "data" def __init__( - self, list_nexus=None, list_run=None, metadata_only=False, check_nexus_compatibility=True, prefix='data' + self, list_nexus=None, list_run=None, metadata_only=False, check_nexus_compatibility=True, prefix="data" ): if list_nexus is None: return @@ -36,11 +36,10 @@ def __init__( if len(_list_wks) > 1: is_same_property = False if check_nexus_compatibility: - check_same_property = CheckIfSameNxsProperty(list_wks=_list_wks, property_name='LambdaRequest') + check_same_property = CheckIfSameNxsProperty(list_wks=_list_wks, property_name="LambdaRequest") is_same_property = check_same_property.is_same_property else: # we force true - is_same_property = True if is_same_property: diff --git a/RefRed/calculations/check_if_same_nxs_property.py b/RefRed/calculations/check_if_same_nxs_property.py index b8c532f0..e1e8c65a 100644 --- a/RefRed/calculations/check_if_same_nxs_property.py +++ b/RefRed/calculations/check_if_same_nxs_property.py @@ -2,9 +2,8 @@ class CheckIfSameNxsProperty(object): - is_same_property = False - property_name = '' + property_name = "" def __init__(self, list_wks=None, property_name=property_name): if list_wks is None: diff --git a/RefRed/calculations/check_list_run_compatibility_and_display.py b/RefRed/calculations/check_list_run_compatibility_and_display.py index 75af3873..ee123484 100644 --- a/RefRed/calculations/check_list_run_compatibility_and_display.py +++ b/RefRed/calculations/check_list_run_compatibility_and_display.py @@ -3,11 +3,12 @@ # third party imports from qtpy import QtGui +import RefRed.colors + # application imports from RefRed.calculations.add_list_nexus import AddListNexus from RefRed.calculations.lr_data import LRData from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata -import RefRed.colors from RefRed.lconfigdataset import LConfigDataset from RefRed.plot.display_plots import DisplayPlots from RefRed.reduction_table_handling.check_list_run_compatibility import CheckListRunCompatibility @@ -15,11 +16,10 @@ class CheckListRunCompatibilityAndDisplay(object): - runs_are_compatible = False wks = None lrdata = None - prefix = 'data' + prefix = "data" def __init__( self, @@ -40,7 +40,7 @@ def __init__( self.is_display_requested = is_display_requested self.runs_are_compatible = False self.lrdata = None - self.prefix = 'data' if self.is_working_with_data_column else 'norm' + self.prefix = "data" if self.is_working_with_data_column else "norm" def run(self): runs_are_compatible = True diff --git a/RefRed/calculations/check_list_run_compatibility_thread.py b/RefRed/calculations/check_list_run_compatibility_thread.py index e33891f4..df3d2d37 100644 --- a/RefRed/calculations/check_list_run_compatibility_thread.py +++ b/RefRed/calculations/check_list_run_compatibility_thread.py @@ -1,27 +1,26 @@ """ - Notes from inspecting the code: - Load data and update application store. +Notes from inspecting the code: +Load data and update application store. - The main "big_table_data" array has three entries per row, - 0: Scattering data - 1: Direct beam data - 2: Reduction options +The main "big_table_data" array has three entries per row, + 0: Scattering data + 1: Direct beam data + 2: Reduction options """ # import logging -import RefRed.colors from qtpy import QtCore, QtGui from qtpy.QtCore import Signal -from RefRed.reduction_table_handling.check_list_run_compatibility import CheckListRunCompatibility +import RefRed.colors from RefRed.calculations.add_list_nexus import AddListNexus -from RefRed.lconfigdataset import LConfigDataset from RefRed.calculations.lr_data import LRData from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata +from RefRed.lconfigdataset import LConfigDataset +from RefRed.reduction_table_handling.check_list_run_compatibility import CheckListRunCompatibility class CheckListRunCompatibilityThread(QtCore.QThread): # type: ignore - updated_data = Signal(int, bool, bool) runs_are_compatible = False @@ -37,7 +36,6 @@ def setup( is_working_with_data_column=True, is_display_requested=False, ): - self.parent = parent self.list_run = list_run self.list_nexus = list_nexus diff --git a/RefRed/calculations/compare_two_lrdata.py b/RefRed/calculations/compare_two_lrdata.py index 53bd629f..93283097 100644 --- a/RefRed/calculations/compare_two_lrdata.py +++ b/RefRed/calculations/compare_two_lrdata.py @@ -3,7 +3,6 @@ class CompareTwoLRData(object): def __init__(self, lrdata_1=None, lrdata_2=None): - self.lrdata_1 = lrdata_1 self.lrdata_2 = lrdata_2 self.result_comparison = 0 @@ -24,7 +23,7 @@ def __init__(self, lrdata_1=None, lrdata_2=None): return def compare_lambda_requested(self): - '''sorting in descending order''' + """sorting in descending order""" _lrdata_1 = self.lrdata_1 _lrdata_2 = self.lrdata_2 @@ -40,7 +39,7 @@ def compare_lambda_requested(self): return 0 def compare_thi(self): - '''sorting in descending order''' + """sorting in descending order""" _lrdata_1 = self.lrdata_1 _lrdata_2 = self.lrdata_2 @@ -56,7 +55,7 @@ def compare_thi(self): return 0 def compare_theta(self): - '''sorting in ascending order''' + """sorting in ascending order""" _lrdata_1 = self.lrdata_1 _lrdata_2 = self.lrdata_2 diff --git a/RefRed/calculations/load_list_nexus.py b/RefRed/calculations/load_list_nexus.py index e796f716..cb418ab8 100644 --- a/RefRed/calculations/load_list_nexus.py +++ b/RefRed/calculations/load_list_nexus.py @@ -2,16 +2,15 @@ class LoadListNexus(object): - list_nexus = None list_run = None - prefix = 'data' + prefix = "data" list_wks_loaded = [] list_run_loaded = [] list_nexuss_loaded = [] - def __init__(self, list_nexus=None, list_run=None, metadata_only=False, prefix='data'): + def __init__(self, list_nexus=None, list_run=None, metadata_only=False, prefix="data"): if list_nexus is None: return self.list_nexus = list_nexus diff --git a/RefRed/calculations/locate_list_run.py b/RefRed/calculations/locate_list_run.py index e968726a..2e68265d 100644 --- a/RefRed/calculations/locate_list_run.py +++ b/RefRed/calculations/locate_list_run.py @@ -4,7 +4,6 @@ class LocateListRun(object): - list_run = [] list_nexus_found = [] list_run_found = [] diff --git a/RefRed/calculations/lr_data.py b/RefRed/calculations/lr_data.py index 33d181b6..59e7f9bb 100644 --- a/RefRed/calculations/lr_data.py +++ b/RefRed/calculations/lr_data.py @@ -3,10 +3,11 @@ import math from typing import List, Optional, Type +import numpy as np + # third-party imports from mantid.api import mtd from mantid.simpleapi import Rebin -import numpy as np # package imports from RefRed.lconfigdataset import LConfigDataset @@ -19,11 +20,10 @@ PLANCK_CONSTANT = 6.626e-34 # m^2 kg s^-1 H_OVER_M_NEUTRON = PLANCK_CONSTANT / NEUTRON_MASS -NEW_GEOMETRY_DATE = '2014-10-01' +NEW_GEOMETRY_DATE = "2014-10-01" class LRData(object): - read_options = dict( is_auto_tof_finder=True, is_auto_peak_finder=True, back_offset_from_peak=3, bins=50, angle_offset=0.001 ) @@ -36,9 +36,9 @@ class LRData(object): low_res = [0, 255] low_res_flag = True use_it_flag = True - full_file_name = [''] - filename = '' - ipts = 'N/A' + full_file_name = [""] + filename = "" + ipts = "N/A" total_counts = 0 def __init__( @@ -74,33 +74,33 @@ def __init__( mt_run = workspace.getRun() - self.ipts = mt_run.getProperty('experiment_identifier').value - self.run_number = mt_run.getProperty('run_number').value - - self.lambda_requested = float(mt_run.getProperty('LambdaRequest').value[0]) - self.lambda_requested_units = mt_run.getProperty('LambdaRequest').units - self.thi = mt_run.getProperty('thi').value[0] - self.thi_units = mt_run.getProperty('thi').units - self.ths = mt_run.getProperty('ths').value[0] - self.ths_units = mt_run.getProperty('ths').units - self.tthd = mt_run.getProperty('tthd').value[0] - self.tthd_units = mt_run.getProperty('tthd').units - self.S1W = mt_run.getProperty('S1HWidth').value[0] - self.S1H = mt_run.getProperty('S1VHeight').value[0] - self.parent.current_ipts = mt_run.getProperty('experiment_identifier').value + self.ipts = mt_run.getProperty("experiment_identifier").value + self.run_number = mt_run.getProperty("run_number").value + + self.lambda_requested = float(mt_run.getProperty("LambdaRequest").value[0]) + self.lambda_requested_units = mt_run.getProperty("LambdaRequest").units + self.thi = mt_run.getProperty("thi").value[0] + self.thi_units = mt_run.getProperty("thi").units + self.ths = mt_run.getProperty("ths").value[0] + self.ths_units = mt_run.getProperty("ths").units + self.tthd = mt_run.getProperty("tthd").value[0] + self.tthd_units = mt_run.getProperty("tthd").units + self.S1W = mt_run.getProperty("S1HWidth").value[0] + self.S1H = mt_run.getProperty("S1VHeight").value[0] + self.parent.current_ipts = mt_run.getProperty("experiment_identifier").value self.total_counts = workspace.getNumberEvents() try: - self.SiW = mt_run.getProperty('SiHWidth').value[0] - self.SiH = mt_run.getProperty('SiVHeight').value[0] + self.SiW = mt_run.getProperty("SiHWidth").value[0] + self.SiH = mt_run.getProperty("SiVHeight").value[0] self.isSiThere = True except: - self.S2W = mt_run.getProperty('S2HWidth').value[0] - self.S2H = mt_run.getProperty('S2VHeight').value[0] + self.S2W = mt_run.getProperty("S2HWidth").value[0] + self.S2H = mt_run.getProperty("S2VHeight").value[0] self.isSiThere = False - self.attenuatorNbr = mt_run.getProperty('vATT').value[0] - 1 - self.date = mt_run.getProperty('run_start').value + self.attenuatorNbr = mt_run.getProperty("vATT").value[0] - 1 + self.date = mt_run.getProperty("run_start").value sample = workspace.getInstrument().getSample() source = workspace.getInstrument().getSource() @@ -121,7 +121,7 @@ def __init__( # calculate theta self.theta = self.calculate_theta() - self.frequency = float(mt_run.getProperty('Speed1').value[0]) + self.frequency = float(mt_run.getProperty("Speed1").value[0]) # Determine the range to select in TOF according to how the DAS computed the # chopper settings @@ -169,16 +169,16 @@ def __init__( tmin = 0 tmax += delta_t - self.binning = [tmin, self.read_options['bins'], tmax] + self.binning = [tmin, self.read_options["bins"], tmax] self.calculate_lambda_range() self.incident_angle = 2.0 * self.calculate_theta(with_offset=False) # 2.theta self.calculate_q_range() # self.lambda_range = self.calculate_lambda_range() # Proton charge - _proton_charge = float(mt_run.getProperty('gd_prtn_chrg').value) + _proton_charge = float(mt_run.getProperty("gd_prtn_chrg").value) # _proton_charge_units = mt_run.getProperty('gd_prtn_chrg').units - new_proton_charge_units = 'mC' + new_proton_charge_units = "mC" self.proton_charge = _proton_charge * 3.6 # to go from microA/h to mC self.proton_charge_units = new_proton_charge_units @@ -239,7 +239,7 @@ def __init__( [peak1, peak2] = pf.getPeaks() self.peak = [int(peak1), int(peak2)] - backOffsetFromPeak = self.read_options['back_offset_from_peak'] + backOffsetFromPeak = self.read_options["back_offset_from_peak"] back1 = int(peak1 - backOffsetFromPeak) back2 = int(peak2 + backOffsetFromPeak) self.back = [back1, back2] @@ -331,7 +331,7 @@ def calculate_theta(self, with_offset=True): # Add the offset angle_offset = 0.0 if with_offset and "angle_offset" in self.read_options: - angle_offset = float(self.read_options['angle_offset']) + angle_offset = float(self.read_options["angle_offset"]) angle_offset_deg = angle_offset theta = theta + angle_offset_deg * math.pi / 180.0 @@ -347,7 +347,7 @@ def _getIxyt(self, nxs_histo): self.Ixyt = nxs_histo.extractY().reshape(self.number_x_pixels, self.number_y_pixels, nbr_tof - 1) def read_data(self): - output_workspace_name = self.workspace_name + '_rebin' + output_workspace_name = self.workspace_name + "_rebin" nxs_histo = Rebin( InputWorkspace=self.workspace_name, OutputWorkspace=output_workspace_name, @@ -381,5 +381,5 @@ def is_nexus_taken_after_refDate(self): This function parses the output.date and returns true if this date is after the ref date """ nexus_date = self.date - nexus_date_acquistion = nexus_date.split('T')[0] + nexus_date_acquistion = nexus_date.split("T")[0] return nexus_date_acquistion > NEW_GEOMETRY_DATE diff --git a/RefRed/calculations/run_sequence_breaker.py b/RefRed/calculations/run_sequence_breaker.py index 73414bb9..0a8f4db1 100644 --- a/RefRed/calculations/run_sequence_breaker.py +++ b/RefRed/calculations/run_sequence_breaker.py @@ -1,10 +1,8 @@ class RunSequenceBreaker(object): - final_list = None str_final_list = None def __init__(self, run_sequence=None): - self.final_list = [] self.str_final_list = [] @@ -16,14 +14,14 @@ def __init__(self, run_sequence=None): if _run_sequence == "": self.final_list = [-1] - self.str_final_list = [''] + self.str_final_list = [""] return # coma separated - coma_separated = _run_sequence.split(',') + coma_separated = _run_sequence.split(",") for _element in coma_separated: - hypen_separated = _element.split('-') + hypen_separated = _element.split("-") nbr_element = len(hypen_separated) if nbr_element > 1: _range = self.getRangeBetweenTwoNumbers(hypen_separated[0], hypen_separated[1]) @@ -36,7 +34,7 @@ def __init__(self, run_sequence=None): self.str_final_list.append(str(hypen_separated[0])) except: self.final_list = [-2] - self.str_final_list = [''] + self.str_final_list = [""] def getRangeBetweenTwoNumbers(self, num1, num2): _num1 = int(num1) diff --git a/RefRed/calculations/sort_lrdata_list.py b/RefRed/calculations/sort_lrdata_list.py index 1f95cbbe..f8cf1f6a 100644 --- a/RefRed/calculations/sort_lrdata_list.py +++ b/RefRed/calculations/sort_lrdata_list.py @@ -21,21 +21,20 @@ class SortLRDataList(object): list_nexus = None criteria1_value = None - criteria1_type = '' + criteria1_type = "" criteria2_value = None - criteria2_type = '' + criteria2_type = "" def __init__( - self, parent=None, list_lrdata=None, list_runs=None, list_wks=None, list_nexus=None, data_type_selected='data' + self, parent=None, list_lrdata=None, list_runs=None, list_wks=None, list_nexus=None, data_type_selected="data" ): - self.list_lrdata = list_lrdata self.list_runs = list_runs self.list_wks = list_wks self.parent = parent self.list_nexus = list_nexus - self.is_data_type_selected = True if data_type_selected == 'data' else False + self.is_data_type_selected = True if data_type_selected == "data" else False def run(self): if len(self.list_lrdata) < 2: diff --git a/RefRed/calculations/update_reduction_table_metadata.py b/RefRed/calculations/update_reduction_table_metadata.py index 324679ae..99917968 100644 --- a/RefRed/calculations/update_reduction_table_metadata.py +++ b/RefRed/calculations/update_reduction_table_metadata.py @@ -11,7 +11,6 @@ def __init__(self, parent=None, lrdata=None, row=-1): self.update() def update(self): - lrdata = self.lrdata row = self.row parent = self.parent diff --git a/RefRed/colors.py b/RefRed/colors.py index 9c92520b..d038e1a2 100644 --- a/RefRed/colors.py +++ b/RefRed/colors.py @@ -1,4 +1,4 @@ -from qtpy import QtGui, QtCore +from qtpy import QtCore, QtGui COLOR_LIST = [ "#0000aa", @@ -44,13 +44,13 @@ "#e5e738", "#f07317", ] -COLOR_BACKGROUND_LIST = ['#c0d2f0', '#c0d59e'] +COLOR_BACKGROUND_LIST = ["#c0d2f0", "#c0d59e"] -TOF_SELECTION_COLOR = '#072be2' -PEAK_SELECTION_COLOR = '#00aa00' # green -BACK_SELECTION_COLOR = '#aa0000' # red -BACK2_SELECTION_COLOR = '#FF8C00' # orange -LOWRESOLUTION_SELECTION_COLOR = '#aa00aa' +TOF_SELECTION_COLOR = "#072be2" +PEAK_SELECTION_COLOR = "#00aa00" # green +BACK_SELECTION_COLOR = "#aa0000" # red +BACK2_SELECTION_COLOR = "#FF8C00" # orange +LOWRESOLUTION_SELECTION_COLOR = "#aa00aa" METADATA_CELL_COLOR = QtGui.QColor(100, 100, 150) VALUE_OK = QtCore.Qt.darkGreen # type: ignore diff --git a/RefRed/config/__init__.py b/RefRed/config/__init__.py index 451964c0..6fbccde8 100644 --- a/RefRed/config/__init__.py +++ b/RefRed/config/__init__.py @@ -1,103 +1,104 @@ # -*- encoding: utf-8 -*- -''' - Package containing configuration modules. - This folder contains all files which define constants and parameters - for quicknxs. - - The config package facilitates a special ConfigProxy interface that - acts like a dictionary, which is automatically generated from the - submodules. Constants (variables using only capital letters) are - directly taken from the module, others are first taken from the - module and than stored in a user config file defined by the - "config_file" variable in the module and read from there on the - next import. To get access to the configuration other modules - only need to import the module name, which can be either - used as dictionary or by accessing the objects attributes. - - For example the module "user1" could look like this:: - - # module docstring - config_file="user" - CONST1=12.3 - CONST2=431.2 - opt1=12 - opt2=1 - - The module that wants to use these information will be similar to:: - - from quicknxs.config import user1 - - print user1.CONS1 # directly read from module - print user1['opt1'] # first time read from module than from user.ini file - - If the module does not define the 'config_file' variable it is treated as - a normal module, if it is None the storage is just temporary and if it - is the empty string it will use the default config file. - - The proxy allows simple interpolation by using '%(name)s' inside a variable - string, which will be substituted by the name variable from the same config. - To use variables from a different config use '%(config.name)s' syntax. -''' +""" +Package containing configuration modules. +This folder contains all files which define constants and parameters +for quicknxs. + +The config package facilitates a special ConfigProxy interface that +acts like a dictionary, which is automatically generated from the +submodules. Constants (variables using only capital letters) are +directly taken from the module, others are first taken from the +module and than stored in a user config file defined by the +"config_file" variable in the module and read from there on the +next import. To get access to the configuration other modules +only need to import the module name, which can be either +used as dictionary or by accessing the objects attributes. + +For example the module "user1" could look like this:: + + # module docstring + config_file="user" + CONST1=12.3 + CONST2=431.2 + opt1=12 + opt2=1 + +The module that wants to use these information will be similar to:: + + from quicknxs.config import user1 + + print user1.CONS1 # directly read from module + print user1['opt1'] # first time read from module than from user.ini file + +If the module does not define the 'config_file' variable it is treated as +a normal module, if it is None the storage is just temporary and if it +is the empty string it will use the default config file. + +The proxy allows simple interpolation by using '%(name)s' inside a variable +string, which will be substituted by the name variable from the same config. +To use variables from a different config use '%(config.name)s' syntax. +""" # hide imported modules for interactive use with IPython tab completion import os as _os import pkgutil as _pkgutil -from .baseconfig import ConfigProxy as _ConfigProxy from logging import warn as _warn +from .baseconfig import ConfigProxy as _ConfigProxy + _package_dir = _os.path.split(_os.path.abspath(__file__))[0] # prepare user config, if it does not exist -_config_path = _os.path.expanduser('~/.RefRed') +_config_path = _os.path.expanduser("~/.RefRed") if not _os.path.exists(_config_path): _os.mkdir(_config_path) # define ipython config path to seperate it from normal ipython configuration -_os.environ['IPYTHONDIR'] = _os.path.join(_config_path, 'ipython') +_os.environ["IPYTHONDIR"] = _os.path.join(_config_path, "ipython") proxy = None __all__ = [] def _create_proxy(): - ''' + """ Read all submodules and if config_file is defined add them to the ConfigProxy object that stores all information in .ini files. The usage in other modules is the same for both cases when no parameter is imported directly from the submodule. - ''' + """ global proxy, __all__ proxy = _ConfigProxy(_config_path) for ignore, name, ispackage in _pkgutil.iter_modules([_package_dir]): - if ispackage or name in ['baseconfig']: + if ispackage or name in ["baseconfig"]: continue try: - modi = __import__('RefRed.config.' + name, fromlist=[name]) + modi = __import__("RefRed.config." + name, fromlist=[name]) except Exception as error: _warn("Could not import module %s,\n %s: %s" % (name, error.__class__.__name__, error)) continue - if 'config_path' in modi.__dict__: + if "config_path" in modi.__dict__: moddict = {} for key, value in modi.__dict__.items(): if ( - key.startswith('_') - or key == 'config_path' - or hasattr(value, '__file__') - or hasattr(value, '__module__') - or type(value).__name__ == 'module' + key.startswith("_") + or key == "config_path" + or hasattr(value, "__file__") + or hasattr(value, "__module__") + or type(value).__name__ == "module" ): continue moddict[key] = value config_holder = proxy.add_path_config(name, moddict, modi.config_path) # noqa F841 - elif 'config_file' in modi.__dict__: + elif "config_file" in modi.__dict__: moddict = {} for key, value in modi.__dict__.items(): if ( - key.startswith('_') - or key == 'config_file' - or hasattr(value, '__file__') - or hasattr(value, '__module__') - or type(value).__name__ == 'module' + key.startswith("_") + or key == "config_file" + or hasattr(value, "__file__") + or hasattr(value, "__module__") + or type(value).__name__ == "module" ): continue moddict[key] = value diff --git a/RefRed/config/baseconfig.py b/RefRed/config/baseconfig.py index 9485065f..d23732ac 100644 --- a/RefRed/config/baseconfig.py +++ b/RefRed/config/baseconfig.py @@ -1,37 +1,38 @@ # -*- coding: utf-8 -*- -''' - Basis of the configuration system. The :class:`ConfigProxy` object - combines module parameters with temporary and user changeable - configuration file options. When used in other modules - this facility is completely hidden to the API. +""" +Basis of the configuration system. The :class:`ConfigProxy` object +combines module parameters with temporary and user changeable +configuration file options. When used in other modules +this facility is completely hidden to the API. - As each parameter can be accessed as an attribute of the ConfigHolder object - it behaves exactly like the according module would to, thus - IDEs with context sensitive syntax completion work with it as well. +As each parameter can be accessed as an attribute of the ConfigHolder object +it behaves exactly like the according module would to, thus +IDEs with context sensitive syntax completion work with it as well. - The initialization of all config modules is done in the config __init__ module. -''' +The initialization of all config modules is done in the config __init__ module. +""" -import os import atexit +import os import re import sys + from configobj import ConfigObj, ConfigObjError class ConfigProxy(object): - ''' + """ Handling of configuration options with temporal and fixed storage to .ini files in the used folder. Each configuration has it's own ConfigHolder object for access but one .ini file can hold several configurations. - ''' + """ _KEYCRE = re.compile(r"%\(([^)]*)\)s") # search pattern for interpolation _PARSE_ERRORS = None - default_storage = 'general' - config_path = '' + default_storage = "general" + config_path = "" configs = {} path_configs = {} storages = {} @@ -48,25 +49,25 @@ def __init__(self, config_path): # store .ini files on interpreter exit atexit.register(self.store) - def add_config(self, name, items, storage=''): - ''' + def add_config(self, name, items, storage=""): + """ Crate a new dictionary connected to a storage config file. :returns: The corresponding :class:`ConfigHolder` object. - ''' - if storage == '': + """ + if storage == "": storage = self.default_storage if storage is None: - storage = '_temp' - if '_temp' not in self.storages: + storage = "_temp" + if "_temp" not in self.storages: self.tmp_storages[storage] = {} # use the exact same dictionary object self.storages[storage] = self.tmp_storages[storage] elif storage not in self.storages: - sfile = os.path.join(self.config_path, storage + '.ini') + sfile = os.path.join(self.config_path, storage + ".ini") try: self.storages[storage] = ConfigObj( - infile=sfile, unrepr=True, encoding='utf8', indent_type=' ', interpolation=False + infile=sfile, unrepr=True, encoding="utf8", indent_type=" ", interpolation=False ) except ConfigObjError: self._PARSE_ERRORS.append( @@ -89,31 +90,31 @@ def add_config(self, name, items, storage=''): return self[name] def add_path_config(self, name, items, cpath): - ''' + """ Crate a new dictionary connected to a storage config file. :returns: The corresponding :class:`ConfigHolder` object. - ''' + """ # get last config from file, if it exists - ccfile = os.path.join(cpath, 'config_path_options.ini') + ccfile = os.path.join(cpath, "config_path_options.ini") if os.path.exists(ccfile): - ccopts = ConfigObj(infile=ccfile, unrepr=True, encoding='utf8', indent_type=' ', interpolation=False) - last_cfile = ccopts['last_file'] + ccopts = ConfigObj(infile=ccfile, unrepr=True, encoding="utf8", indent_type=" ", interpolation=False) + last_cfile = ccopts["last_file"] else: try: os.makedirs(cpath) except OSError: pass - ccopts = ConfigObj(infile=ccfile, unrepr=True, encoding='utf8', indent_type=' ', interpolation=False) - last_cfile = 'default' - ccopts['last_file'] = last_cfile - ccopts['config_files'] = [last_cfile] + ccopts = ConfigObj(infile=ccfile, unrepr=True, encoding="utf8", indent_type=" ", interpolation=False) + last_cfile = "default" + ccopts["last_file"] = last_cfile + ccopts["config_files"] = [last_cfile] if cpath not in self.storages: - sfile = os.path.join(cpath, last_cfile + '.ini') + sfile = os.path.join(cpath, last_cfile + ".ini") try: self.storages[cpath] = ConfigObj( - infile=sfile, unrepr=True, encoding='utf8', indent_type=' ', interpolation=False + infile=sfile, unrepr=True, encoding="utf8", indent_type=" ", interpolation=False ) except ConfigObjError: self._PARSE_ERRORS.append( @@ -147,7 +148,7 @@ def switch_path_config(self, cpath, cname): if cpath in self.configs and self.configs[cpath] in self.path_configs: cpath = self.configs[cpath] else: - raise KeyError('Config path %s is not defined' % cpath) + raise KeyError("Config path %s is not defined" % cpath) # save the current config to a file # remove constants for storage for ignore, config in list(self.storages[cpath].items()): @@ -157,10 +158,10 @@ def switch_path_config(self, cpath, cname): self.storages[cpath].write() # create a new config, from the defaults - sfile = os.path.join(cpath, cname + '.ini') + sfile = os.path.join(cpath, cname + ".ini") try: self.storages[cpath] = ConfigObj( - infile=sfile, unrepr=True, encoding='utf8', indent_type=' ', interpolation=False + infile=sfile, unrepr=True, encoding="utf8", indent_type=" ", interpolation=False ) except ConfigObjError: self._PARSE_ERRORS.append( @@ -169,8 +170,8 @@ def switch_path_config(self, cpath, cname): sys.exc_info(), ) ) - if cname not in self.path_configs[cpath][0]['config_files']: - self.path_configs[cpath][0]['config_files'].append(cname) + if cname not in self.path_configs[cpath][0]["config_files"]: + self.path_configs[cpath][0]["config_files"].append(cname) # update missing items from default config for name, items in list(self.path_configs[cpath][1].items()): @@ -181,31 +182,31 @@ def switch_path_config(self, cpath, cname): self.storages[cpath][name][key] = value else: self.storages[cpath][name] = dict(items) - self.path_configs[cpath][0]['last_file'] = cname + self.path_configs[cpath][0]["last_file"] = cname def get_path_configs(self, cpath): if cpath not in self.path_configs: if cpath in self.configs and self.configs[cpath] in self.path_configs: cpath = self.configs[cpath] else: - raise KeyError('Config path %s is not defined' % cpath) - return self.path_configs[cpath][0]['config_files'] + raise KeyError("Config path %s is not defined" % cpath) + return self.path_configs[cpath][0]["config_files"] def add_alias(self, config, alias): - ''' + """ Crate an alias for another configuration item. :returns: The corresponding :class:`ConfigHolder` object. - ''' + """ if config not in self.configs: - raise KeyError('no configuration named %s found' % config) + raise KeyError("no configuration named %s found" % config) self.aliases[alias] = config return self[config] def store(self): """store configuration data into .ini files.""" for item in list(self.storages.values()): - if not hasattr(item, 'write'): + if not hasattr(item, "write"): continue # remove constants for storage restore = {} @@ -240,9 +241,9 @@ def get_config_item(self, config, item): raise KeyError("%s is no known configuration" % config) storage = self.configs[config] # special convenience methods to switch the config file with the config object - if storage in self.path_configs and item == 'get_configs': + if storage in self.path_configs and item == "get_configs": return lambda: self.get_path_configs(storage) - if storage in self.path_configs and item == 'switch_config': + if storage in self.path_configs and item == "switch_config": return lambda new_config: self.switch_path_config(storage, new_config) # if item in self.tmp_storages[storage][config]: @@ -252,17 +253,17 @@ def get_config_item(self, config, item): value = self.storages[storage][config][item] if ( isinstance(value, str) - and '%' in value - and not self.storages[storage][config].get('NO_INTERPOLATION', False) + and "%" in value + and not self.storages[storage][config].get("NO_INTERPOLATION", False) ): # perform interpolation with constants if possible value = self.interpolate(config, value) return value def interpolate(self, config, value, recdepth=0): - ''' + """ Interpolate value with available options starting in the same configuration. - ''' + """ vtype = type(value) storage = self.configs[config] if recdepth > 5: @@ -276,7 +277,7 @@ def interpolate(self, config, value, recdepth=0): match_end = match.span()[1] match = self._KEYCRE.search(value[match_start + match_end :]) match_start += match_end - if '.' not in match_key: + if "." not in match_key: # search same config for value if match_key in self.tmp_storages[storage][config]: value = value.replace(match_str, vtype(self.tmp_storages[storage][config][match_key])) @@ -284,7 +285,7 @@ def interpolate(self, config, value, recdepth=0): value = value.replace(match_str, vtype(self.storages[storage][config][match_key])) else: # search other config for values - configi, match_key = match_key.split('.', 1) + configi, match_key = match_key.split(".", 1) if not (configi in self.configs or configi in self.aliases): continue if configi in self.aliases: @@ -294,7 +295,7 @@ def interpolate(self, config, value, recdepth=0): value = value.replace(match_str, vtype(self.tmp_storages[storagei][configi][match_key])) if match_key in self.storages[storagei][configi]: value = value.replace(match_str, vtype(self.storages[storagei][configi][match_key])) - if '%' in value: + if "%" in value: return self.interpolate(config, value, recdepth + 1) return value @@ -320,8 +321,8 @@ def get_config_keys(self, config): storage = self.configs[config] keys = list(self.storages[storage][config].keys()) if storage in self.path_configs: - keys.append('get_configs') - keys.append('switch_config') + keys.append("get_configs") + keys.append("switch_config") return keys def keys(self): @@ -341,19 +342,19 @@ def __len__(self): def __repr__(self): output = self.__class__.__name__ - output += '(storages=%i, configs=%i)' % (len(self.storages), len(self)) + output += "(storages=%i, configs=%i)" % (len(self.storages), len(self)) return output class ConfigHolder(object): - ''' + """ Dictionary like object connected to the a :class:`ConfigProxy` reading and writing values directly to that object. Each key can also be accessed as attribute of the object. To store items temporarily, the object supports a "temp" attribute, which itself is a ConfigHolder object. - ''' + """ def __init__(self, proxy, name, storetmp=False): self._proxy = proxy @@ -372,13 +373,13 @@ def __getattribute__(self, name): Basis of the parameter access (e.g. can use object.key to access object[key]). If a """ - if name.startswith('_') or name in dir(ConfigHolder): + if name.startswith("_") or name in dir(ConfigHolder): return object.__getattribute__(self, name) else: return self.__getitem__(name) def __setattr__(self, name, value): - if name.startswith('_') or name in dir(ConfigHolder): + if name.startswith("_") or name in dir(ConfigHolder): object.__setattr__(self, name, value) else: return self.__setitem__(name, value) @@ -404,10 +405,10 @@ def items(self): return [(str(key), self[key]) for key in list(self.keys())] def __repr__(self): - output = self.__class__.__name__ + '(' - spacer = '\n' + ' ' * len(output) - output += repr(dict(list(self.items()))).replace('\n', spacer) - output += ')' + output = self.__class__.__name__ + "(" + spacer = "\n" + " " * len(output) + output += repr(dict(list(self.items()))).replace("\n", spacer) + output += ")" return output def __dir__(self): diff --git a/RefRed/config/export.py b/RefRed/config/export.py index a1d8490b..72f1395a 100644 --- a/RefRed/config/export.py +++ b/RefRed/config/export.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- -''' +""" Options specific to the data file export in qio. -''' +""" -config_file = 'reduction' +config_file = "reduction" sampleSize = 10.0 diff --git a/RefRed/config/gui.py b/RefRed/config/gui.py index 3e46e912..f1cb13c3 100644 --- a/RefRed/config/gui.py +++ b/RefRed/config/gui.py @@ -1,12 +1,12 @@ # -*- coding: utf-8 -*- -''' +""" GUI configuration settings -''' +""" -config_file = 'gui' +config_file = "gui" # UI geometry -interface = 'default' +interface = "default" geometry = None state = None splitters = ([240, 505, 239], [298, 438], [240, 169, 360]) @@ -17,9 +17,9 @@ normalizeXTof = False # plot borders figure_params = [ - {'top': 0.95, 'right': 0.95, 'bottom': 0.1, 'left': 0.15}, # xy_overview - {'top': 0.95, 'right': 0.95, 'bottom': 0.1, 'left': 0.15}, # xtof_overview - {'top': 0.95, 'right': 0.95, 'bottom': 0.1, 'left': 0.15}, # refl - {'top': 0.95, 'right': 0.95, 'bottom': 0.1, 'left': 0.15}, # x_project - {'top': 0.95, 'right': 0.95, 'bottom': 0.1, 'left': 0.15}, # y_project + {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # xy_overview + {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # xtof_overview + {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # refl + {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # x_project + {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # y_project ] diff --git a/RefRed/config/instrument.py b/RefRed/config/instrument.py index b7152c8e..bb39c51b 100644 --- a/RefRed/config/instrument.py +++ b/RefRed/config/instrument.py @@ -1,19 +1,20 @@ # -*- coding: utf-8 -*- -''' +""" REF_L specific values. -''' +""" + from os.path import expanduser -config_file = '' +config_file = "" -NAME = 'REF_L' -BEAMLINE = '4B' +NAME = "REF_L" +BEAMLINE = "4B" # for the search of files by number -data_base = '/SNS/REF_L' -BASE_SEARCH = '*/data/REF_L_%s_' -OLD_BASE_SEARCH = '*/*/%s/NeXus/REF_L_%s*' -LIVE_DATA = '/SNS/REF_L/shared/LiveData/meta_data.xml' -EXTENSION_SCRIPTS = '/SNS/REF_L/shared/quicknxs_scripts' +data_base = "/SNS/REF_L" +BASE_SEARCH = "*/data/REF_L_%s_" +OLD_BASE_SEARCH = "*/*/%s/NeXus/REF_L_%s*" +LIVE_DATA = "/SNS/REF_L/shared/LiveData/meta_data.xml" +EXTENSION_SCRIPTS = "/SNS/REF_L/shared/quicknxs_scripts" -local_data_base = expanduser('~/') +local_data_base = expanduser("~/") diff --git a/RefRed/config/metadataSelected.py b/RefRed/config/metadataSelected.py index 84a27088..b261c866 100644 --- a/RefRed/config/metadataSelected.py +++ b/RefRed/config/metadataSelected.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- -''' +""" This will keep record of all the metadata previously selected -''' +""" import os -config_path = os.path.expanduser('~/tmp/path_config') +config_path = os.path.expanduser("~/tmp/path_config") -metadata_list = [''] +metadata_list = [""] diff --git a/RefRed/config/misc.py b/RefRed/config/misc.py index eb2f9f96..b7632db7 100644 --- a/RefRed/config/misc.py +++ b/RefRed/config/misc.py @@ -1,17 +1,17 @@ # -*- coding: utf-8 -*- -''' - doc -''' +""" +doc +""" -config_file = '' +config_file = "" -ADMIN = 'Jean Bilheux' -ADMIN_EMAIL = 'j35@ornl.gov' -SMTP_SERVER = '128.219.166.53' +ADMIN = "Jean Bilheux" +ADMIN_EMAIL = "j35@ornl.gov" +SMTP_SERVER = "128.219.166.53" -SCRIPT_VERSION = '1.0' +SCRIPT_VERSION = "1.0" debug_mode = False -default_log_levels = {'CONSOLE': 'WARNING', 'FILE': 'INFO', 'GUI': 'INFO'} -debug_log_levels = {'CONSOLE': 'DEBUG', 'FILE': 'DEBUG', 'GUI': 'INFO'} -pdb_log_levels = {'CONSOLE': 'DEBUG', 'FILE': 'INFO', 'GUI': 'INFO'} +default_log_levels = {"CONSOLE": "WARNING", "FILE": "INFO", "GUI": "INFO"} +debug_log_levels = {"CONSOLE": "DEBUG", "FILE": "DEBUG", "GUI": "INFO"} +pdb_log_levels = {"CONSOLE": "DEBUG", "FILE": "INFO", "GUI": "INFO"} diff --git a/RefRed/config/output_templates.py b/RefRed/config/output_templates.py index 310dde0b..4cfca760 100644 --- a/RefRed/config/output_templates.py +++ b/RefRed/config/output_templates.py @@ -1,9 +1,9 @@ # -*- coding: utf-8 -*- -''' - Templeates used for ASCII file creation. -''' +""" +Templeates used for ASCII file creation. +""" -config_file = 'reduction' +config_file = "reduction" NO_INTERPOLATION = True gp_template = """#!/usr/bin/gnuplot @@ -62,16 +62,16 @@ # u'"%(file_name)s" u 1:2 smooth csplines t "" lw 1.5 lc %(index)i' gp_line_3D = 'splot "%(file_name)s" u %(x)i:%(y)i:(Imin($%(z)i)) w pm3d t ""' # GP_LINE_3D=u'splot "%(file_name)s" u %(x)i:%(y)i:%(z)i w pm3d t ""' -GP_SEP = ',\\\n ' +GP_SEP = ",\\\n " GP_SEP_3D = '\nset title "%s"\n' # set of characters to replace, as they can't be iso_8859_1 encoded but are # available with gnuplot enhanced commands -GP_REPLACE_CHARS = (('α', '{/Symbol a}'), ('δ', '{/Symbol d}')) +GP_REPLACE_CHARS = (("α", "{/Symbol a}"), ("δ", "{/Symbol d}")) -gp_font_paths = ['/usr/share/fonts/dejavu/', '/usr/share/fonts/truetype/ttf-dejavu/'] +gp_font_paths = ["/usr/share/fonts/dejavu/", "/usr/share/fonts/truetype/ttf-dejavu/"] -FILE_HEADER = '''# Datafile created by QuickNXS %(version)s +FILE_HEADER = """# Datafile created by QuickNXS %(version)s # Date: %(date)s # Type: %(datatype)s # Input file indices: %(indices)s @@ -89,19 +89,19 @@ # %(column_units)s # Column Names: # %(column_names)s -''' # noqa E501 +""" # noqa E501 FILE_HEADER_PARAMS = ( - '%(scale)-12g %(P0)-3i %(PN)-5i %(x_pos)-8g %(x_width)-12g %(y_pos)-8g %(y_width)-12g ' - '%(bg_pos)-8g %(bg_width)-12g %(dpix)-12g %(tth)-12g %(file_number)-12s %(norm_index)-9s ' - '%(extract_fan)-4i %(file_name)-12s ' + "%(scale)-12g %(P0)-3i %(PN)-5i %(x_pos)-8g %(x_width)-12g %(y_pos)-8g %(y_width)-12g " + "%(bg_pos)-8g %(bg_width)-12g %(dpix)-12g %(tth)-12g %(file_number)-12s %(norm_index)-9s " + "%(extract_fan)-4i %(file_name)-12s " ) DICTIZE_CHANNELS = { - 'x': 'unpolarized', - '+': 'up', - '-': 'down', - '++': 'upup', - '--': 'downdown', - '+-': 'updown', - '-+': 'downup', + "x": "unpolarized", + "+": "up", + "-": "down", + "++": "upup", + "--": "downdown", + "+-": "updown", + "-+": "downup", } diff --git a/RefRed/config/plotting.py b/RefRed/config/plotting.py index bdd0d2f3..64987cba 100644 --- a/RefRed/config/plotting.py +++ b/RefRed/config/plotting.py @@ -1,14 +1,14 @@ # -*- coding: utf-8 -*- -''' +""" Options for the matplotlib graph creation. -''' +""" -config_file = 'gui' +config_file = "gui" font = { - 'family': 'serif', + "family": "serif", # 'weight' : 'normal', # 'variant': 'DejaVuSerif', - 'size': 7, + "size": 7, } -savefig = {'dpi': 600} +savefig = {"dpi": 600} diff --git a/RefRed/config/ref_l.py b/RefRed/config/ref_l.py index 27b6efdf..3b16c43a 100644 --- a/RefRed/config/ref_l.py +++ b/RefRed/config/ref_l.py @@ -1,16 +1,16 @@ # -*- coding: utf-8 -*- -''' +""" REF_L specific values. -''' +""" -config_file = '' +config_file = "" -NAME = 'REF_L' -BEAMLINE = '4B' +NAME = "REF_L" +BEAMLINE = "4B" # for the search of files by number -data_base = '/SNS/REF_L' -BASE_SEARCH = '*/data/REF_L_%s_' -OLD_BASE_SEARCH = '*/*/%s/NeXus/REF_L_%s*' -LIVE_DATA = '/SNS/REF_L/shared/LiveData/meta_data.xml' -EXTENSION_SCRIPTS = '/SNS/REF_L/shared/quicknxs_scripts' +data_base = "/SNS/REF_L" +BASE_SEARCH = "*/data/REF_L_%s_" +OLD_BASE_SEARCH = "*/*/%s/NeXus/REF_L_%s*" +LIVE_DATA = "/SNS/REF_L/shared/LiveData/meta_data.xml" +EXTENSION_SCRIPTS = "/SNS/REF_L/shared/quicknxs_scripts" diff --git a/RefRed/config/refllastloadedfiles.py b/RefRed/config/refllastloadedfiles.py index 0b1f80f1..18a0d053 100644 --- a/RefRed/config/refllastloadedfiles.py +++ b/RefRed/config/refllastloadedfiles.py @@ -1,31 +1,31 @@ # -*- coding: utf-8 -*- -''' +""" This will keep record of all the last config, ascii and reduced files -''' +""" import os -config_path = os.path.expanduser('~/tmp/path_config') +config_path = os.path.expanduser("~/tmp/path_config") -reduce1 = '' -date1 = '' -reduce2 = '' -date2 = '' -reduce3 = '' -date3 = '' -reduce4 = '' -date4 = '' -reduce5 = '' -date5 = '' -reduce6 = '' -date6 = '' -reduce7 = '' -date7 = '' -reduce8 = '' -date8 = '' -reduce9 = '' -date9 = '' -reduce10 = '' -date10 = '' +reduce1 = "" +date1 = "" +reduce2 = "" +date2 = "" +reduce3 = "" +date3 = "" +reduce4 = "" +date4 = "" +reduce5 = "" +date5 = "" +reduce6 = "" +date6 = "" +reduce7 = "" +date7 = "" +reduce8 = "" +date8 = "" +reduce9 = "" +date9 = "" +reduce10 = "" +date10 = "" -config_files_path = '' +config_files_path = "" diff --git a/RefRed/configuration/export_xml_config.py b/RefRed/configuration/export_xml_config.py index c2b79dd1..3a0eaaa8 100644 --- a/RefRed/configuration/export_xml_config.py +++ b/RefRed/configuration/export_xml_config.py @@ -21,33 +21,31 @@ def __init__(self, parent=None): def header_part(self): str_array = self.str_array - str_array.append('\n') - str_array.append(' REFL\n') - str_array.append(' ' + datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p") + '\n') - str_array.append(' %s\n' % lr_reduction.__version__) - str_array.append(' ' + mantid.__version__ + '\n') - str_array.append('RefRed-%s\n' % RefRed.__version__) + str_array.append("\n") + str_array.append(" REFL\n") + str_array.append(" " + datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p") + "\n") + str_array.append(" %s\n" % lr_reduction.__version__) + str_array.append(" " + mantid.__version__ + "\n") + str_array.append("RefRed-%s\n" % RefRed.__version__) # metadata - str_array.append(' \n') + str_array.append(" \n") self.str_array = str_array def main_part(self): - str_array = self.str_array _big_table_data = self.parent.big_table_data nbr_row = self.parent.REDUCTIONTABLE_MAX_ROWCOUNT o_general_settings = GlobalReductionSettingsHandler(parent=self.parent) for row in range(nbr_row): - _data: LRData = _big_table_data[row, 0] if _data is None: break # we found the first empty row in the reduction table. No more runs available - str_array.append(' \n') - str_array.append(' narrow\n') + str_array.append(" \n") + str_array.append(" narrow\n") data_peak = _data.peak data_back = _data.back @@ -85,79 +83,79 @@ def main_part(self): norm_low_res_flag = False norm_lambda_requested = -1 - str_array.append(' ' + str(data_peak[0]) + '\n') - str_array.append(' ' + str(data_peak[1]) + '\n') - str_array.append(' N/A\n') - str_array.append(' ' + str(data_back_flag) + '\n') - str_array.append(' ' + str(data_two_backgrounds) + '\n') - str_array.append(' ' + str(data_back[0]) + '\n') - str_array.append(' ' + str(data_back[1]) + '\n') - str_array.append(' ' + str(data_back2[0]) + '\n') - str_array.append(' ' + str(data_back2[1]) + '\n') - str_array.append(' True\n') - str_array.append(' ' + str(tof[0]) + '\n') - str_array.append(' ' + str(tof[1]) + '\n') - str_array.append(' ' + str(q_range[0]) + '\n') - str_array.append(' ' + str(q_range[1]) + '\n') - str_array.append(' ' + str(lambda_range[0]) + '\n') - str_array.append(' ' + str(lambda_range[1]) + '\n') - str_array.append(' ' + str(incident_angle) + '\n') + str_array.append(" " + str(data_peak[0]) + "\n") + str_array.append(" " + str(data_peak[1]) + "\n") + str_array.append(" N/A\n") + str_array.append(" " + str(data_back_flag) + "\n") + str_array.append(" " + str(data_two_backgrounds) + "\n") + str_array.append(" " + str(data_back[0]) + "\n") + str_array.append(" " + str(data_back[1]) + "\n") + str_array.append(" " + str(data_back2[0]) + "\n") + str_array.append(" " + str(data_back2[1]) + "\n") + str_array.append(" True\n") + str_array.append(" " + str(tof[0]) + "\n") + str_array.append(" " + str(tof[1]) + "\n") + str_array.append(" " + str(q_range[0]) + "\n") + str_array.append(" " + str(q_range[1]) + "\n") + str_array.append(" " + str(lambda_range[0]) + "\n") + str_array.append(" " + str(lambda_range[1]) + "\n") + str_array.append(" " + str(incident_angle) + "\n") _data_run_number = str(self.parent.ui.reductionTable.item(row, 1).text()) - str_array.append(' ' + _data_run_number + '\n') + str_array.append(" " + _data_run_number + "\n") # if type(data_full_file_name) == type([]): # data_full_file_name = ','.join(data_full_file_name) # str_array.append(' ' + data_full_file_name + '\n') - str_array.append(' ' + str(data_low_res[0]) + '\n') - str_array.append(' ' + str(data_low_res[1]) + '\n') - str_array.append(' ' + str(data_low_res_flag) + '\n') + str_array.append(" " + str(data_low_res[0]) + "\n") + str_array.append(" " + str(data_low_res[1]) + "\n") + str_array.append(" " + str(data_low_res_flag) + "\n") tthd = str(self.parent.ui.metadatatthdValue.text()) - str_array.append(' ' + tthd + '\n') + str_array.append(" " + tthd + "\n") ths = str(self.parent.ui.metadatathiValue.text()) - str_array.append(' ' + ths + '\n') - str_array.append(' ' + str(data_lambda_requested) + '\n') - - str_array.append(' ' + str(norm_flag) + '\n') - str_array.append(' ' + str(norm_low_res_flag) + '\n') - str_array.append(' ' + str(norm_low_res[1]) + '\n') - str_array.append(' ' + str(norm_low_res[0]) + '\n') - str_array.append(' ' + str(norm_peak[0]) + '\n') - str_array.append(' ' + str(norm_peak[1]) + '\n') - str_array.append(' ' + str(norm_back_flag) + '\n') - str_array.append(' ' + str(norm_two_backgrounds) + '\n') - str_array.append(' ' + str(norm_back[0]) + '\n') - str_array.append(' ' + str(norm_back[1]) + '\n') - str_array.append(' ' + str(norm_back2[0]) + '\n') - str_array.append(' ' + str(norm_back2[1]) + '\n') - str_array.append(' ' + str(norm_lambda_requested) + '\n') + str_array.append(" " + ths + "\n") + str_array.append(" " + str(data_lambda_requested) + "\n") + + str_array.append(" " + str(norm_flag) + "\n") + str_array.append(" " + str(norm_low_res_flag) + "\n") + str_array.append(" " + str(norm_low_res[1]) + "\n") + str_array.append(" " + str(norm_low_res[0]) + "\n") + str_array.append(" " + str(norm_peak[0]) + "\n") + str_array.append(" " + str(norm_peak[1]) + "\n") + str_array.append(" " + str(norm_back_flag) + "\n") + str_array.append(" " + str(norm_two_backgrounds) + "\n") + str_array.append(" " + str(norm_back[0]) + "\n") + str_array.append(" " + str(norm_back[1]) + "\n") + str_array.append(" " + str(norm_back2[0]) + "\n") + str_array.append(" " + str(norm_back2[1]) + "\n") + str_array.append(" " + str(norm_lambda_requested) + "\n") _norm_run_number_cell = self.parent.ui.reductionTable.item(row, 2).text() - if str(_norm_run_number_cell) != '': + if str(_norm_run_number_cell) != "": _norm_run_number = str(_norm_run_number_cell) else: - _norm_run_number = '0' - str_array.append(' ' + _norm_run_number + '\n') + _norm_run_number = "0" + str_array.append(" " + _norm_run_number + "\n") # if type(norm_full_file_name) == type([]): # norm_full_file_name = ','.join(norm_full_file_name) # str_array.append(' ' + norm_full_file_name + '\n') - str_array.append(' False\n') + str_array.append(" False\n") # The angle offset is currently not exposed in the UI, so we set it to 0. - str_array.append(' 0 \n') - str_array.append(' 0 \n') + str_array.append(" 0 \n") + str_array.append(" 0 \n") q_step = str(self.parent.ui.qStep.text()) - str_array.append(' ' + q_step + '\n') - q_min = str(self.parent.gui_metadata['q_min']) - str_array.append(' ' + q_min + '\n') + str_array.append(" " + q_step + "\n") + q_min = str(self.parent.gui_metadata["q_min"]) + str_array.append(" " + q_min + "\n") scalingFactorFlag = self.parent.ui.scalingFactorFlag.isChecked() - str_array.append(' ' + str(scalingFactorFlag) + '\n') + str_array.append(" " + str(scalingFactorFlag) + "\n") scalingFactorFile = o_general_settings.scaling_factor_file - str_array.append(' ' + scalingFactorFile + '\n') + str_array.append(" " + scalingFactorFile + "\n") # incident medium allItems = [ @@ -166,23 +164,23 @@ def main_part(self): ] finalList = allItems[1:] strFinalList = ",".join(finalList) - str_array.append(' ' + strFinalList + '\n') + str_array.append(" " + strFinalList + "\n") imIndex = self.parent.ui.selectIncidentMediumList.currentIndex() str_array.append( - ' ' + str(imIndex - 1) + '\n' + " " + str(imIndex - 1) + "\n" ) - str_array.append(' True\n') + str_array.append(" True\n") str_array.append(o_general_settings.dead_time.to_xml(indent=" ") + "\n") # dead time settings - str_array.append(' ' + str(const_q) + '\n') + str_array.append(" " + str(const_q) + "\n") - str_array.append(' \n') + str_array.append(" \n") - str_array.append(' \n') - str_array.append('\n') + str_array.append(" \n") + str_array.append("\n") self.str_array = str_array def save(self, filename: str): @@ -198,7 +196,7 @@ def save(self, filename: str): if os.path.isfile(filename): os.remove(filename) - with open(filename, 'w') as outfile: + with open(filename, "w") as outfile: outfile.writelines(self.str_array) logging.info(f"Config is saved to {filename}.") diff --git a/RefRed/configuration/load_reduction_table_from_lconfigdataset.py b/RefRed/configuration/load_reduction_table_from_lconfigdataset.py index b25dec88..2a1d78fd 100644 --- a/RefRed/configuration/load_reduction_table_from_lconfigdataset.py +++ b/RefRed/configuration/load_reduction_table_from_lconfigdataset.py @@ -1,16 +1,16 @@ from qtpy import QtGui, QtWidgets + +import RefRed.colors from RefRed.calculations.add_list_nexus import AddListNexus -from RefRed.calculations.lr_data import LRData from RefRed.calculations.locate_list_run import LocateListRun +from RefRed.calculations.lr_data import LRData from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata +from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.progressbar_handler import ProgressBarHandler from RefRed.plot.display_plots import DisplayPlots -from RefRed.gui_handling.gui_utility import GuiUtility -import RefRed.colors class LoadReductionTableFromLConfigDataSet(object): - parent = None def __init__(self, parent=None): @@ -19,7 +19,7 @@ def __init__(self, parent=None): nbr_lconfig = self.get_nbr_lconfig() big_table_data = self.parent.big_table_data o_load_config_progressbar_handler = ProgressBarHandler(parent=parent) - o_load_config_progressbar_handler.setup(nbr_reduction=nbr_lconfig, label='Loading Config.') + o_load_config_progressbar_handler.setup(nbr_reduction=nbr_lconfig, label="Loading Config.") for index_row, lconfig in enumerate(big_table_data[:, 2]): if lconfig is None: @@ -35,10 +35,10 @@ def __init__(self, parent=None): list_run=list_data_run, metadata_only=False, check_nexus_compatibility=False, - prefix='data', + prefix="data", ) data_lrdata = LRData(_add_data_nexus.wks, lconfig=lconfig, is_data=True, parent=self.parent) - self.update_lrdata(lrdata=data_lrdata, lconfig=lconfig, type='data', row=index_row) + self.update_lrdata(lrdata=data_lrdata, lconfig=lconfig, type="data", row=index_row) list_norm_run = lconfig.norm_sets o_list_norm_nexus = LocateListRun(list_run=list_norm_run) @@ -49,10 +49,10 @@ def __init__(self, parent=None): list_run=list_norm_run, metadata_only=False, check_nexus_compatibility=False, - prefix='norm', + prefix="norm", ) norm_lrdata = LRData(_add_norm_nexus.wks, is_data=False, parent=self.parent) - self.update_lrdata(lrdata=norm_lrdata, lconfig=lconfig, type='norm', row=index_row) + self.update_lrdata(lrdata=norm_lrdata, lconfig=lconfig, type="norm", row=index_row) is_display_requested = self.display_of_this_row_checked(index_row) if is_display_requested: @@ -89,10 +89,10 @@ def get_nbr_lconfig(self): nbr_row += 1 return nbr_row - def update_lrdata(self, lrdata=None, lconfig=None, type='data', row=0): + def update_lrdata(self, lrdata=None, lconfig=None, type="data", row=0): big_table_data = self.parent.big_table_data - if type == 'data': + if type == "data": peak1 = int(lconfig.data_peak[0]) peak2 = int(lconfig.data_peak[1]) back1_1 = int(lconfig.data_back[0]) @@ -137,12 +137,12 @@ def update_lrdata(self, lrdata=None, lconfig=None, type='data', row=0): lrdata.full_file_name = full_file_name lrdata.const_q = const_q - index_col = 0 if type == 'data' else 1 + index_col = 0 if type == "data" else 1 reduction_table_index_col = index_col + 1 big_table_data[row, index_col] = lrdata self.parent.big_table_data = big_table_data - if type == 'data': + if type == "data": UpdateReductionTableMetadata(parent=self.parent, lrdata=lrdata, row=row) QtWidgets.QApplication.processEvents() diff --git a/RefRed/configuration/loading_configuration.py b/RefRed/configuration/loading_configuration.py index 29c38254..23e20c72 100644 --- a/RefRed/configuration/loading_configuration.py +++ b/RefRed/configuration/loading_configuration.py @@ -1,8 +1,8 @@ # standard imports import logging import os -from xml.dom import minidom from typing import Any +from xml.dom import minidom # third party imports from qtpy import QtWidgets @@ -12,7 +12,6 @@ from RefRed.configuration.load_reduction_table_from_lconfigdataset import ( LoadReductionTableFromLConfigDataSet as LoadReductionTable, ) - from RefRed.configuration.populate_reduction_table_from_lconfigdataset import ( PopulateReductionTableFromLConfigDataSet as PopulateReductionTable, ) diff --git a/RefRed/configuration/populate_reduction_table_from_lconfigdataset.py b/RefRed/configuration/populate_reduction_table_from_lconfigdataset.py index af1089cd..ab5b1922 100644 --- a/RefRed/configuration/populate_reduction_table_from_lconfigdataset.py +++ b/RefRed/configuration/populate_reduction_table_from_lconfigdataset.py @@ -1,5 +1,4 @@ class PopulateReductionTableFromLConfigDataSet(object): - parent = None def __init__(self, parent=None): diff --git a/RefRed/configuration/saving_configuration.py b/RefRed/configuration/saving_configuration.py index 6b86be0f..8ec2a215 100644 --- a/RefRed/configuration/saving_configuration.py +++ b/RefRed/configuration/saving_configuration.py @@ -1,27 +1,28 @@ -from qtpy import QtWidgets import os + +from qtpy import QtWidgets + from RefRed.configuration.export_xml_config import ExportXMLConfig -from RefRed.utilities import makeSureFileHasExtension -from RefRed.status_message_handler import StatusMessageHandler from RefRed.gui_handling.gui_utility import GuiUtility +from RefRed.status_message_handler import StatusMessageHandler +from RefRed.utilities import makeSureFileHasExtension class SavingConfiguration(object): - parent = None - def __init__(self, parent=None, filename=''): + def __init__(self, parent=None, filename=""): self.parent = parent self.filename = filename - StatusMessageHandler(parent=self.parent, message='Saving config ...', is_threaded=False) + StatusMessageHandler(parent=self.parent, message="Saving config ...", is_threaded=False) def run(self): - if self.filename == '': + if self.filename == "": _path = self.parent.path_config _filter = "XML (*.xml);; All Files (*.*)" - file_dialog = QtWidgets.QFileDialog(self.parent, 'Save Configuration File', _path, _filter) + file_dialog = QtWidgets.QFileDialog(self.parent, "Save Configuration File", _path, _filter) file_dialog.setViewMode(QtWidgets.QFileDialog.List) file_dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) file_dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) @@ -42,7 +43,7 @@ def run(self): self.filename = makeSureFileHasExtension(self.filename) ExportXMLConfig(parent=self.parent).save(self.filename) - StatusMessageHandler(parent=self.parent, message='Done!', is_threaded=True) + StatusMessageHandler(parent=self.parent, message="Done!", is_threaded=True) o_gui_utility = GuiUtility(parent=self.parent) o_gui_utility.new_config_file_loaded(config_file_name=self.filename) diff --git a/RefRed/configuration/user_configuration.py b/RefRed/configuration/user_configuration.py index a224b680..d0fb01c5 100644 --- a/RefRed/configuration/user_configuration.py +++ b/RefRed/configuration/user_configuration.py @@ -1,5 +1,4 @@ class UserConfiguration(object): - is_reduced_plot_stitching_tab_ylog = True is_reduced_plot_stitching_tab_xlog = False diff --git a/RefRed/configuration/user_configuration_handler.py b/RefRed/configuration/user_configuration_handler.py index a1688547..be282eff 100644 --- a/RefRed/configuration/user_configuration_handler.py +++ b/RefRed/configuration/user_configuration_handler.py @@ -1,6 +1,8 @@ -from qtpy.QtCore import QSettings # type: ignore import os -from RefRed import ORGANIZATION, APPNAME + +from qtpy.QtCore import QSettings # type: ignore + +from RefRed import APPNAME, ORGANIZATION from RefRed.configuration.user_configuration import UserConfiguration from RefRed.utilities import str2bool @@ -12,16 +14,16 @@ def __init__(self, parent=None): self.parent = parent settings = QSettings(ORGANIZATION, APPNAME) - self.parent.path_ascii = str(settings.value("path_ascii", os.path.expanduser('~'))) + self.parent.path_ascii = str(settings.value("path_ascii", os.path.expanduser("~"))) - self.parent.path_config = str(settings.value("path_config", os.path.expanduser('~'))) + self.parent.path_config = str(settings.value("path_config", os.path.expanduser("~"))) o_user_config = UserConfiguration() ylog_value = str(settings.value("is_reduced_plot_stitching_tab_ylog")) - if ylog_value != '': + if ylog_value != "": o_user_config.is_reduced_plot_stitching_tab_ylog = str2bool(ylog_value) xlog_value = str(settings.value("is_reduced_plot_stitching_tab_xlog")) - if xlog_value != '': + if xlog_value != "": o_user_config.is_reduced_plot_stitching_tab_xlog = str2bool(xlog_value) self.parent.o_user_configuration = o_user_config @@ -31,12 +33,12 @@ def __init__(self, parent=None): self.parent = parent settings = QSettings(ORGANIZATION, APPNAME) - settings.setValue('path_ascii', self.parent.path_ascii) - settings.setValue('path_config', self.parent.path_config) + settings.setValue("path_ascii", self.parent.path_ascii) + settings.setValue("path_config", self.parent.path_config) o_user_config = self.parent.o_user_configuration - settings.setValue('is_reduced_plot_stitching_tab_xlog', str(o_user_config.is_reduced_plot_stitching_tab_xlog)) - settings.setValue('is_reduced_plot_stitching_tab_ylog', str(o_user_config.is_reduced_plot_stitching_tab_ylog)) + settings.setValue("is_reduced_plot_stitching_tab_xlog", str(o_user_config.is_reduced_plot_stitching_tab_xlog)) + settings.setValue("is_reduced_plot_stitching_tab_ylog", str(o_user_config.is_reduced_plot_stitching_tab_ylog)) _gui_metadata = self.parent.gui_metadata for _key in _gui_metadata.keys(): diff --git a/RefRed/decorators.py b/RefRed/decorators.py index eb72529c..9c5cc1c5 100644 --- a/RefRed/decorators.py +++ b/RefRed/decorators.py @@ -1,19 +1,21 @@ -''' - Module for useful decorators -''' +""" +Module for useful decorators +""" -from qtpy import QtGui, QtCore, QtWidgets -from RefRed import WINDOW_TITLE from functools import wraps + from mantid.kernel import ConfigService, Logger +from qtpy import QtCore, QtGui, QtWidgets + +from RefRed import WINDOW_TITLE def _shouldShowLogs(): - '''Determine whether logs will be shown on startup''' - levels = ['debug', 'information', 'notice', 'warning', 'error', 'critical', 'fatal'] - log_level_str = ConfigService.getString('logging.loggers.root.level') + """Determine whether logs will be shown on startup""" + levels = ["debug", "information", "notice", "warning", "error", "critical", "fatal"] + log_level_str = ConfigService.getString("logging.loggers.root.level") if log_level_str in levels: - return levels.index('debug') >= levels.index(log_level_str) + return levels.index("debug") >= levels.index(log_level_str) else: # default behavior is to let mantid sort things out return True @@ -22,7 +24,7 @@ def _shouldShowLogs(): # finish setting up determining whether to log SHOULD_LOG = _shouldShowLogs() del _shouldShowLogs -_mantid_logger = Logger('RefRed') # handle to the logger +_mantid_logger = Logger("RefRed") # handle to the logger _write_log = _mantid_logger.debug # pointer to the object's method # @@ -31,24 +33,24 @@ def _shouldShowLogs(): def _to_call_signature(func_ptr, ref_ptr=None, *args, **kwargs) -> str: - '''Helper function to convert function call to an overly detailed string representation''' + """Helper function to convert function call to an overly detailed string representation""" func_name = func_ptr.__name__ if ref_ptr: - func_name = f'{ref_ptr}.{func_name}' + func_name = f"{ref_ptr}.{func_name}" # check for log level and skip converting values to string if level is too high if SHOULD_LOG: - args_str = ', '.join([f'{item}' for item in args] + [f'{key}={value}' for key, value in kwargs.items()]) + args_str = ", ".join([f"{item}" for item in args] + [f"{key}={value}" for key, value in kwargs.items()]) else: - args_str = 'NOT SHOWN' - return f'{func_name}({args_str})' + args_str = "NOT SHOWN" + return f"{func_name}({args_str})" def log_qtpy_slot(function): - '''qt slots are called with a unique signature that don't appear to match the native function signature''' + """qt slots are called with a unique signature that don't appear to match the native function signature""" @wraps(function) def wrapper_func(ref): - _write_log('qtpy slot ' + _to_call_signature(function, ref)) + _write_log("qtpy slot " + _to_call_signature(function, ref)) return function(ref) return wrapper_func @@ -57,7 +59,7 @@ def wrapper_func(ref): def log_function(function): @wraps(function) def wrapper_func(*args, **kwargs): - _write_log(_to_call_signature(function, ref_ptr='', *args, **kwargs)) + _write_log(_to_call_signature(function, ref_ptr="", *args, **kwargs)) return function(*args, **kwargs) return wrapper_func diff --git a/RefRed/export/ascii_loader.py b/RefRed/export/ascii_loader.py index 66617138..52238c8c 100644 --- a/RefRed/export/ascii_loader.py +++ b/RefRed/export/ascii_loader.py @@ -1,6 +1,5 @@ import numpy as np - Filepath = str diff --git a/RefRed/export/export_plot_ascii.py b/RefRed/export/export_plot_ascii.py index 9a6dca8e..b18e0ad8 100644 --- a/RefRed/export/export_plot_ascii.py +++ b/RefRed/export/export_plot_ascii.py @@ -3,20 +3,19 @@ from pathlib import Path from typing import List, Tuple +from lr_reduction import output as lr_output + # third-party imorts from qtpy.QtWidgets import QFileDialog # RefRed imports import RefRed.utilities from RefRed.gui_handling.gui_utility import GuiUtility -from RefRed.utilities import makeSureFileHasExtension from RefRed.reduction.reduced_data_handler import ReducedDataHandler - -from lr_reduction import output as lr_output +from RefRed.utilities import makeSureFileHasExtension class ExportPlotAscii: - # NOTE: # figure layout as of 10-22-2021 # ------------ main window ------------| @@ -247,10 +246,10 @@ def write_output_file(self, file_path): refl = sf * _data.reduce_y_axis d_refl = sf * _data.reduce_e_axis - _data.meta_data['scaling_factors']['a'] = sf * _data.meta_data['scaling_factors']['a'] - _data.meta_data['scaling_factors']['err_a'] = sf * _data.meta_data['scaling_factors']['err_a'] - _data.meta_data['scaling_factors']['b'] = sf * _data.meta_data['scaling_factors']['b'] - _data.meta_data['scaling_factors']['err_b'] = sf * _data.meta_data['scaling_factors']['err_b'] + _data.meta_data["scaling_factors"]["a"] = sf * _data.meta_data["scaling_factors"]["a"] + _data.meta_data["scaling_factors"]["err_a"] = sf * _data.meta_data["scaling_factors"]["err_a"] + _data.meta_data["scaling_factors"]["b"] = sf * _data.meta_data["scaling_factors"]["b"] + _data.meta_data["scaling_factors"]["err_b"] = sf * _data.meta_data["scaling_factors"]["err_b"] coll.add(qz_mid, refl, d_refl, meta_data=_data.meta_data) diff --git a/RefRed/export/reduced_ascii_loader.py b/RefRed/export/reduced_ascii_loader.py index b6e384fa..7b730399 100644 --- a/RefRed/export/reduced_ascii_loader.py +++ b/RefRed/export/reduced_ascii_loader.py @@ -1,4 +1,5 @@ import os + from RefRed.export.ascii_loader import AsciiLoader @@ -22,7 +23,7 @@ def __init__(self, parent, ascii_file_name: str = "", is_live_reduction: bool = self.is_live_reduction = is_live_reduction if is_live_reduction: self.ascii_file_name = "LAST REDUCED SET" - self.short_ascii_file_name = 'LAST REDUCED SET' + self.short_ascii_file_name = "LAST REDUCED SET" self.big_table_data = self.parent.big_table_data else: self.ascii_file_name = ascii_file_name diff --git a/RefRed/file_loading_utility.py b/RefRed/file_loading_utility.py index e25dd162..da31cc5b 100644 --- a/RefRed/file_loading_utility.py +++ b/RefRed/file_loading_utility.py @@ -1,5 +1,5 @@ """ - TODO: verify whether this is really needed +TODO: verify whether this is really needed """ # third party packages @@ -11,4 +11,4 @@ def loadCsvFile(filename): :param str filename: Absolute path to CSV file :return List[float]:Three-item list, each item being one file column """ - return [column.tolist() for column in np.genfromtxt(filename, delimiter=',').transpose()] + return [column.tolist() for column in np.genfromtxt(filename, delimiter=",").transpose()] diff --git a/RefRed/gui_handling/auto_tof_range_radio_button_handler.py b/RefRed/gui_handling/auto_tof_range_radio_button_handler.py index 7d9a8ad7..25bbf064 100644 --- a/RefRed/gui_handling/auto_tof_range_radio_button_handler.py +++ b/RefRed/gui_handling/auto_tof_range_radio_button_handler.py @@ -1,10 +1,9 @@ +from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.plot.display_plots import DisplayPlots -from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata class AutoTofRangeRadioButtonHandler(object): - parent = None all_rows = [] row = -1 diff --git a/RefRed/gui_handling/data_norm_spinboxes.py b/RefRed/gui_handling/data_norm_spinboxes.py index 2e7ff891..1d221ecd 100644 --- a/RefRed/gui_handling/data_norm_spinboxes.py +++ b/RefRed/gui_handling/data_norm_spinboxes.py @@ -11,10 +11,9 @@ class SpinBox(object): - parent = None - def __init__(self, parent=None, is_data=True, entry_type: str = 'peak', value_min=-1, value_max=-1, flag=True): + def __init__(self, parent=None, is_data=True, entry_type: str = "peak", value_min=-1, value_max=-1, flag=True): self.parent = parent big_table_data: TableData = parent.big_table_data gui_utility = GuiUtility(parent=self.parent) @@ -30,7 +29,6 @@ def __init__(self, parent=None, is_data=True, entry_type: str = 'peak', value_mi row=active_row_index, is_data=is_data ) for row_index in all_rows: - if is_data: data = big_table_data.reflectometry_data(row_index) else: @@ -51,13 +49,13 @@ def __init__(self, parent=None, is_data=True, entry_type: str = 'peak', value_mi is_plot_yi = True is_plot_it = False is_plot_ix = False - if entry_type == 'peak': + if entry_type == "peak": data.peak = [val_min, val_max] - elif entry_type == 'back': + elif entry_type == "back": data.back = [val_min, val_max] - elif entry_type == 'back2': + elif entry_type == "back2": data.back2 = [val_min, val_max] - elif entry_type == 'low_res': + elif entry_type == "low_res": is_plot_yt = False is_plot_yi = False is_plot_ix = True @@ -86,28 +84,25 @@ def __init__(self, parent=None, is_data=True, entry_type: str = 'peak', value_mi class DataSpinbox(object): - def __init__(self, parent=None, entry_type='peak', value_min=-1, value_max=-1, flag=True): - SpinBox( - parent=parent, is_data=True, entry_type=entry_type, value_min=value_min, value_max=value_max, flag=flag - ) + def __init__(self, parent=None, entry_type="peak", value_min=-1, value_max=-1, flag=True): + SpinBox(parent=parent, is_data=True, entry_type=entry_type, value_min=value_min, value_max=value_max, flag=flag) class NormSpinbox(object): - def __init__(self, parent=None, entry_type='peak', value_min=-1, value_max=-1, flag=True): + def __init__(self, parent=None, entry_type="peak", value_min=-1, value_max=-1, flag=True): SpinBox( parent=parent, is_data=False, entry_type=entry_type, value_min=value_min, value_max=value_max, flag=flag ) class DataPeakSpinbox(object): - parent = None def __init__(self, parent=None): self.parent = parent peak1 = self.parent.ui.peakFromValue.value() peak2 = self.parent.ui.peakToValue.value() - DataSpinbox(parent=parent, entry_type='peak', value_min=peak1, value_max=peak2) + DataSpinbox(parent=parent, entry_type="peak", value_min=peak1, value_max=peak2) class DataBackSpinbox(object): @@ -124,10 +119,10 @@ class DataBackSpinbox(object): parent = None - def __init__(self, parent: QWidget, entry_type: str = 'back'): - if entry_type == 'back': + def __init__(self, parent: QWidget, entry_type: str = "back"): + if entry_type == "back": back1, back2 = parent.ui.backFromValue.value(), parent.ui.backToValue.value() - elif entry_type == 'back2': + elif entry_type == "back2": back1, back2 = parent.ui.back2FromValue.value(), parent.ui.back2ToValue.value() else: raise ValueError("Valid `entry_type` options are 'back', 'back2'") @@ -135,14 +130,13 @@ def __init__(self, parent: QWidget, entry_type: str = 'back'): class NormPeakSpinbox(object): - Parent = None def __init__(self, parent=None): self.parent = parent peak1 = self.parent.ui.normPeakFromValue.value() peak2 = self.parent.ui.normPeakToValue.value() - NormSpinbox(parent=parent, entry_type='peak', value_min=peak1, value_max=peak2) + NormSpinbox(parent=parent, entry_type="peak", value_min=peak1, value_max=peak2) class NormBackSpinbox(object): @@ -160,9 +154,9 @@ class NormBackSpinbox(object): parent = None def __init__(self, parent: QWidget, entry_type: str = "back"): - if entry_type == 'back': + if entry_type == "back": back1, back2 = parent.ui.normBackFromValue.value(), parent.ui.normBackToValue.value() - elif entry_type == 'back2': + elif entry_type == "back2": back1, back2 = parent.ui.normBack2FromValue.value(), parent.ui.normBack2ToValue.value() else: raise ValueError(f"entry_type '{entry_type}' is not valid. Valid options are 'back', 'back2'") @@ -170,7 +164,6 @@ def __init__(self, parent: QWidget, entry_type: str = "back"): class DataLowResSpinbox(object): - parent = None def __init__(self, parent=None): @@ -178,11 +171,10 @@ def __init__(self, parent=None): lowres1 = self.parent.ui.dataLowResFromValue.value() lowres2 = self.parent.ui.dataLowResToValue.value() flag = self.parent.ui.dataLowResFlag.isChecked() - DataSpinbox(parent=parent, entry_type='low_res', value_min=lowres1, value_max=lowres2, flag=flag) + DataSpinbox(parent=parent, entry_type="low_res", value_min=lowres1, value_max=lowres2, flag=flag) class NormLowResSpinbox(object): - parent = None def __init__(self, parent=None): @@ -190,4 +182,4 @@ def __init__(self, parent=None): lowres1 = self.parent.ui.normLowResFromValue.value() lowres2 = self.parent.ui.normLowResToValue.value() flag = self.parent.ui.normLowResFlag.isChecked() - NormSpinbox(parent=parent, entry_type='low_res', value_min=lowres1, value_max=lowres2, flag=flag) + NormSpinbox(parent=parent, entry_type="low_res", value_min=lowres1, value_max=lowres2, flag=flag) diff --git a/RefRed/gui_handling/fill_stitching_table.py b/RefRed/gui_handling/fill_stitching_table.py index bf6f7786..2c565840 100644 --- a/RefRed/gui_handling/fill_stitching_table.py +++ b/RefRed/gui_handling/fill_stitching_table.py @@ -3,8 +3,7 @@ from typing import Optional # third party imports -from qtpy import QtGui, QtCore -from qtpy import QtWidgets +from qtpy import QtCore, QtGui, QtWidgets # application imports from RefRed.gui_handling.gui_utility import GuiUtility @@ -33,9 +32,9 @@ def fillRow(self, row_index=0): self.fillTableRunNumber() - if stitching_type == 'absolute': + if stitching_type == "absolute": self.fillTableForAbsoluteNormalization() - elif stitching_type == 'auto': + elif stitching_type == "auto": self.fillTableForAutoStitching() else: self.fillTableForManualStitching() diff --git a/RefRed/gui_handling/first_angle_range_gui_handler.py b/RefRed/gui_handling/first_angle_range_gui_handler.py index 6ea6a6d6..f7244fe4 100644 --- a/RefRed/gui_handling/first_angle_range_gui_handler.py +++ b/RefRed/gui_handling/first_angle_range_gui_handler.py @@ -4,11 +4,11 @@ def __init__(self, parent=None): class FirstAngleRangeGuiHandler(ParentGuiHandler): - ''' + """ This class allows to enable or not the First Angle widgets according to status of SF or first_angle buttons in the stitching tab - ''' + """ def __init__(self, parent=None): super(FirstAngleRangeGuiHandler, self).__init__(parent=parent) @@ -27,7 +27,6 @@ def is_sf_button_clicked(self): class NormalizationOrStitchingButtonStatus(ParentGuiHandler): - is_absolute_normalization = True is_auto_stitching = False is_manual_stitching = False @@ -74,11 +73,11 @@ def resetAllWidgets(self): class NormalizationOrStitchingGuiHandler(NormalizationOrStitchingButtonStatus): - ''' + """ Various widgets have to be enabled or not according to status of the 3 main buttons: Absolute_Normalization, Auto._Stitching and Manual_Stitching - ''' + """ def __init__(self, parent=None): super(NormalizationOrStitchingGuiHandler, self).__init__(parent=parent) diff --git a/RefRed/gui_handling/gui_utility.py b/RefRed/gui_handling/gui_utility.py index 3de64db2..7ccc0ac8 100644 --- a/RefRed/gui_handling/gui_utility.py +++ b/RefRed/gui_handling/gui_utility.py @@ -1,6 +1,5 @@ # standard imports -from typing import List -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, List # third party imports from qtpy import QtWidgets @@ -16,7 +15,6 @@ class GuiUtility(object): - NULL_ACTIVE_ROW = -1 # fake row index when no active row found in the reduction table def __init__(self, parent: "MainGui"): @@ -24,29 +22,29 @@ def __init__(self, parent: "MainGui"): def get_ipts(self, row=-1): if row == -1: - return 'N/A' + return "N/A" _data0 = self.parent.big_table_data.reflectometry_data(row) if _data0 is None: - return 'N/A' + return "N/A" return _data0.ipts def init_widgets_value(self): _gui_metadata = self.parent.gui_metadata # event tof bins - _tof_bin = int(_gui_metadata['tof_bin']) + _tof_bin = int(_gui_metadata["tof_bin"]) self.parent.ui.eventTofBins.setValue(_tof_bin) # q bin - _q_bin = _gui_metadata['q_min'] + _q_bin = _gui_metadata["q_min"] self.parent.ui.qStep.setText(str(_q_bin)) # angle offset - _angle_offset = "%.3f" % _gui_metadata['angle_offset'] + _angle_offset = "%.3f" % _gui_metadata["angle_offset"] self.parent.ui.angleOffsetValue.setText(_angle_offset) # angle offset error - _angle_offset_error = "%.3f" % _gui_metadata['angle_offset_error'] + _angle_offset_error = "%.3f" % _gui_metadata["angle_offset_error"] self.parent.ui.angleOffsetError.setText(_angle_offset_error) def get_row_with_highest_q(self): @@ -188,7 +186,7 @@ def new_config_file_loaded(self, config_file_name=None): def gui_has_been_modified(self): dialog_title = WINDOW_TITLE + self.parent.current_loaded_file - new_dialog_title = dialog_title + '*' + new_dialog_title = dialog_title + "*" self.parent.setWindowTitle(new_dialog_title) def gui_not_modified(self): @@ -198,9 +196,9 @@ def gui_not_modified(self): def get_reduced_yaxis_type(self): if self.parent.ui.RvsQ.isChecked(): - return 'RvsQ' + return "RvsQ" else: - return 'RQ4vsQ' + return "RQ4vsQ" def getStitchingType(self): """ @@ -208,8 +206,8 @@ def getStitchingType(self): can be either 'auto', 'manual' or 'absolute' """ if self.parent.ui.absolute_normalization_button.isChecked(): - return 'absolute' + return "absolute" elif self.parent.ui.auto_stitching_button.isChecked(): - return 'auto' + return "auto" else: - return 'manual' + return "manual" diff --git a/RefRed/gui_handling/progressbar_handler.py b/RefRed/gui_handling/progressbar_handler.py index 1fb079ba..2f72cfd9 100644 --- a/RefRed/gui_handling/progressbar_handler.py +++ b/RefRed/gui_handling/progressbar_handler.py @@ -1,17 +1,17 @@ +import time + from qtpy import QtCore from qtpy.QtWidgets import QApplication -import time class ProgressBarHandler(object): - nbr_reduction = 0 current_step = 0 def __init__(self, parent=None): self.parent = parent - def setup(self, nbr_reduction=0, label='Reduction Process'): + def setup(self, nbr_reduction=0, label="Reduction Process"): self.nbr_reduction = nbr_reduction self.parent.ui.reductionProcessProgressBar.setMinimum(0) diff --git a/RefRed/gui_handling/refred_interface_handler.py b/RefRed/gui_handling/refred_interface_handler.py index 876011c8..f23a0788 100644 --- a/RefRed/gui_handling/refred_interface_handler.py +++ b/RefRed/gui_handling/refred_interface_handler.py @@ -2,7 +2,6 @@ class RefRedInterfaceHandler(object): - from_row = -1 to_row = -1 @@ -22,12 +21,12 @@ def __clear_stitching_table(self): nbr_col = self.parent.ui.dataStitchingTable.columnCount() for _row in range(nbr_row): for _col in range(0, nbr_col): - if not (self.parent.ui.dataStitchingTable.item(_row, _col) is None): + if self.parent.ui.dataStitchingTable.item(_row, _col) is not None: self.parent.ui.dataStitchingTable.item(_row, _col).setText("") def __clear_scaling_factor(self): self.parent.ui.scalingFactorFile.setText("") - _list = ['Select Incident Medium ...'] + _list = ["Select Incident Medium ..."] self.parent.ui.selectIncidentMediumList.clear() self.parent.ui.selectIncidentMediumList.addItems(_list) - self.parent.full_scaling_factor_file_name = '' + self.parent.full_scaling_factor_file_name = "" diff --git a/RefRed/gui_handling/scaling_factor_widgets_handler.py b/RefRed/gui_handling/scaling_factor_widgets_handler.py index 6883e69e..9d238137 100644 --- a/RefRed/gui_handling/scaling_factor_widgets_handler.py +++ b/RefRed/gui_handling/scaling_factor_widgets_handler.py @@ -1,10 +1,10 @@ import os + from numpy import shape from qtpy.QtWidgets import QFileDialog class ScalingFactorWidgetsHandler(object): - parent = None def __init__(self, parent=None): diff --git a/RefRed/gui_handling/update_plot_widget_status.py b/RefRed/gui_handling/update_plot_widget_status.py index a9e3a886..db85e354 100644 --- a/RefRed/gui_handling/update_plot_widget_status.py +++ b/RefRed/gui_handling/update_plot_widget_status.py @@ -1,6 +1,6 @@ # RefRed imports -from RefRed.plot.background_settings import backgrounds_settings from RefRed.gui_handling.gui_utility import GuiUtility +from RefRed.plot.background_settings import backgrounds_settings class UpdatePlotWidgetStatus(object): @@ -51,9 +51,7 @@ def data_tab_widgets(self, status=False): parent.ui.backToValue.setEnabled(status_custom) parent.ui.backFromValue.setEnabled(status_custom) status_custom = ( - status - and backgrounds_settings["data"].subtract_background - and backgrounds_settings["data"].two_backgrounds + status and backgrounds_settings["data"].subtract_background and backgrounds_settings["data"].two_backgrounds ) parent.ui.back2ToValue.setEnabled(status_custom) parent.ui.back2FromValue.setEnabled(status_custom) @@ -89,9 +87,7 @@ def norm_tab_widgets(self, status=False): parent.ui.normBackToValue.setEnabled(status_custom) parent.ui.normBackFromValue.setEnabled(status_custom) status_custom = ( - status - and backgrounds_settings["norm"].subtract_background - and backgrounds_settings["norm"].two_backgrounds + status and backgrounds_settings["norm"].subtract_background and backgrounds_settings["norm"].two_backgrounds ) parent.ui.normBack2ToValue.setEnabled(status_custom) parent.ui.normBack2FromValue.setEnabled(status_custom) diff --git a/RefRed/initialization/gui.py b/RefRed/initialization/gui.py index 236f8a00..887e6b9b 100644 --- a/RefRed/initialization/gui.py +++ b/RefRed/initialization/gui.py @@ -1,22 +1,21 @@ -from qtpy import QtGui, QtCore, QtWidgets - import socket +from qtpy import QtCore, QtGui, QtWidgets + from RefRed import WINDOW_TITLE -from RefRed.interfaces.mytablewidget import ReductionTableColumnIndex -from RefRed.plot.all_plot_axis import AllPlotAxis from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.update_plot_widget_status import UpdatePlotWidgetStatus +from RefRed.interfaces.mytablewidget import ReductionTableColumnIndex +from RefRed.plot.all_plot_axis import AllPlotAxis class Gui(object): - parent = None vertical_header = [ "Plotted", "Data Run #", "Norm. Run #", - "2\u03b8 (\u00B0)", + "2\u03b8 (\u00b0)", "\u03bbmin (\u00c5)", "\u03bbmax (\u00c5)", "Qmin (1/\u00c5)", @@ -29,7 +28,6 @@ class Gui(object): gui_size_coeff = 2.0 / 3.0 def __init__(self, parent): - self.parent = parent self.set_gui_title() self.set_gui_size() diff --git a/RefRed/interfaces/deadtime_entry.py b/RefRed/interfaces/deadtime_entry.py index 64087062..e7593641 100644 --- a/RefRed/interfaces/deadtime_entry.py +++ b/RefRed/interfaces/deadtime_entry.py @@ -1,9 +1,9 @@ # third party imports -from qtpy.QtWidgets import QGroupBox, QHBoxLayout, QCheckBox, QPushButton +from qtpy.QtWidgets import QCheckBox, QGroupBox, QHBoxLayout, QPushButton class DeadTimeEntryPoint(QGroupBox): - def __init__(self, title='Dead Time Correction'): + def __init__(self, title="Dead Time Correction"): super().__init__(title) self.initUI() @@ -22,9 +22,9 @@ def initUI(self): "}" ) - self.applyCheckBox = QCheckBox('Apply', self) + self.applyCheckBox = QCheckBox("Apply", self) self.applyCheckBox.stateChanged.connect(self.toggleSettingsButton) - self.settingsButton = QPushButton('Settings', self) + self.settingsButton = QPushButton("Settings", self) self.settingsButton.setEnabled(self.applyCheckBox.isChecked()) # enabled if we use the correction # Create a horizontal layout for the checkbox and settings button diff --git a/RefRed/interfaces/deadtime_settings.py b/RefRed/interfaces/deadtime_settings.py index 3be8413d..77ed77e2 100644 --- a/RefRed/interfaces/deadtime_settings.py +++ b/RefRed/interfaces/deadtime_settings.py @@ -1,7 +1,8 @@ # third-party imports -from qtpy.QtWidgets import QDialog, QWidget -from xml.dom.minidom import Document, Element from typing import Any, Callable, Dict +from xml.dom.minidom import Document, Element + +from qtpy.QtWidgets import QDialog, QWidget # RefRed imports from RefRed.configuration.global_settings import GlobalSettings @@ -138,9 +139,9 @@ def get_state_from_form(self) -> dict: Dictionary whose keys must match fields of class `DeadTimeSettingsModel` """ return { - 'paralyzable': self.ui.use_paralyzable.isChecked(), - 'dead_time': self.ui.dead_time_value.value(), - 'tof_step': self.ui.dead_time_tof.value(), + "paralyzable": self.ui.use_paralyzable.isChecked(), + "dead_time": self.ui.dead_time_value.value(), + "tof_step": self.ui.dead_time_tof.value(), } def accept(self): diff --git a/RefRed/interfaces/mplwidgets.py b/RefRed/interfaces/mplwidgets.py index 31bd7898..79f54ae8 100644 --- a/RefRed/interfaces/mplwidgets.py +++ b/RefRed/interfaces/mplwidgets.py @@ -1,11 +1,13 @@ #!/usr/bin/env python import os import tempfile -from qtpy import QtCore, QtGui, QtWidgets + import matplotlib.colors from matplotlib.colors import LogNorm, Normalize -from RefRed.config import plotting from matplotlib.figure import Figure +from qtpy import QtCore, QtGui, QtWidgets + +from RefRed.config import plotting # set the default backend to be compatible with Qt in case someone uses pylab from IPython console @@ -47,11 +49,11 @@ def set_matplotlib_backend(): BACKEND = set_matplotlib_backend() if BACKEND == "Qt4Agg": - from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4 import NavigationToolbar2QT + from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas elif BACKEND == "Qt5Agg": - from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5 import NavigationToolbar2QT + from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.cbook import Stack # path where all of the icons are @@ -179,7 +181,6 @@ def setup_toolbar(self): self.adj_window = None def activate_widget(self, widget_name, activateIt): - if widget_name == "pan": if activateIt: self.isPanActivated = True @@ -282,7 +283,6 @@ def save_figure(self, *args): def toggle_ylog(self, *args): ax = self.canvas.ax if len(ax.images) == 0 and all([c.__class__.__name__ != "QuadMesh" for c in ax.collections]): - # logstate=ax.get_xscale() if self.ylog: ax.set_yscale("linear") @@ -306,7 +306,6 @@ def toggle_ylog(self, *args): def toggle_xlog(self, *args): ax = self.canvas.ax if len(ax.images) == 0 and all([c.__class__.__name__ != "QuadMesh" for c in ax.collections]): - if self.xlog: ax.set_xscale("linear") else: @@ -328,7 +327,6 @@ def toggle_xlog(self, *args): class MplCanvas(FigureCanvas): - trigger_click = QtCore.Signal(bool, bool, int, int) trigger_figure_left = QtCore.Signal() diff --git a/RefRed/interfaces/mytablewidget.py b/RefRed/interfaces/mytablewidget.py index c050406a..e0aca26c 100644 --- a/RefRed/interfaces/mytablewidget.py +++ b/RefRed/interfaces/mytablewidget.py @@ -10,7 +10,6 @@ class MyTableWidget(QtWidgets.QTableWidget): - parent = None ui = None diff --git a/RefRed/lconfigdataset.py b/RefRed/lconfigdataset.py index b5193399..50b926e3 100644 --- a/RefRed/lconfigdataset.py +++ b/RefRed/lconfigdataset.py @@ -13,8 +13,8 @@ class LConfigDataset(object): data_runs_compatible = True data_wks = None - data_sets = [''] - data_full_file_name = [''] + data_sets = [""] + data_full_file_name = [""] data_peak: List[int] = [0, 0] # lower and upper boundaries for the peak data_back: List[int] = [0, 0] # lower and upper boundaries for the first background data_back2: List[int] = [0, 0] # lower and upper boundaries for the second background @@ -24,14 +24,14 @@ class LConfigDataset(object): data_low_res_flag = True data_lambda_requested = -1 - tof_range = ['0', '0'] - tof_units = 'ms' + tof_range = ["0", "0"] + tof_units = "ms" tof_auto_flag = True norm_runs_compatible = True norm_wks = None - norm_sets = [''] - norm_full_file_name = [''] + norm_sets = [""] + norm_full_file_name = [""] norm_flag = True norm_peak = [0, 0] norm_back = [0, 0] @@ -43,8 +43,8 @@ class LConfigDataset(object): norm_low_res_flag = True norm_lambda_requested = -1 - q_range = ['0', '0'] - lambda_range = ['0', '0'] + q_range = ["0", "0"] + lambda_range = ["0", "0"] const_q = False reduce_q_axis = [] diff --git a/RefRed/load_reduced_data_set/load_reduced_data_set_handler.py b/RefRed/load_reduced_data_set/load_reduced_data_set_handler.py index 50aca412..efa4957e 100644 --- a/RefRed/load_reduced_data_set/load_reduced_data_set_handler.py +++ b/RefRed/load_reduced_data_set/load_reduced_data_set_handler.py @@ -1,11 +1,12 @@ -from qtpy import QtWidgets import os + +from qtpy import QtWidgets + from RefRed.export.reduced_ascii_loader import ReducedAsciiLoader from RefRed.load_reduced_data_set.stitching_ascii_widget import StitchingAsciiWidget class LoadReducedDataSetHandler(object): - last_row_loaded = -1 def __init__(self, parent=None): diff --git a/RefRed/load_reduced_data_set/reduced_ascii_data_right_click.py b/RefRed/load_reduced_data_set/reduced_ascii_data_right_click.py index 66730596..f6aea308 100644 --- a/RefRed/load_reduced_data_set/reduced_ascii_data_right_click.py +++ b/RefRed/load_reduced_data_set/reduced_ascii_data_right_click.py @@ -1,6 +1,7 @@ from qtpy import QtGui, QtWidgets -from RefRed.load_reduced_data_set.reduced_ascii_table_handler import ReducedAsciiTableHandler + from RefRed.load_reduced_data_set.load_reduced_data_set_handler import LoadReducedDataSetHandler +from RefRed.load_reduced_data_set.reduced_ascii_table_handler import ReducedAsciiTableHandler class ReducedAsciiDataRightClick(object): diff --git a/RefRed/load_reduced_data_set/reduced_ascii_table_handler.py b/RefRed/load_reduced_data_set/reduced_ascii_table_handler.py index 2cece72e..e6e16207 100644 --- a/RefRed/load_reduced_data_set/reduced_ascii_table_handler.py +++ b/RefRed/load_reduced_data_set/reduced_ascii_table_handler.py @@ -2,7 +2,6 @@ class ReducedAsciiTableHandler(object): - list_filename_to_remove = [] total_number_of_rows_in_table = -1 diff --git a/RefRed/load_reduced_data_set/stitching_ascii_widget.py b/RefRed/load_reduced_data_set/stitching_ascii_widget.py index 5aeb346e..289dcad9 100644 --- a/RefRed/load_reduced_data_set/stitching_ascii_widget.py +++ b/RefRed/load_reduced_data_set/stitching_ascii_widget.py @@ -1,29 +1,26 @@ +import numpy as np from qtpy import QtWidgets from qtpy.QtCore import Qt # type: ignore -import numpy as np from RefRed.gui_handling.gui_utility import GuiUtility class StitchingAsciiWidget(object): - loaded_ascii_array = [] tableUi = None stitchingPlot = None parent = None isylog = True isxlog = True - yaxistype = 'RvsQ' + yaxistype = "RvsQ" row_of_this_file = 0 def __init__(self, parent=None): - self.parent = parent self.tableUi = parent.ui.reducedAsciiDataSetTable self.stitchingPlot = parent.ui.data_stitching_plot def add_data(self, newloaded_ascii): - row_of_this_file = self.get_row_of_this_file(newloaded_ascii) if row_of_this_file == -1: # add row @@ -58,7 +55,6 @@ def remove_all_data(self): self.loaded_ascii_array = [] def get_row_of_this_file(self, loaded_ascii): - newFilename = loaded_ascii.ascii_file_name nbrRow = len(self.loaded_ascii_array) @@ -71,10 +67,8 @@ def get_row_of_this_file(self, loaded_ascii): return -1 def update_status(self): - nbrRow = len(self.loaded_ascii_array) for i in range(nbrRow): - _data_object = self.loaded_ascii_array[i] _item_state = self.parent.ui.reducedAsciiDataSetTable.cellWidget(i, 1).checkState() @@ -100,20 +94,18 @@ def update_display(self): self.stitchingPlot.errorbar(_q_axis, _y_axis_red, yerr=_e_axis_red) def format_data_from_ymode_selected(self, q_axis, y_axis, e_axis): - data_type = self.get_selected_reduced_output() [final_y_axis, final_e_axis] = self.get_formated_output(data_type, q_axis, y_axis, e_axis) return [final_y_axis, final_e_axis] def get_formated_output(self, data_type, _q_axis, _y_axis, _e_axis): - try: # R vs Q selected - if data_type == 'RvsQ': + if data_type == "RvsQ": return [_y_axis, _e_axis] # RQ4 vs Q selected - if data_type == 'RQ4vsQ': + if data_type == "RQ4vsQ": _q_axis_4 = _q_axis**4 _final_y_axis = _y_axis * _q_axis_4 _final_e_axis = _e_axis * _q_axis_4 diff --git a/RefRed/low_res_finder_algorithms/low_res_finder.py b/RefRed/low_res_finder_algorithms/low_res_finder.py index b3a33191..539b2ef7 100644 --- a/RefRed/low_res_finder_algorithms/low_res_finder.py +++ b/RefRed/low_res_finder_algorithms/low_res_finder.py @@ -1,9 +1,9 @@ -import numpy as np import math +import numpy as np + class LowResFinder(object): - low_res = [-1, -1] xdata_firstderi = [] ydata_firstderi = [] @@ -132,5 +132,5 @@ def get_low_res(self): if __name__ == "__main__": from RefRed.file_loading_utility import loadCsvFile - [xdata, ydata, edata] = loadCsvFile('easy_data_set.csv') + [xdata, ydata, edata] = loadCsvFile("easy_data_set.csv") peakfinder1 = LowResFinder(xdata, ydata, edata) diff --git a/RefRed/main.py b/RefRed/main.py index f64f4065..352c87c7 100644 --- a/RefRed/main.py +++ b/RefRed/main.py @@ -1,27 +1,37 @@ # import sys -from qtpy import QtCore, QtWidgets import logging -import numpy as np import os +import numpy as np +from qtpy import QtCore, QtWidgets + +from RefRed.about_dialog import AboutDialog from RefRed.autopopulatemaintable.reductiontable_auto_fill import ReductionTableAutoFill +from RefRed.browsing_runs import BrowsingRuns +from RefRed.config.mantid_config import MantidConfig from RefRed.configuration.loading_configuration import LoadingConfiguration from RefRed.configuration.saving_configuration import SavingConfiguration from RefRed.configuration.user_configuration_handler import RetrieveUserConfiguration, SaveUserConfiguration +from RefRed.decorators import config_file_has_been_modified, config_file_modification_reset from RefRed.export.export_plot_ascii import ExportPlotAscii -from RefRed.gui_handling.data_norm_spinboxes import DataPeakSpinbox, NormPeakSpinbox -from RefRed.gui_handling.data_norm_spinboxes import DataBackSpinbox, NormBackSpinbox -from RefRed.gui_handling.data_norm_spinboxes import DataLowResSpinbox, NormLowResSpinbox -from RefRed.gui_handling.scaling_factor_widgets_handler import ScalingFactorWidgetsHandler from RefRed.gui_handling.auto_tof_range_radio_button_handler import AutoTofRangeRadioButtonHandler -from RefRed.gui_handling.gui_utility import GuiUtility -from RefRed.gui_handling.stitching_yscale_options_radio_button_handler import StitchingYScaleOptionsRadioButtonHandler +from RefRed.gui_handling.data_norm_spinboxes import ( + DataBackSpinbox, + DataLowResSpinbox, + DataPeakSpinbox, + NormBackSpinbox, + NormLowResSpinbox, + NormPeakSpinbox, +) from RefRed.gui_handling.first_angle_range_gui_handler import ( - NormalizationOrStitchingButtonStatus, FirstAngleRangeGuiHandler, + NormalizationOrStitchingButtonStatus, ) -from RefRed.gui_handling.refred_interface_handler import RefRedInterfaceHandler +from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.observer import SpinBoxObserver +from RefRed.gui_handling.refred_interface_handler import RefRedInterfaceHandler +from RefRed.gui_handling.scaling_factor_widgets_handler import ScalingFactorWidgetsHandler +from RefRed.gui_handling.stitching_yscale_options_radio_button_handler import StitchingYScaleOptionsRadioButtonHandler from RefRed.initialization.gui import Gui as InitializeGui from RefRed.initialization.gui_connections import GuiConnections as MakeGuiConnections from RefRed.interfaces import load_ui @@ -29,44 +39,40 @@ from RefRed.load_reduced_data_set.load_reduced_data_set_handler import LoadReducedDataSetHandler from RefRed.load_reduced_data_set.reduced_ascii_data_right_click import ReducedAsciiDataRightClick from RefRed.metadata.metadata_finder import MetadataFinder +from RefRed.plot.background_settings import BackgroundSettingsView, backgrounds_settings from RefRed.plot.display_plots import DisplayPlots -from RefRed.plot.single_click_plot import SingleClickPlot from RefRed.plot.home_plot_button_clicked import HomePlotButtonClicked -from RefRed.plot.mouse_leave_plot import MouseLeavePlot from RefRed.plot.log_plot_toggle import LogPlotToggle -from RefRed.plot.background_settings import backgrounds_settings, BackgroundSettingsView +from RefRed.plot.mouse_leave_plot import MouseLeavePlot +from RefRed.plot.single_click_plot import SingleClickPlot from RefRed.preview_config.preview_config import PreviewConfig from RefRed.reduction.live_reduction_handler import LiveReductionHandler from RefRed.reduction.reduced_data_handler import ReducedDataHandler from RefRed.reduction_table_handling.const_q_checkbox_handler import ConstQCheckBoxHandler from RefRed.reduction_table_handling.reduction_table_check_box import ReductionTableCheckBox -from RefRed.reduction_table_handling.update_reduction_table import UpdateReductionTable -from RefRed.reduction_table_handling.reduction_table_right_click import ReductionTableRightClick from RefRed.reduction_table_handling.reduction_table_handler import ReductionTableHandler +from RefRed.reduction_table_handling.reduction_table_right_click import ReductionTableRightClick +from RefRed.reduction_table_handling.update_reduction_table import UpdateReductionTable from RefRed.settings.initialize_settings import InitializeSettings from RefRed.settings.settings_editor import SettingsEditor from RefRed.sf_calculator.sf_calculator import SFCalculator from RefRed.sf_preview.sf_preview import SFPreview -from RefRed.decorators import config_file_has_been_modified, config_file_modification_reset -from RefRed.about_dialog import AboutDialog -from RefRed.browsing_runs import BrowsingRuns -from RefRed.config.mantid_config import MantidConfig from RefRed.tabledata import TableData class MainGui(QtWidgets.QMainWindow): - '''Top class that handles the GUI''' + """Top class that handles the GUI""" file_loaded_signal = QtCore.Signal(int, bool, bool) # default location - path_ascii = '.' # ascii file such as scaling factor file + path_ascii = "." # ascii file such as scaling factor file - full_scaling_factor_file_name = '' + full_scaling_factor_file_name = "" home_dir = os.path.expanduser("~") - default_loaded_file = os.path.join(home_dir, 'tmp.xml') - current_loaded_file = os.path.join(home_dir, 'tmp.xml') - browsed_files = {'data': None, 'norm': None} + default_loaded_file = os.path.join(home_dir, "tmp.xml") + current_loaded_file = os.path.join(home_dir, "tmp.xml") + browsed_files = {"data": None, "norm": None} current_ipts = "" o_user_configuration = None # will record the various settings of the GUI defined by the user @@ -81,34 +87,34 @@ class MainGui(QtWidgets.QMainWindow): current_table_reduction_row_selected = -1 reduction_table_check_box_state = np.zeros((REDUCTIONTABLE_MAX_ROWCOUNT), dtype=bool) loading_nxs_thread = { - 'thread1': None, - 'thread2': None, - 'thread3': None, - 'thread4': None, - 'thread5': None, - 'thread6': None, - 'thread7': None, - 'thread8': None, - 'thread9': None, - 'thread10': None, - 'thread11': None, - 'thread12': None, - 'thread13': None, - 'thread14': None, - 'thread15': None, - 'thread16': None, - 'thread17': None, - 'thread18': None, - 'thread19': None, - 'thread20': None, - 'thread21': None, - 'thread22': None, - 'thread23': None, - 'thread24': None, - 'thread25': None, - 'thread26': None, - 'thread27': None, - 'thread28': None, + "thread1": None, + "thread2": None, + "thread3": None, + "thread4": None, + "thread5": None, + "thread6": None, + "thread7": None, + "thread8": None, + "thread9": None, + "thread10": None, + "thread11": None, + "thread12": None, + "thread13": None, + "thread14": None, + "thread15": None, + "thread16": None, + "thread17": None, + "thread18": None, + "thread19": None, + "thread20": None, + "thread21": None, + "thread22": None, + "thread23": None, + "thread24": None, + "thread25": None, + "thread26": None, + "thread27": None, + "thread28": None, } index_free_thread = 0 @@ -134,7 +140,7 @@ def __init__(self, argv=[], parent=None): RetrieveUserConfiguration(parent=self) self.file_loaded_signal.connect(self.file_loaded) - log_file = os.path.expanduser("~") + '/.refred.log' + log_file = os.path.expanduser("~") + "/.refred.log" logging.basicConfig(filename=log_file, level=logging.DEBUG) # backup the last value for each spinbox in this widget @@ -156,79 +162,79 @@ def __init__(self, argv=[], parent=None): # home button of plots def home_clicked_yi_plot(self): - HomePlotButtonClicked(parent=self, plot_type='yi') + HomePlotButtonClicked(parent=self, plot_type="yi") def home_clicked_yt_plot(self): - HomePlotButtonClicked(parent=self, plot_type='yt') + HomePlotButtonClicked(parent=self, plot_type="yt") def home_clicked_it_plot(self): - HomePlotButtonClicked(parent=self, plot_type='it') + HomePlotButtonClicked(parent=self, plot_type="it") def home_clicked_ix_plot(self): - HomePlotButtonClicked(parent=self, plot_type='ix') + HomePlotButtonClicked(parent=self, plot_type="ix") def home_clicked_data_stitching_plot(self): - HomePlotButtonClicked(parent=self, plot_type='stitching') + HomePlotButtonClicked(parent=self, plot_type="stitching") # leave figure def leave_figure_yi_plot(self): - MouseLeavePlot(parent=self, plot_type='yi') + MouseLeavePlot(parent=self, plot_type="yi") def leave_figure_yt_plot(self): - MouseLeavePlot(parent=self, plot_type='yt') + MouseLeavePlot(parent=self, plot_type="yt") def leave_figure_it_plot(self): - MouseLeavePlot(parent=self, plot_type='it') + MouseLeavePlot(parent=self, plot_type="it") def leave_figure_ix_plot(self): - MouseLeavePlot(parent=self, plot_type='ix') + MouseLeavePlot(parent=self, plot_type="ix") def leave_figure_data_stitching_plot(self): - MouseLeavePlot(parent=self, plot_type='stitching') + MouseLeavePlot(parent=self, plot_type="stitching") # single click def single_click_data_yi_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='data', plot_type='yi') + SingleClickPlot(self, data_type="data", plot_type="yi") def single_click_norm_yi_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='norm', plot_type='yi') + SingleClickPlot(self, data_type="norm", plot_type="yi") def single_click_norm_yt_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='norm', plot_type='yt') + SingleClickPlot(self, data_type="norm", plot_type="yt") def single_click_data_yt_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='data', plot_type='yt') + SingleClickPlot(self, data_type="data", plot_type="yt") def single_click_norm_it_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='norm', plot_type='it') + SingleClickPlot(self, data_type="norm", plot_type="it") def single_click_data_it_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='data', plot_type='it') + SingleClickPlot(self, data_type="data", plot_type="it") def single_click_norm_ix_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='norm', plot_type='ix') + SingleClickPlot(self, data_type="norm", plot_type="ix") def single_click_data_ix_plot(self, isPanOrZoomActivated): - SingleClickPlot(self, data_type='data', plot_type='ix') + SingleClickPlot(self, data_type="data", plot_type="ix") # toggle log def logy_toggle_yt_plot(self, checked): - LogPlotToggle(parent=self, status=checked, plot_type='yt', is_y_log=True) + LogPlotToggle(parent=self, status=checked, plot_type="yt", is_y_log=True) def logy_toggle_it_plot(self, checked): - LogPlotToggle(parent=self, status=checked, plot_type='it', is_y_log=True) + LogPlotToggle(parent=self, status=checked, plot_type="it", is_y_log=True) def logy_toggle_ix_plot(self, checked): - LogPlotToggle(parent=self, status=checked, plot_type='ix', is_y_log=True) + LogPlotToggle(parent=self, status=checked, plot_type="ix", is_y_log=True) def logx_toggle_yi_plot(self, checked): - LogPlotToggle(parent=self, status=checked, plot_type='yi', is_y_log=False) + LogPlotToggle(parent=self, status=checked, plot_type="yi", is_y_log=False) def logx_toggle_data_stitching(self, checked): - LogPlotToggle(parent=self, status=checked, plot_type='stitching', is_y_log=False) + LogPlotToggle(parent=self, status=checked, plot_type="stitching", is_y_log=False) def logy_toggle_data_stitching(self, checked): - LogPlotToggle(parent=self, status=checked, plot_type='stitching', is_y_log=True) + LogPlotToggle(parent=self, status=checked, plot_type="stitching", is_y_log=True) # display row checkbox def reduction_table_visibility_changed_test(self, state, row): @@ -469,27 +475,27 @@ def data_norm_sequence_event(self, *args, **kwargs): @config_file_has_been_modified def data_sequence_event(self, *args, **kwargs): str_data_input = self.ui.data_sequence_lineEdit.text() - ReductionTableAutoFill(parent=self, list_of_run_from_input=str_data_input, data_type_selected='data') - self.ui.data_sequence_lineEdit.setText('') + ReductionTableAutoFill(parent=self, list_of_run_from_input=str_data_input, data_type_selected="data") + self.ui.data_sequence_lineEdit.setText("") self.norm_sequence_event() @config_file_has_been_modified def data_browse_button(self, *args, **kwargs): - BrowsingRuns(parent=self, data_type='data') - ReductionTableAutoFill(parent=self, list_of_run_from_input='', data_type_selected='data') - self.ui.data_sequence_lineEdit.setText('') + BrowsingRuns(parent=self, data_type="data") + ReductionTableAutoFill(parent=self, list_of_run_from_input="", data_type_selected="data") + self.ui.data_sequence_lineEdit.setText("") @config_file_has_been_modified def norm_sequence_event(self, *args, **kwargs): str_norm_input = self.ui.norm_sequence_lineEdit.text() - ReductionTableAutoFill(parent=self, list_of_run_from_input=str_norm_input, data_type_selected='norm') - self.ui.norm_sequence_lineEdit.setText('') + ReductionTableAutoFill(parent=self, list_of_run_from_input=str_norm_input, data_type_selected="norm") + self.ui.norm_sequence_lineEdit.setText("") @config_file_has_been_modified def norm_browse_button(self, *args, **kwargs): - BrowsingRuns(parent=self, data_type='norm') - ReductionTableAutoFill(parent=self, list_of_run_from_input='', data_type_selected='norm') - self.ui.norm_sequence_lineEdit.setText('') + BrowsingRuns(parent=self, data_type="norm") + ReductionTableAutoFill(parent=self, list_of_run_from_input="", data_type_selected="norm") + self.ui.norm_sequence_lineEdit.setText("") # Menu buttons def action_new(self): @@ -548,23 +554,23 @@ def data_stitching_table_manual_spin_box(self): self.stitching_sf_radio_button() def export_stitching_data(self): - o_export_plot = ExportPlotAscii(parent=self, data_type='stitched') + o_export_plot = ExportPlotAscii(parent=self, data_type="stitched") o_export_plot.export() def export_it(self): - o_export_plot = ExportPlotAscii(parent=self, data_type='it') + o_export_plot = ExportPlotAscii(parent=self, data_type="it") o_export_plot.export() def export_yi(self): - o_export_plot = ExportPlotAscii(parent=self, data_type='yi') + o_export_plot = ExportPlotAscii(parent=self, data_type="yi") o_export_plot.export() def export_ix(self): - o_export_plot = ExportPlotAscii(parent=self, data_type='ix') + o_export_plot = ExportPlotAscii(parent=self, data_type="ix") o_export_plot.export() def export_yt(self): - o_export_plot = ExportPlotAscii(parent=self, data_type='yt') + o_export_plot = ExportPlotAscii(parent=self, data_type="yt") o_export_plot.export() @config_file_has_been_modified @@ -589,13 +595,13 @@ def stitching_sf_radio_button(self): o_reduced_plot.plot() def stitching_yscale_options_radio_button_1(self): - '''R vs Q''' + """R vs Q""" o_button_handler = StitchingYScaleOptionsRadioButtonHandler(parent=self) o_button_handler.set_index_button_clicked(index=0) self.stitching_sf_radio_button() def stitching_yscale_options_radio_button_2(self): - '''RQ^4 vs Q''' + """RQ^4 vs Q""" o_button_handler = StitchingYScaleOptionsRadioButtonHandler(parent=self) o_button_handler.set_index_button_clicked(index=1) self.stitching_sf_radio_button() diff --git a/RefRed/metadata/metadata_finder.py b/RefRed/metadata/metadata_finder.py index 8192f99e..8fa4cab2 100644 --- a/RefRed/metadata/metadata_finder.py +++ b/RefRed/metadata/metadata_finder.py @@ -1,29 +1,29 @@ +import os +import time from pathlib import Path -from qtpy.QtGui import QPalette, QPixmap, QIcon + +import numpy as np +from mantid.simpleapi import LoadEventNexus +from qtpy.QtCore import QSettings, QSize, Qt # type: ignore +from qtpy.QtGui import QIcon, QPalette, QPixmap from qtpy.QtWidgets import ( - QMainWindow, QCheckBox, QFileDialog, - QTableWidgetItem, + QMainWindow, QMessageBox, QPushButton, + QTableWidgetItem, ) -from qtpy.QtCore import Qt, QSize, QSettings # type: ignore -from mantid.simpleapi import LoadEventNexus -import os -import time -import numpy as np -from RefRed import ORGANIZATION, APPNAME -from RefRed.interfaces import load_ui +import RefRed.nexus_utilities +import RefRed.utilities +from RefRed import APPNAME, ORGANIZATION from RefRed.calculations.run_sequence_breaker import RunSequenceBreaker from RefRed.decorators import waiting_effects -import RefRed.utilities -import RefRed.nexus_utilities +from RefRed.interfaces import load_ui class MetadataFinder(QMainWindow): - _open_instances = [] parent = None @@ -177,7 +177,7 @@ def populateconfigureTable(self): _index = 0 for _key in list_keys: _name = _key - if (search_string.strip() != "") and (not (search_string in _name.lower())): + if (search_string.strip() != "") and (search_string not in _name.lower()): continue self.ui.configureTable.insertRow(_index) @@ -243,7 +243,7 @@ def loadNxs(self): _list_runs = oListRuns.getFinalList() if len(_list_runs) > self.WARNING_NBR_FILES: msgBox = QMessageBox() - _str = "Program is about to load {:%d} files. Do you want to continue ?".format(len(_list_runs)) + _str = f"Program is about to load {len(_list_runs):%d} files. Do you want to continue ?" msgBox.setText(_str) msgBox.addButton(QPushButton("NO"), QMessageBox.NoRole) msgBox.addButton(QPushButton("YES"), QMessageBox.YesRole) @@ -280,7 +280,7 @@ def loadNxs(self): return self.list_filename.append(_filename) randomString = RefRed.utilities.generate_random_workspace_name() - print(f"About to load \"{_filename}\"") + print(f'About to load "{_filename}"') _nxs = LoadEventNexus(Filename=_filename, OutputWorkspace=randomString, MetaDataOnly=True) self.list_nxs.append(_nxs) diff --git a/RefRed/nexus_utilities.py b/RefRed/nexus_utilities.py index 0fd91247..95cb5f75 100644 --- a/RefRed/nexus_utilities.py +++ b/RefRed/nexus_utilities.py @@ -1,7 +1,8 @@ import sys -from mantid.kernel import logger -from mantid.api import FileFinder + import h5py +from mantid.api import FileFinder +from mantid.kernel import logger def findNeXusFullPath(run_number): @@ -9,14 +10,14 @@ def findNeXusFullPath(run_number): full_file_name = FileFinder.findRuns("REF_L_%d" % int(run_number))[0] except RuntimeError: logger.error("Could not find file: %s" % sys.exc_info()[1]) - full_file_name = '' + full_file_name = "" return full_file_name def get_run_number(nexus_full_path): try: - with h5py.File(nexus_full_path, 'r') as hf: - _run_number = hf.get('entry/run_number')[0].decode() + with h5py.File(nexus_full_path, "r") as hf: + _run_number = hf.get("entry/run_number")[0].decode() return _run_number except: logger.error("Could not find run number: %s" % sys.exc_info()[1]) diff --git a/RefRed/peak_finder_algorithms/peak_finder_derivation.py b/RefRed/peak_finder_algorithms/peak_finder_derivation.py index a97465e3..db652cf4 100644 --- a/RefRed/peak_finder_algorithms/peak_finder_derivation.py +++ b/RefRed/peak_finder_algorithms/peak_finder_derivation.py @@ -1,9 +1,9 @@ -import numpy as np import math +import numpy as np + class PeakFinderDerivation(object): - peaks = [-1, -1] xdata_firstderi = [] ydata_firstderi = [] @@ -175,6 +175,6 @@ def getPeaks(cls): if __name__ == "__main__": from file_loading_utility import loadCsvFile - [xdata, ydata, edata] = loadCsvFile('easy_data_set.csv') + [xdata, ydata, edata] = loadCsvFile("easy_data_set.csv") peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) [high_x, high_y] = peakfinder1.get5HighestPoints() diff --git a/RefRed/plot/all_plot_axis.py b/RefRed/plot/all_plot_axis.py index c3252e37..ae514c3c 100644 --- a/RefRed/plot/all_plot_axis.py +++ b/RefRed/plot/all_plot_axis.py @@ -1,5 +1,4 @@ class AllPlotAxis(object): - yt_view_interval = None yt_data_interval = None is_yt_ylog = False diff --git a/RefRed/plot/background_settings.py b/RefRed/plot/background_settings.py index 456e773e..92ebcbb4 100644 --- a/RefRed/plot/background_settings.py +++ b/RefRed/plot/background_settings.py @@ -2,8 +2,8 @@ from typing import List, Optional, Tuple # third-party imports -from qtpy.QtCore import Qt, QObject, Signal # type: ignore -from qtpy.QtWidgets import QDialog, QCheckBox, QWidget +from qtpy.QtCore import QObject, Qt, Signal # type: ignore +from qtpy.QtWidgets import QCheckBox, QDialog, QWidget # application imports from RefRed.calculations.lr_data import LRData @@ -100,9 +100,9 @@ def __init__(self): self.maingui: Optional[QObject] = None def __getitem__(self, key): - if key == 'data': + if key == "data": return self.data - elif key == 'norm': + elif key == "norm": return self.norm else: raise KeyError(f"No attribute with key '{key}' found in CompositeBackgroundSettings") @@ -200,7 +200,6 @@ def _initialize_reduction_table_updaters(self): class BackgroundSettingsView(QDialog): - # checkbox names as well as names for the model properties options = ["subtract_background", "two_backgrounds"] diff --git a/RefRed/plot/clear_plots.py b/RefRed/plot/clear_plots.py index 336cb529..2ad06ccc 100644 --- a/RefRed/plot/clear_plots.py +++ b/RefRed/plot/clear_plots.py @@ -1,5 +1,4 @@ class ClearPlots(object): - parent = None plot_yt = False @@ -37,11 +36,11 @@ def __init__( if is_data: self.clear_data_plots() - parent.ui.dataNameOfFile.setText('') + parent.ui.dataNameOfFile.setText("") if is_norm: self.clear_norm_plots() - parent.ui.normNameOfFile.setText('') + parent.ui.normNameOfFile.setText("") if self.stitched: self.clear_stitched() @@ -51,19 +50,19 @@ def __init__( def clear_metadata(self): parent = self.parent - parent.ui.metadataProtonChargeValue.setText('N/A') - parent.ui.metadataProtonChargeUnits.setText('units') - parent.ui.metadataLambdaRequestedValue.setText('N/A') - parent.ui.metadataLambdaRequestedUnits.setText('units') - parent.ui.metadatathiValue.setText('N/A') - parent.ui.metadatathiUnits.setText('units') - parent.ui.metadatatthdValue.setText('N/A') - parent.ui.metadatatthdUnits.setText('units') - parent.ui.metadataS1WValue.setText('N/A') - parent.ui.metadataS1HValue.setText('N/A') - parent.ui.metadataS2WValue.setText('N/A') - parent.ui.metadataS2HValue.setText('N/A') - parent.ui.metadataRunNumber.setText('N/A') + parent.ui.metadataProtonChargeValue.setText("N/A") + parent.ui.metadataProtonChargeUnits.setText("units") + parent.ui.metadataLambdaRequestedValue.setText("N/A") + parent.ui.metadataLambdaRequestedUnits.setText("units") + parent.ui.metadatathiValue.setText("N/A") + parent.ui.metadatathiUnits.setText("units") + parent.ui.metadatatthdValue.setText("N/A") + parent.ui.metadatatthdUnits.setText("units") + parent.ui.metadataS1WValue.setText("N/A") + parent.ui.metadataS1HValue.setText("N/A") + parent.ui.metadataS2WValue.setText("N/A") + parent.ui.metadataS2HValue.setText("N/A") + parent.ui.metadataRunNumber.setText("N/A") def clear_data_plots(self): parent = self.parent diff --git a/RefRed/plot/display_plots.py b/RefRed/plot/display_plots.py index 207c4d36..8210fa9f 100644 --- a/RefRed/plot/display_plots.py +++ b/RefRed/plot/display_plots.py @@ -1,11 +1,11 @@ # standard imports import bisect -# third party imports +import RefRed.colors as colors +# third party imports # application imports from RefRed.calculations.lr_data import LRData -import RefRed.colors as colors from RefRed.gui_handling.update_plot_widget_status import UpdatePlotWidgetStatus from RefRed.plot.background_settings import backgrounds_settings from RefRed.plot.clear_plots import ClearPlots @@ -13,7 +13,6 @@ class DisplayPlots(object): - parent = None _data = None is_data = True @@ -312,7 +311,6 @@ def plot_it(self): self.it_plot_ui.canvas.draw_idle() def plot_yt(self): - _ytof = self.ytof _isLog = True _tof_axis = self.tofAxis @@ -401,7 +399,6 @@ def workWithData(self, update_reduction_table=True): self.ix_plot_ui = parent.ui.data_ix_plot if update_reduction_table: - [peak1, peak2] = self.peak parent.ui.peakFromValue.setValue(peak1) parent.ui.peakToValue.setValue(peak2) diff --git a/RefRed/plot/home_plot_button_clicked.py b/RefRed/plot/home_plot_button_clicked.py index ab999f77..5fc8add4 100644 --- a/RefRed/plot/home_plot_button_clicked.py +++ b/RefRed/plot/home_plot_button_clicked.py @@ -2,7 +2,6 @@ class HomePlotButtonClicked(object): - parent = None def __init__(self, parent=None, plot_type=None): @@ -10,7 +9,7 @@ def __init__(self, parent=None, plot_type=None): return self.parent = parent - if plot_type == 'stitching': + if plot_type == "stitching": data = parent.big_table_data[0, 0] if data.all_plot_axis.reduced_plot_stitching_tab_data_interval is None: return @@ -21,7 +20,6 @@ def __init__(self, parent=None, plot_type=None): self.update_manual_axis_input_dialog(xmin, xmax, ymin, ymax) else: - o_gui_utility = GuiUtility(parent=self.parent) row = o_gui_utility.get_current_table_reduction_check_box_checked() column = 0 if o_gui_utility.is_data_tab_selected() else 1 @@ -34,7 +32,7 @@ def __init__(self, parent=None, plot_type=None): if data.all_plot_axis.yi_data_interval is None: return - if plot_type == 'yi': + if plot_type == "yi": [xmin, xmax, ymin, ymax] = data.all_plot_axis.yi_data_interval data.all_plot_axis.yi_view_interval = [xmin, xmax, ymin, ymax] if column == 0: @@ -42,7 +40,7 @@ def __init__(self, parent=None, plot_type=None): else: _plot_ui = parent.ui.norm_yi_plot.canvas - elif plot_type == 'yt': + elif plot_type == "yt": [xmin, xmax, ymin, ymax] = data.all_plot_axis.yt_data_interval data.all_plot_axis.yt_view_interval = [xmin, xmax, ymin, ymax] if column == 0: @@ -50,7 +48,7 @@ def __init__(self, parent=None, plot_type=None): else: _plot_ui = parent.ui.norm_yt_plot.canvas - elif plot_type == 'it': + elif plot_type == "it": [xmin, xmax, ymin, ymax] = data.all_plot_axis.it_data_interval data.all_plot_axis.it_view_interval = [xmin, xmax, ymin, ymax] if column == 0: @@ -58,7 +56,7 @@ def __init__(self, parent=None, plot_type=None): else: _plot_ui = parent.ui.norm_it_plot.canvas - elif plot_type == 'ix': + elif plot_type == "ix": [xmin, xmax, ymin, ymax] = data.all_plot_axis.ix_data_interval data.all_plot_axis.ix_view_interval = [xmin, xmax, ymin, ymax] if column == 0: @@ -73,7 +71,6 @@ def __init__(self, parent=None, plot_type=None): _plot_ui.draw() def update_manual_axis_input_dialog(self, xmin, xmax, ymin, ymax): - if self.parent.manual_x_axis_dialog is not None: _xmin = "%.4f" % xmin _xmax = "%.4f" % xmax diff --git a/RefRed/plot/launch_stitching_manual_axis.py b/RefRed/plot/launch_stitching_manual_axis.py index d68eabac..72d9e2d6 100644 --- a/RefRed/plot/launch_stitching_manual_axis.py +++ b/RefRed/plot/launch_stitching_manual_axis.py @@ -1,20 +1,20 @@ from qtpy.QtWidgets import QMainWindow + from RefRed.calculations.lr_data import LRData +from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.interfaces import load_ui from RefRed.reduction.reduced_data_handler import ReducedDataHandler -from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.tabledata import TableData class ChangeStitchingDataInterval(object): - def __init__(self, parent=None, yaxis_type='RvsQ', x_min=None, x_max=None, y_min=None, y_max=None) -> None: - + def __init__(self, parent=None, yaxis_type="RvsQ", x_min=None, x_max=None, y_min=None, y_max=None) -> None: self.parent = parent row = 0 big_table_data: TableData = parent.big_table_data _lrdata: LRData = big_table_data.reflectometry_data(row) - if yaxis_type == 'RvsQ': + if yaxis_type == "RvsQ": [xmin_user, xmax_user] = _lrdata.all_plot_axis.reduced_plot_RQQ4userView_x # type: ignore [ymin_user, ymax_user] = _lrdata.all_plot_axis.reduced_plot_RQuserView_y # type: ignore @@ -49,11 +49,10 @@ def plot(self): class LaunchStitchingManualXAxis(QMainWindow): - x_min = None x_max = None _lrdata = None - yaxis_type = 'RvsQ' + yaxis_type = "RvsQ" def __init__(self, parent=None, mouse_x=0, mouse_y=0): QMainWindow.__init__(self, parent=parent) @@ -80,11 +79,10 @@ def __init__(self, parent=None, mouse_x=0, mouse_y=0): self.init_widgets() def init_widgets(self): - o_gui_utility = GuiUtility(parent=self.parent) axis_type = o_gui_utility.get_reduced_yaxis_type() - if axis_type == 'RvsQ': + if axis_type == "RvsQ": [_x_min, _x_max, _y_min, _y_max] = self._lrdata.all_plot_axis.get_user_reduced_RQ_view() else: [_x_min, _x_max, _y_min, _y_max] = self._lrdata.all_plot_axis.get_user_reduced_RQ4Q_view() @@ -130,11 +128,10 @@ def validate_changes(self): class LaunchStitchingManualYAxis(QMainWindow): - y_min = None y_max = None _lrdata = None - yaxis_type = 'RvsQ' + yaxis_type = "RvsQ" def __init__(self, parent=None, mouse_x=0, mouse_y=0): QMainWindow.__init__(self, parent=parent) @@ -163,7 +160,7 @@ def init_widgets(self): o_gui_utility = GuiUtility(parent=self.parent) axis_type = o_gui_utility.get_reduced_yaxis_type() - if axis_type == 'RvsQ': + if axis_type == "RvsQ": [_x_min, _x_max, _y_min, _y_max] = self._lrdata.all_plot_axis.get_user_reduced_RQ_view() else: [_x_min, _x_max, _y_min, _y_max] = self._lrdata.all_plot_axis.get_user_reduced_RQ4Q_view() @@ -187,7 +184,7 @@ def y_max_event(self): self.validate_changes() def y_auto_rescale_event(self): - if self.yaxis_type == 'RvsQ': + if self.yaxis_type == "RvsQ": [xmin_user, xmax_user] = self._lrdata.all_plot_axis.reduced_plot_RQQ4userView_x [ymin_user, ymax_user] = self._lrdata.all_plot_axis.reduced_plot_RQuserView_y [xmin_auto, xmax_auto] = self._lrdata.all_plot_axis.reduced_plot_RQQ4autoView_x diff --git a/RefRed/plot/log_plot_toggle.py b/RefRed/plot/log_plot_toggle.py index 3caf718b..ce3b12ac 100644 --- a/RefRed/plot/log_plot_toggle.py +++ b/RefRed/plot/log_plot_toggle.py @@ -2,15 +2,14 @@ class LogPlotToggle(object): - def __init__(self, parent=None, status='log', plot_type=None, is_y_log=True): - + def __init__(self, parent=None, status="log", plot_type=None, is_y_log=True): status = str(status) - if status == 'log': + if status == "log": isLog = True else: isLog = False - if plot_type == 'stitching': + if plot_type == "stitching": [row, column] = [0, 0] else: o_gui_utility = GuiUtility(parent=parent) @@ -21,27 +20,27 @@ def __init__(self, parent=None, status='log', plot_type=None, is_y_log=True): if data is None: return - if plot_type == 'stitching': + if plot_type == "stitching": if is_y_log: data.all_plot_axis.is_reduced_plot_stitching_tab_ylog = isLog else: data.all_plot_axis.is_reduced_plot_stitching_tab_xlog = isLog - elif plot_type == 'yi': + elif plot_type == "yi": if is_y_log: data.all_plot_axis.is_yi_ylog = isLog else: data.all_plot_axis.is_yi_xlog = isLog - elif plot_type == 'yt': + elif plot_type == "yt": if is_y_log: data.all_plot_axis.is_yt_ylog = isLog else: data.all_plot_axis.is_yt_xlog = isLog - elif plot_type == 'it': + elif plot_type == "it": if is_y_log: data.all_plot_axis.is_it_ylog = isLog else: data.all_plot_axis.is_it_xlog = isLog - elif plot_type == 'ix': + elif plot_type == "ix": if is_y_log: data.all_plot_axis.is_ix_ylog = isLog else: diff --git a/RefRed/plot/mouse_leave_plot.py b/RefRed/plot/mouse_leave_plot.py index c23fcc32..1f501f90 100644 --- a/RefRed/plot/mouse_leave_plot.py +++ b/RefRed/plot/mouse_leave_plot.py @@ -2,7 +2,6 @@ class MouseLeavePlot(object): - parent = None def __init__(self, parent=None, plot_type=None): @@ -10,7 +9,7 @@ def __init__(self, parent=None, plot_type=None): return self.parent = parent - if plot_type == 'stitching': + if plot_type == "stitching": self.leave_figure_plot(plot_type=plot_type, row=0, column=0) # elif retain_all: # self.leave_all_figure_plot(plot_type = plot_type) @@ -34,22 +33,22 @@ def leave_all_figure_plot(self, plot_type, row=-1, column=-1): return c = 0 # TODO what is the meaning of `c` ? - if plot_type == 'yi': + if plot_type == "yi": if c == 0: plot_ui = parent.ui.data_yi_plot else: plot_ui = parent.ui.norm_yi_plot - elif plot_type == 'yt': + elif plot_type == "yt": if c == 0: plot_ui = parent.ui.data_yt_plot else: plot_ui = parent.ui.norm_yt_plot - elif plot_type == 'it': + elif plot_type == "it": if c == 0: plot_ui = parent.ui.data_it_plot else: plot_ui = parent.ui.norm_it_plot - elif plot_type == 'ix': + elif plot_type == "ix": if c == 0: plot_ui = parent.ui.data_ix_plot else: @@ -61,16 +60,16 @@ def leave_all_figure_plot(self, plot_type, row=-1, column=-1): plot_ui.canvas.ax.yaxis.set_data_interval(ymin, ymax) plot_ui.draw() - if plot_type == 'yi': + if plot_type == "yi": data.all_plot_axis.yi_view_interval = [xmin, xmax, ymin, ymax] parent.global_yi_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'yt': + elif plot_type == "yt": data.all_plot_axis.yt_view_interval = [xmin, xmax, ymin, ymax] parent.global_yt_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'it': + elif plot_type == "it": data.all_plot_axis.it_view_interval = [xmin, xmax, ymin, ymax] parent.global_it_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'ix': + elif plot_type == "ix": data.all_plot_axis.ix_view_interval = [xmin, xmax, ymin, ymax] parent.global_ix_view_interval = [xmin, xmax, ymin, ymax] @@ -89,31 +88,31 @@ def leave_figure_plot(self, plot_type=None, row=-1, column=-1): if data is None: return - if plot_type == 'yi': + if plot_type == "yi": # view_interval = data.all_plot_axis.yi_view_interval if column == 0: plot_ui = parent.ui.data_yi_plot else: plot_ui = parent.ui.norm_yi_plot - elif plot_type == 'yt': + elif plot_type == "yt": # view_interval = data.all_plot_axis.yt_view_interval if column == 0: plot_ui = parent.ui.data_yt_plot else: plot_ui = parent.ui.norm_yt_plot - elif plot_type == 'it': + elif plot_type == "it": # view_interval = data.all_plot_axis.it_view_interval if column == 0: plot_ui = parent.ui.data_it_plot else: plot_ui = parent.ui.norm_it_plot - elif plot_type == 'ix': + elif plot_type == "ix": # view_interval = data.all_plot_axis.ix_view_interval if column == 0: plot_ui = parent.ui.data_ix_plot else: plot_ui = parent.ui.norm_ix_plot - elif plot_type == 'stitching': + elif plot_type == "stitching": # view_interval = data.all_plot_axis.reduced_plot_stitching_tab_view_interval plot_ui = parent.ui.data_stitching_plot @@ -123,15 +122,15 @@ def leave_figure_plot(self, plot_type=None, row=-1, column=-1): plot_ui.canvas.ax.yaxis.set_data_interval(ymin, ymax) plot_ui.draw() - if plot_type == 'yi': + if plot_type == "yi": data.all_plot_axis.yi_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'yt': + elif plot_type == "yt": data.all_plot_axis.yt_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'it': + elif plot_type == "it": data.all_plot_axis.it_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'ix': + elif plot_type == "ix": data.all_plot_axis.ix_view_interval = [xmin, xmax, ymin, ymax] - elif plot_type == 'stitching': + elif plot_type == "stitching": data.all_plot_axis.reduced_plot_stitching_tab_view_interval = [xmin, xmax, ymin, ymax] parent.big_table_data[row, column] = data diff --git a/RefRed/plot/popup_plot_1d.py b/RefRed/plot/popup_plot_1d.py index 1a1629ba..64d17390 100644 --- a/RefRed/plot/popup_plot_1d.py +++ b/RefRed/plot/popup_plot_1d.py @@ -1,25 +1,25 @@ # standard imports import bisect -from pathlib import Path import os +from pathlib import Path from typing import Optional # third-party imports from qtpy.QtWidgets import QDialog, QFileDialog +import RefRed.colors +import RefRed.utilities + # package imports from RefRed.calculations.lr_data import LRData -import RefRed.colors from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.observer import SpinBoxObserver from RefRed.interfaces import load_ui -from RefRed.plot.background_settings import backgrounds_settings, BackgroundSettingsView +from RefRed.plot.background_settings import BackgroundSettingsView, backgrounds_settings from RefRed.plot.display_plots import DisplayPlots -import RefRed.utilities class PopupPlot1d(QDialog): - parent = None data_type = "data" data = None @@ -44,7 +44,6 @@ class PopupPlot1d(QDialog): nbr_pixel_y_axis = 304 def __init__(self, parent=None, data_type: str = "data", data: Optional[LRData] = None, row: int = 0): - self.data_type = data_type self.parent = parent # argument data is optional for historical reasons but it should always be passed, never use the default value diff --git a/RefRed/plot/popup_plot_2d.py b/RefRed/plot/popup_plot_2d.py index f2e4dd97..e70765ba 100644 --- a/RefRed/plot/popup_plot_2d.py +++ b/RefRed/plot/popup_plot_2d.py @@ -1,23 +1,22 @@ # standard imports -from pathlib import Path import os +from pathlib import Path # third-party imports from qtpy.QtWidgets import QDialog, QFileDialog # package imports import RefRed.colors +import RefRed.utilities from RefRed.gui_handling.auto_tof_range_radio_button_handler import AutoTofRangeRadioButtonHandler from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.observer import SpinBoxObserver from RefRed.interfaces import load_ui -from RefRed.plot.background_settings import backgrounds_settings, BackgroundSettingsView +from RefRed.plot.background_settings import BackgroundSettingsView, backgrounds_settings from RefRed.plot.display_plots import DisplayPlots -import RefRed.utilities class PopupPlot2d(QDialog): - parent = None _open_instances = [] # registry of PopupPlot2d instances data = None @@ -31,7 +30,6 @@ class PopupPlot2d(QDialog): auto_max_tof = None def __init__(self, parent=None, data_type="data", data=None, row=0): - self.parent = parent self.data = data self.data_type = data_type diff --git a/RefRed/plot/single_click_plot.py b/RefRed/plot/single_click_plot.py index 358b161b..2273785d 100644 --- a/RefRed/plot/single_click_plot.py +++ b/RefRed/plot/single_click_plot.py @@ -1,16 +1,14 @@ import time + +from RefRed.gui_handling.gui_utility import GuiUtility +from RefRed.plot.launch_stitching_manual_axis import LaunchStitchingManualXAxis, LaunchStitchingManualYAxis from RefRed.plot.popup_plot_1d import PopupPlot1d from RefRed.plot.popup_plot_2d import PopupPlot2d -from RefRed.plot.launch_stitching_manual_axis import LaunchStitchingManualXAxis -from RefRed.plot.launch_stitching_manual_axis import LaunchStitchingManualYAxis -from RefRed.gui_handling.gui_utility import GuiUtility - DOUBLE_CLICK_DELAY = 0.4 # seconds class SingleClickPlot(object): - parent = None data = None row = 0 @@ -18,17 +16,16 @@ class SingleClickPlot(object): def __init__( self, parent, - data_type='data', - plot_type='yi', + data_type="data", + plot_type="yi", is_pan_or_zoom_activated=False, is_manual_zoom_requested=False, is_x_axis_manual_zoom_requested=False, mouse_x=0, mouse_y=0, ): - self.parent = parent - if plot_type == 'stitching': + if plot_type == "stitching": if is_manual_zoom_requested: self.right_click_stitching_plot(is_x_axis_manual_zoom_requested, mouse_x, mouse_y) return @@ -42,13 +39,13 @@ def __init__( self.data = parent.big_table_data[row, col] - if plot_type in ['ix', 'it']: + if plot_type in ["ix", "it"]: return - if plot_type == 'yi': + if plot_type == "yi": self.single_yi_plot_click(data_type=data_type) - if plot_type == 'yt': + if plot_type == "yt": self.single_yt_plot_click(data_type=data_type) def right_click_stitching_plot(self, is_x_axis_manual_zoom_requested, mouse_x, mouse_y): @@ -63,7 +60,7 @@ def right_click_stitching_plot(self, is_x_axis_manual_zoom_requested, mouse_x, m self.parent.manual_y_axis_dialog = manual_axis manual_axis.show() - def single_yi_plot_click(self, data_type='data'): + def single_yi_plot_click(self, data_type="data"): parent = self.parent if parent.time_click1 == -1: parent.time_click1 = time.time() @@ -80,7 +77,7 @@ def single_yi_plot_click(self, data_type='data'): parent.time_click1 = -1 - def single_yt_plot_click(self, data_type='data'): + def single_yt_plot_click(self, data_type="data"): parent = self.parent if parent.time_click1 == -1: parent.time_click1 = time.time() diff --git a/RefRed/preview_config/preview_config.py b/RefRed/preview_config/preview_config.py index d346d533..d48167e5 100644 --- a/RefRed/preview_config/preview_config.py +++ b/RefRed/preview_config/preview_config.py @@ -1,13 +1,14 @@ -from PyQt5.QtWidgets import QFileDialog -from qtpy import QtGui, QtWidgets from xml.dom import minidom + from numpy import empty -from RefRed.interfaces import load_ui +from PyQt5.QtWidgets import QFileDialog +from qtpy import QtGui, QtWidgets + import RefRed.colors +from RefRed.interfaces import load_ui class PreviewConfig(QtWidgets.QMainWindow): - system_name = ["instrument_name", "timestamp", "version", "mantid_version", "generator"] data_name = [ diff --git a/RefRed/reduction/calculate_sf_overlap_range.py b/RefRed/reduction/calculate_sf_overlap_range.py index abacb754..21c43a63 100644 --- a/RefRed/reduction/calculate_sf_overlap_range.py +++ b/RefRed/reduction/calculate_sf_overlap_range.py @@ -1,22 +1,22 @@ +import numpy as np from mantid import mtd from mantid.simpleapi import CreateWorkspace, Fit, ReplaceSpecialValues -import numpy as np class CalculateSFoverlapRange(object): - ''' + """ calculate the scaling factor (SF) to apply to match the average value of the overlap range of data between the two lconfig data sets - ''' + """ def __init__(self, left_lconfig, right_lconfig): self.left_lconfig = left_lconfig self.right_lconfig = right_lconfig def getSF(self): - ''' + """ fit data of the overlaping region between left and right sets - ''' + """ left_set = self.applySFtoLconfig(self.left_lconfig) right_set = self.right_lconfig @@ -30,8 +30,8 @@ def getSF(self): _sf = 1 else: - [a_left, b_left] = self.fitData(left_set, index_min_in_left, type='left') - [a_right, b_right] = self.fitData(right_set, index_max_in_right, type='right') + [a_left, b_left] = self.fitData(left_set, index_min_in_left, type="left") + [a_right, b_right] = self.fitData(right_set, index_max_in_right, type="right") nbr_points = 10 fit_range_to_use = self.gitFittingOverlapRange(min_x, max_x, nbr_points) @@ -41,9 +41,9 @@ def getSF(self): return _sf def applySFtoLconfig(self, lconfig): - ''' + """ use the auto_sf to the data set - ''' + """ y_axis = lconfig.reduce_y_axis e_axis = lconfig.reduce_e_axis sf = lconfig.sf_auto @@ -57,15 +57,14 @@ def applySFtoLconfig(self, lconfig): return lconfig def gitFittingOverlapRange(self, min_x, max_x, nbr_points): - step = (float(max_x) - float(min_x)) / float(nbr_points) _fit_range = np.arange(min_x, max_x + step, step) return _fit_range def calculateOverlapAxis(self, left_axis, right_axis): - ''' + """ calculate the overlap region of the two axis - ''' + """ _min_x = -1 _max_x = -1 no_overlap = True @@ -84,11 +83,11 @@ def calculateOverlapAxis(self, left_axis, right_axis): return [_min_x, _max_x, left_min_index, right_max_index, no_overlap] - def fitData(self, data_set, threshold_index, type='right'): - ''' + def fitData(self, data_set, threshold_index, type="right"): + """ will fit the data with linear fitting y=ax + b - ''' - if type == 'left': + """ + if type == "left": x_axis = data_set.reduce_q_axis[threshold_index:] y_axis = data_set.tmp_y_axis[threshold_index:] e_axis = data_set.tmp_e_axis[threshold_index:] @@ -103,9 +102,9 @@ def fitData(self, data_set, threshold_index, type='right'): InputWorkspace=dataToFit, NaNValue=0, NaNError=0, InfinityValue=0, InfinityError=0 ) - Fit(InputWorkspace=dataToFit, Function="name=UserFunction, Formula=a+b*x, a=1, b=2", Output='res') + Fit(InputWorkspace=dataToFit, Function="name=UserFunction, Formula=a+b*x, a=1, b=2", Output="res") - res = mtd['res_Parameters'] + res = mtd["res_Parameters"] b = res.cell(0, 1) a = res.cell(1, 1) @@ -117,19 +116,19 @@ def findNearest(self, array, value): return idx def scaleToApplyForBestOverlap(self, fit_range_to_use, a_left, b_left, a_right, b_right): - ''' + """ This function will use the same overlap region and will determine the scaling to apply to the second fit to get the best match - ''' + """ left_mean = self.calculateMeanOfFunctionOverRange(fit_range_to_use, a_left, b_left) right_mean = self.calculateMeanOfFunctionOverRange(fit_range_to_use, a_right, b_right) _sf = right_mean / left_mean return _sf def calculateMeanOfFunctionOverRange(self, range_to_use, a, b): - ''' + """ will return the average value of the function over the given range - ''' + """ sz_range = range_to_use.size _sum = 0 for i in range(sz_range): diff --git a/RefRed/reduction/global_reduction_settings_handler.py b/RefRed/reduction/global_reduction_settings_handler.py index 216b60b5..c25d9114 100644 --- a/RefRed/reduction/global_reduction_settings_handler.py +++ b/RefRed/reduction/global_reduction_settings_handler.py @@ -27,7 +27,7 @@ def retrieve_settings(self): self.settings.update( { "incident_medium_selected": str(self.parent.ui.selectIncidentMediumList.currentText()).strip(), - "q_min": float(self.parent.gui_metadata['q_min']), + "q_min": float(self.parent.gui_metadata["q_min"]), "q_step": float(self.parent.ui.qStep.text()), "scaling_factor_flag": self.parent.ui.scalingFactorFlag.isChecked(), "scaling_factor_file": str(self.parent.full_scaling_factor_file_name), diff --git a/RefRed/reduction/individual_reduction_settings_handler.py b/RefRed/reduction/individual_reduction_settings_handler.py index 514adc7b..6153e22d 100644 --- a/RefRed/reduction/individual_reduction_settings_handler.py +++ b/RefRed/reduction/individual_reduction_settings_handler.py @@ -1,10 +1,10 @@ """ - Generate reduction options from the reduction table. +Generate reduction options from the reduction table. - Note from code review: - It's not clear why the configuration stored in big_table_data[:, 3] - is saved if it's not used here. It creates confusion as to where we should - keep this information. +Note from code review: +It's not clear why the configuration stored in big_table_data[:, 3] +is saved if it's not used here. It creates confusion as to where we should +keep this information. """ # standard imports @@ -16,10 +16,9 @@ class IndividualReductionSettingsHandler(object): - data = None norm = None - output_workspace = '' + output_workspace = "" def __init__(self, parent=None, row_index=-1): self.parent = parent diff --git a/RefRed/reduction/live_calculate_sf.py b/RefRed/reduction/live_calculate_sf.py index 6f701894..ff0e5a0f 100644 --- a/RefRed/reduction/live_calculate_sf.py +++ b/RefRed/reduction/live_calculate_sf.py @@ -1,13 +1,11 @@ -from RefRed.reduction.normalization_stitching import AbsoluteNormalization -from RefRed.reduction.normalization_stitching import AutomaticStitching -from RefRed.reduction.normalization_stitching import ManualStitching from RefRed.gui_handling.gui_utility import GuiUtility +from RefRed.reduction.normalization_stitching import AbsoluteNormalization, AutomaticStitching, ManualStitching class LiveCalculateSF(object): - ''' + """ This class will determine the best scaling factor (SF) to apply to the data to stitch them - ''' + """ big_table_data = [] parent = None @@ -20,36 +18,36 @@ def __init__(self, parent=None, row_index=0, n_runs=1): self.n_runs = n_runs def run(self): - ''' + """ main part of the program that will calculate the various SF - ''' + """ o_gui = GuiUtility(parent=self.parent) stitching_type = o_gui.getStitchingType() - if stitching_type == 'absolute': + if stitching_type == "absolute": self.absolute_normalization_calculation(row_index=self.row_index) - elif stitching_type == 'auto': + elif stitching_type == "auto": self.auto_stitching_calculation(row_index=self.row_index) else: self.manual_stitching_calculation(row_index=self.row_index) def absolute_normalization_calculation(self, row_index=row_index): - ''' + """ will perform the absolute normalization - ''' + """ o_abs_norm = AbsoluteNormalization(parent=self.parent, row_index=row_index, n_runs=self.n_runs) o_abs_norm.run() def auto_stitching_calculation(self, row_index=row_index): - ''' + """ will perform the auto stitching normalization - ''' + """ o_auto_stit = AutomaticStitching(parent=self.parent, row_index=row_index, n_runs=self.n_runs) o_auto_stit.run() def manual_stitching_calculation(self, row_index=row_index): - ''' + """ will perform the manual stitching normalization - ''' + """ o_manual_stit = ManualStitching(parent=self.parent, row_index=row_index, n_runs=self.n_runs) o_manual_stit.run() diff --git a/RefRed/reduction/live_reduced_data_handler.py b/RefRed/reduction/live_reduced_data_handler.py index 92eb769c..e4bb3ffb 100644 --- a/RefRed/reduction/live_reduced_data_handler.py +++ b/RefRed/reduction/live_reduced_data_handler.py @@ -1,14 +1,13 @@ -from qtpy.QtWidgets import QApplication import numpy as np +from qtpy.QtWidgets import QApplication -from RefRed.gui_handling.gui_utility import GuiUtility -from RefRed.gui_handling.fill_stitching_table import FillStitchingTable import RefRed.colors +from RefRed.gui_handling.fill_stitching_table import FillStitchingTable +from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.tabledata import TableData class LiveReducedDataHandler(object): - big_table_data = None colors = None row_index = 0 @@ -69,10 +68,10 @@ def plot(self): ) if _data.all_plot_axis.is_reduced_plot_stitching_tab_ylog: - self.parent.ui.data_stitching_plot.set_yscale('log') + self.parent.ui.data_stitching_plot.set_yscale("log") if _data.all_plot_axis.is_reduced_plot_stitching_tab_xlog: - self.parent.ui.data_stitching_plot.set_xscale('log') + self.parent.ui.data_stitching_plot.set_xscale("log") self.parent.ui.data_stitching_plot.draw() self.parent.ui.data_stitching_plot.canvas.draw_idle() @@ -114,10 +113,10 @@ def live_plot(self): ) if _data.all_plot_axis.is_reduced_plot_stitching_tab_ylog: - self.parent.ui.data_stitching_plot.set_yscale('log') + self.parent.ui.data_stitching_plot.set_yscale("log") if _data.all_plot_axis.is_reduced_plot_stitching_tab_xlog: - self.parent.ui.data_stitching_plot.set_xscale('log') + self.parent.ui.data_stitching_plot.set_xscale("log") QApplication.processEvents() @@ -139,7 +138,7 @@ def get_current_color_plot(self, index_color): class ProducedSelectedOutputScaled(object): parent = None - axis_type = 'RvsQ' + axis_type = "RvsQ" def __init__(self, parent=None, q_axis=None, y_axis=None, e_axis=None): self.parent = parent @@ -161,13 +160,13 @@ def calculate(self): input_e_axis = self.input_e_axis # R vs Q selected - if self.axis_type == 'RvsQ': + if self.axis_type == "RvsQ": self.output_y_axis = input_y_axis self.output_e_axis = input_e_axis return # RQ4 vs Q selected - if self.axis_type == 'RQ4vsQ': + if self.axis_type == "RQ4vsQ": _q_axis_4 = input_q_axis**4 self.output_y_axis = input_y_axis * _q_axis_4 self.output_e_axis = input_e_axis * _q_axis_4 diff --git a/RefRed/reduction/normalization_stitching.py b/RefRed/reduction/normalization_stitching.py index 278432ec..ab2037b4 100644 --- a/RefRed/reduction/normalization_stitching.py +++ b/RefRed/reduction/normalization_stitching.py @@ -10,9 +10,9 @@ def __init__(self, parent=None, row_index=0, n_runs=1): self.n_runs = n_runs def _calculateSFCE(self, data_type="absolute"): - ''' + """ Scaling factor calculation of Ctritical Edge (CE) - ''' + """ _q_min = float(str(self.parent.ui.sf_qmin_value.text())) _q_max = float(str(self.parent.ui.sf_qmax_value.text())) @@ -39,10 +39,10 @@ def _calculateSFCE(self, data_type="absolute"): # Save the SF in first run self.saveSFinLConfig(self.parent.big_table_data[0, 2], _sf, data_type=data_type) - def saveSFinLConfig(self, lconfig, sf, data_type='absolute'): - if data_type == 'absolute': + def saveSFinLConfig(self, lconfig, sf, data_type="absolute"): + if data_type == "absolute": lconfig.sf_abs_normalization = sf - elif data_type == 'auto': + elif data_type == "auto": lconfig.sf_auto = sf else: lconfig.sf_manual = sf @@ -56,9 +56,9 @@ def getLConfig(self, row_index): class AbsoluteNormalization(ParentHandler): - ''' + """ this class performs the absolute normalization of reduced data - ''' + """ def __init__(self, parent=None, row_index=0, n_runs=1): super(AbsoluteNormalization, self).__init__(parent=parent, row_index=row_index, n_runs=n_runs) @@ -81,13 +81,13 @@ def copySFtoOtherAngles(self): ce_lconfig = self.getLConfig(0) _sf = ce_lconfig.sf_abs_normalization lconfig = self.getLConfig(self.row_index) - lconfig = self.saveSFinLConfig(lconfig, _sf, data_type='absolute') + lconfig = self.saveSFinLConfig(lconfig, _sf, data_type="absolute") class AutomaticStitching(ParentHandler): - ''' + """ automatic stiching of the reduced data using the Q range to calculate the CE - ''' + """ def __init__(self, parent=None, row_index=0, n_runs=1): super(AutomaticStitching, self).__init__(parent=parent, row_index=row_index, n_runs=n_runs) @@ -97,14 +97,14 @@ def run(self): def use_first_angle_range(self): if self.row_index == 0: - self._calculateSFCE(data_type='auto') + self._calculateSFCE(data_type="auto") else: self._calculateSFOtherAngles() def _calculateSFOtherAngles(self): - ''' + """ Scaling factor calculation of other angles - ''' + """ _row_index = self.row_index left_lconfig = self.getLConfig(_row_index - 1) right_lconfig = self.getLConfig(_row_index) @@ -115,10 +115,10 @@ def _calculateSFOtherAngles(self): class ManualStitching(ParentHandler): - ''' + """ manual stitching of the data. The program will simply used the data defined in the main table to scaled the data - ''' + """ def __init__(self, parent=None, row_index=0, n_runs=1): super(ManualStitching, self).__init__(parent=parent, row_index=row_index, n_runs=n_runs) @@ -127,4 +127,4 @@ def run(self): ce_lconfig = self.getLConfig(self.row_index) _sf = ce_lconfig.sf_manual lconfig = self.getLConfig(self.row_index) - lconfig = self.saveSFinLConfig(lconfig, _sf, data_type='manual') + lconfig = self.saveSFinLConfig(lconfig, _sf, data_type="manual") diff --git a/RefRed/reduction/reduced_data_handler.py b/RefRed/reduction/reduced_data_handler.py index d7d743e9..74b29f6f 100644 --- a/RefRed/reduction/reduced_data_handler.py +++ b/RefRed/reduction/reduced_data_handler.py @@ -1,10 +1,10 @@ -from RefRed.gui_handling.gui_utility import GuiUtility -import RefRed.colors import numpy as np +import RefRed.colors +from RefRed.gui_handling.gui_utility import GuiUtility -class ReducedDataHandler(object): +class ReducedDataHandler(object): big_table_data = None colors = None @@ -72,10 +72,10 @@ def plot(self): ) if _data.all_plot_axis.is_reduced_plot_stitching_tab_ylog: - self.parent.ui.data_stitching_plot.set_yscale('log') + self.parent.ui.data_stitching_plot.set_yscale("log") if _data.all_plot_axis.is_reduced_plot_stitching_tab_xlog: - self.parent.ui.data_stitching_plot.set_xscale('log') + self.parent.ui.data_stitching_plot.set_xscale("log") self.parent.ui.data_stitching_plot.draw() @@ -101,9 +101,8 @@ def get_current_color_plot(self, index_color): class ProducedSelectedOutputScaled(object): - parent = None - axis_type = 'RvsQ' + axis_type = "RvsQ" def __init__(self, parent=None, q_axis=None, y_axis=None, e_axis=None): self.parent = parent @@ -126,13 +125,13 @@ def calculate(self): input_e_axis = self.input_e_axis # R vs Q selected - if self.axis_type == 'RvsQ': + if self.axis_type == "RvsQ": self.output_y_axis = input_y_axis self.output_e_axis = input_e_axis return # RQ4 vs Q selected - if self.axis_type == 'RQ4vsQ': + if self.axis_type == "RQ4vsQ": _q_axis_4 = input_q_axis**4 self.output_y_axis = input_y_axis * _q_axis_4 self.output_e_axis = input_e_axis * _q_axis_4 diff --git a/RefRed/reduction_table_handling/check_list_run_compatibility.py b/RefRed/reduction_table_handling/check_list_run_compatibility.py index b3e13e4c..e25a3a5c 100644 --- a/RefRed/reduction_table_handling/check_list_run_compatibility.py +++ b/RefRed/reduction_table_handling/check_list_run_compatibility.py @@ -1,9 +1,8 @@ -from RefRed.calculations.load_list_nexus import LoadListNexus from RefRed.calculations.check_if_same_nxs_property import CheckIfSameNxsProperty +from RefRed.calculations.load_list_nexus import LoadListNexus class CheckListRunCompatibility(object): - list_wks = None runs_compatible = False @@ -19,7 +18,7 @@ def __init__(self, list_nexus=None, list_run=None): load_object = LoadListNexus(list_nexus=list_nexus_found, list_run=list_run_found, metadata_only=True) self.list_wks = load_object.list_wks_loaded - same_property_object = CheckIfSameNxsProperty(list_wks=self.list_wks, property_name='LambdaRequest') + same_property_object = CheckIfSameNxsProperty(list_wks=self.list_wks, property_name="LambdaRequest") if same_property_object.is_same_property: self.runs_compatible = True else: diff --git a/RefRed/reduction_table_handling/reduction_table_check_box.py b/RefRed/reduction_table_handling/reduction_table_check_box.py index 971e3f3f..11603c78 100644 --- a/RefRed/reduction_table_handling/reduction_table_check_box.py +++ b/RefRed/reduction_table_handling/reduction_table_check_box.py @@ -13,7 +13,6 @@ class ReductionTableCheckBox(object): - BOX_CHECKED = 2 # value emited by qtpy.QtWidgets.QCheckBox.stateChanged when checked row_selected = -1 prev_row_selected = -1 diff --git a/RefRed/reduction_table_handling/reduction_table_handler.py b/RefRed/reduction_table_handling/reduction_table_handler.py index f0525c64..d5a84b9e 100644 --- a/RefRed/reduction_table_handling/reduction_table_handler.py +++ b/RefRed/reduction_table_handling/reduction_table_handler.py @@ -12,7 +12,6 @@ class ReductionTableHandler(object): - from_row = -1 to_row = -1 diff --git a/RefRed/reduction_table_handling/update_reduction_table.py b/RefRed/reduction_table_handling/update_reduction_table.py index 61370414..c8bf12db 100644 --- a/RefRed/reduction_table_handling/update_reduction_table.py +++ b/RefRed/reduction_table_handling/update_reduction_table.py @@ -14,7 +14,6 @@ class UpdateReductionTable(object): - raw_runs = None is_data_displayed = True @@ -23,11 +22,11 @@ def __init__(self, parent=None, row=0, col=1, runs=None): self.row = row self.col = col - data_type = 'data' if col == 1 else 'norm' + data_type = "data" if col == 1 else "norm" self.is_data_displayed = True if (col == 1) else False item = self.parent.ui.reductionTable.item(row, col) - if item.text() == '': + if item.text() == "": self.clear_cell() self.parent.file_loaded_signal.emit(row, self.is_data_displayed, self.display_of_this_row_checked()) QApplication.processEvents() @@ -42,7 +41,7 @@ def __init__(self, parent=None, row=0, col=1, runs=None): col_comments = ReductionTableColumnIndex.COMMENTS if list_run_object.list_run_not_found != []: str_list_run_not_found = [str(x) for x in list_run_object.list_run_not_found] - runs_not_located = ', '.join(str_list_run_not_found) + runs_not_located = ", ".join(str_list_run_not_found) mess = "Can not locate %s run(s): %s" % (data_type, runs_not_located) self.parent.ui.reductionTable.item(row, col_comments).setText(mess) _color = QtGui.QColor(RefRed.colors.VALUE_BAD) @@ -56,10 +55,10 @@ def __init__(self, parent=None, row=0, col=1, runs=None): list_run_found = list(list_run_object.list_run_found) if list_run_found == []: - self.parent.ui.reductionTable.item(row, col).setText('') + self.parent.ui.reductionTable.item(row, col).setText("") return str_list_run_found = [str(x) for x in list_run_found] - final_list_run_found = ','.join(str_list_run_found) + final_list_run_found = ",".join(str_list_run_found) self.parent.ui.reductionTable.item(row, col).setText(final_list_run_found) list_nexus_found = list_run_object.list_nexus_found diff --git a/RefRed/settings/initialize_settings.py b/RefRed/settings/initialize_settings.py index 047041da..7063d41e 100644 --- a/RefRed/settings/initialize_settings.py +++ b/RefRed/settings/initialize_settings.py @@ -1,5 +1,6 @@ from qtpy.QtCore import QSettings # type: ignore -from RefRed import ORGANIZATION, APPNAME + +from RefRed import APPNAME, ORGANIZATION from RefRed.settings.list_settings import ListSettings @@ -25,7 +26,7 @@ def __getValue(self, key: str, lsettings, qsettings): value = lsettings.__dict__[key] # value from qsettings if qsettings.contains(key): - _value = str(qsettings.value(key) or '').strip() + _value = str(qsettings.value(key) or "").strip() if _value: value = _value diff --git a/RefRed/settings/list_settings.py b/RefRed/settings/list_settings.py index 5b957e99..961c3240 100644 --- a/RefRed/settings/list_settings.py +++ b/RefRed/settings/list_settings.py @@ -1,6 +1,5 @@ class ListSettings(object): def __init__(self): - self.q_min = 0.005 self.d_q0 = 0.0 self.dq_over_q = 0.028 diff --git a/RefRed/settings/settings_editor.py b/RefRed/settings/settings_editor.py index a4654250..bbc6611b 100644 --- a/RefRed/settings/settings_editor.py +++ b/RefRed/settings/settings_editor.py @@ -1,12 +1,12 @@ from qtpy import QtCore, QtWidgets -from RefRed.interfaces import load_ui -from RefRed.settings.settings_password_editor import SettingsPasswordEditor + from RefRed.gui_handling.gui_utility import GuiUtility +from RefRed.interfaces import load_ui from RefRed.settings.list_settings import ListSettings +from RefRed.settings.settings_password_editor import SettingsPasswordEditor class SettingsEditor(QtWidgets.QMainWindow): - is_super_user = False def __init__(self, parent=None, loadUI: bool = True): @@ -25,7 +25,7 @@ def populate_table(self): self.ui.tableWidget.setColumnCount(1) self.ui.tableWidget.setRowCount(nbr_key) self.ui.tableWidget.setVerticalHeaderLabels(_list_keys) - self.ui.tableWidget.setHorizontalHeaderLabels(['Value']) + self.ui.tableWidget.setHorizontalHeaderLabels(["Value"]) for _index, _key in enumerate(_gui_metadata.keys()): _item = QtWidgets.QTableWidgetItem() diff --git a/RefRed/settings/settings_password_editor.py b/RefRed/settings/settings_password_editor.py index 4c0cbc5c..0f8af60a 100644 --- a/RefRed/settings/settings_password_editor.py +++ b/RefRed/settings/settings_password_editor.py @@ -1,10 +1,10 @@ from qtpy import QtWidgets + from RefRed.interfaces import load_ui class SettingsPasswordEditor(QtWidgets.QDialog): - - password = '5' + password = "5" def __init__(self, parent=None): self.parent = parent diff --git a/RefRed/sf_calculator/check_sf_run_reduction_button_status.py b/RefRed/sf_calculator/check_sf_run_reduction_button_status.py index 65840741..76c13b31 100644 --- a/RefRed/sf_calculator/check_sf_run_reduction_button_status.py +++ b/RefRed/sf_calculator/check_sf_run_reduction_button_status.py @@ -2,7 +2,6 @@ class CheckSfRunReductionButtonStatus(object): - sf_gui = None def __init__(self, parent=None): @@ -27,7 +26,7 @@ def isBigTableReady(self): back1 = str(self.sf_gui.tableWidget.item(_row, 12).text()) back2 = str(self.sf_gui.tableWidget.item(_row, 13).text()) - if (peak1 == 'N/A') or (peak2 == 'N/A') or (back1 == 'N/A') or (back2 == 'N/A'): + if (peak1 == "N/A") or (peak2 == "N/A") or (back1 == "N/A") or (back2 == "N/A"): return False if int(peak1) < int(back1): @@ -40,7 +39,7 @@ def isBigTableReady(self): def isOutputFileNameReady(self): output_file_name = self.sf_gui.sfFileNameLabel.text() - if output_file_name == 'N/A': + if output_file_name == "N/A": return False return True diff --git a/RefRed/sf_calculator/compare_two_nxsdata_for_sfcalculator.py b/RefRed/sf_calculator/compare_two_nxsdata_for_sfcalculator.py index b241ac47..ba75d635 100644 --- a/RefRed/sf_calculator/compare_two_nxsdata_for_sfcalculator.py +++ b/RefRed/sf_calculator/compare_two_nxsdata_for_sfcalculator.py @@ -1,5 +1,5 @@ class CompareTwoNXSDataForSFcalculator(object): - ''' + """ will return -1, 0 or 1 according to the position of the nexusToPosition in relation to the nexusToCompareWith based on the following criteria #1: number of attenuators (ascending order) @@ -7,7 +7,7 @@ class CompareTwoNXSDataForSFcalculator(object): #3: S2W (ascending order) #4: S2H (descending order) #5 if everything up to this point is identical, return 0 - ''' + """ nexusToCompareWithRun = None nexusToPositionRun = None @@ -23,17 +23,17 @@ def __init__(self, nxsdataToCompareWith, nxsdataToPosition): self.mtdToCompareWith = nxsdataToCompareWith.workspace self.mtdToPosition = nxsdataToPosition.workspace - compare1 = self.compareParameter('LambdaRequest', 'descending') + compare1 = self.compareParameter("LambdaRequest", "descending") if compare1 != 0: self.resultComparison = compare1 return - compare2 = self.compareParameter('vATT', 'ascending') + compare2 = self.compareParameter("vATT", "ascending") if compare2 != 0: self.resultComparison = compare2 return - compare3 = self.comparepCharge('descending') + compare3 = self.comparepCharge("descending") if compare3 != 0: self.resultComparison = compare3 return @@ -45,7 +45,7 @@ def comparepCharge(self, order): _paramNexusToCompareWith = self.get_normalized_pcharge(_mtdToCompareWith) _paramNexusToPosition = self.get_normalized_pcharge(_mtdToPosition) - if order == 'ascending': + if order == "ascending": resultLessThan = -1 resultMoreThan = 1 else: @@ -61,7 +61,7 @@ def comparepCharge(self, order): def get_normalized_pcharge(self, _mtd): _run = _mtd.getRun() - pcharge = float(_run.getProperty('gd_prtn_chrg').value) + pcharge = float(_run.getProperty("gd_prtn_chrg").value) # FIXME get total counts and divide pcharge/total_counts total_counts = float(_mtd.getNumberEvents()) @@ -80,7 +80,7 @@ def compareParameter(self, param, order, param_backup=None): _paramNexusToCompareWith = float(_nexusToCompareWithRun.getProperty(param_backup).value[0]) _paramNexusToPosition = float(_nexusToPositionRun.getProperty(param_backup).value[0]) - if order == 'ascending': + if order == "ascending": resultLessThan = -1 resultMoreThan = 1 else: diff --git a/RefRed/sf_calculator/fill_sf_gui_table.py b/RefRed/sf_calculator/fill_sf_gui_table.py index 503014f5..893a5d3d 100644 --- a/RefRed/sf_calculator/fill_sf_gui_table.py +++ b/RefRed/sf_calculator/fill_sf_gui_table.py @@ -1,23 +1,21 @@ -from qtpy import QtGui, QtCore -from qtpy import QtWidgets +from qtpy import QtCore, QtGui, QtWidgets + import RefRed.colors class FillSFGuiTable(object): - tableData = None parent = None index_color = 0 def __init__(self, parent=None, table=None, is_using_si_slits=False): - self.parent = parent if is_using_si_slits: - s2ih = 'SiH' - s2iw = 'SiW' + s2ih = "SiH" + s2iw = "SiW" else: - s2ih = 'S2H' - s2iw = 'S2W' + s2ih = "S2H" + s2iw = "S2W" verticalHeader = [ "Run #", "Nbr. Attenuator", @@ -126,8 +124,8 @@ def __init__(self, parent=None, table=None, is_using_si_slits=False): for k in range(10, 16): _value = _row[k] _brush = QtGui.QBrush() - if _value == '0' or _value == 'N/A' or _value == '': - _value = 'N/A' + if _value == "0" or _value == "N/A" or _value == "": + _value = "N/A" _brush.setColor(RefRed.colors.VALUE_BAD) is_any_red = True else: diff --git a/RefRed/sf_calculator/incident_medium_list_editor.py b/RefRed/sf_calculator/incident_medium_list_editor.py index 640caa9e..ad35a13d 100644 --- a/RefRed/sf_calculator/incident_medium_list_editor.py +++ b/RefRed/sf_calculator/incident_medium_list_editor.py @@ -5,7 +5,6 @@ class IncidentMediumListEditor(QDialog): - sf_gui = None current_index = -1 @@ -32,9 +31,9 @@ def fillGui(self, _list): def validateEvent(self): text_medium = str(self.ui.textEdit.toPlainText()) - text_list = text_medium.split('\n') + text_list = text_medium.split("\n") [text_list, current_index] = removeEmptyStrElementAndUpdateIndexSelected(text_list, self.current_index) - text_list.insert(0, 'Select or Define Incident Medium ...') + text_list.insert(0, "Select or Define Incident Medium ...") self.sf_gui.incidentMediumComboBox.clear() self.sf_gui.incidentMediumComboBox.addItems(text_list) self.sf_gui.incidentMediumComboBox.setCurrentIndex(current_index) diff --git a/RefRed/sf_calculator/load_and_sort_nxsdata_for_sf_calculator.py b/RefRed/sf_calculator/load_and_sort_nxsdata_for_sf_calculator.py index 5917394c..21374ce7 100644 --- a/RefRed/sf_calculator/load_and_sort_nxsdata_for_sf_calculator.py +++ b/RefRed/sf_calculator/load_and_sort_nxsdata_for_sf_calculator.py @@ -1,9 +1,9 @@ -from qtpy import QtWidgets -import numpy as np import mantid.simpleapi as api +import numpy as np +from qtpy import QtWidgets -from RefRed.sf_calculator.sort_nxsdata import SortNXSData from RefRed.sf_calculator.lr_data import LRData +from RefRed.sf_calculator.sort_nxsdata import SortNXSData INSTRUMENT_SHORT_NAME = "REF_L" @@ -14,15 +14,15 @@ class LoadAndSortNXSDataForSFcalculator(object): list_NXSData = [] list_NXSData_sorted = [] list_metadata = [ - 'gd_prtn_chrg', - 'S1HWidth', - 'S1VHeight', - 'S2HWidth', - 'S2VHeight', - 'SiHWidth', - 'SiVHeight', - 'LambdaRequest', - 'vATT', + "gd_prtn_chrg", + "S1HWidth", + "S1VHeight", + "S2HWidth", + "S2VHeight", + "SiHWidth", + "SiVHeight", + "LambdaRequest", + "vATT", ] big_table = [] is_using_si_slits = False @@ -44,7 +44,7 @@ def __init__(self, list_runs, parent=None, read_options=None, sort_by_metadata=F def loadNXSData(self): for _runs in self.list_runs: _full_file_name = api.FileFinder.findRuns("%s_%d" % (INSTRUMENT_SHORT_NAME, int(_runs)))[0] - if _full_file_name != '': + if _full_file_name != "": workspace = api.LoadEventNexus( Filename=_full_file_name, OutputWorkspace="__data_file_%s" % _runs, MetaDataOnly=False ) @@ -142,7 +142,7 @@ def retrieveMetadataValue(self, _name): elif isinstance(_value, str): _value = _value else: - _value = '[' + str(_value[0]) + ',...]' + '-> (' + str(len(_value)) + ' entries)' + _value = "[" + str(_value[0]) + ",...]" + "-> (" + str(len(_value)) + " entries)" return _value def getTableData(self): diff --git a/RefRed/sf_calculator/lr_data.py b/RefRed/sf_calculator/lr_data.py index b80cf08d..bdf9bb02 100644 --- a/RefRed/sf_calculator/lr_data.py +++ b/RefRed/sf_calculator/lr_data.py @@ -1,14 +1,15 @@ """ - Notes from review: This class does a subset of what is done in calculations.lr_data. - This code is probably not needed. +Notes from review: This class does a subset of what is done in calculations.lr_data. +This code is probably not needed. """ -from mantid.simpleapi import Rebin -import numpy as np import logging import math import os +import numpy as np +from mantid.simpleapi import Rebin + from RefRed.peak_finder_algorithms.peak_finder_derivation import PeakFinderDerivation from RefRed.plot.all_plot_axis import AllPlotAxis @@ -19,7 +20,7 @@ class LRData(object): tof_range = None - low_res = ['0', '255'] + low_res = ["0", "255"] low_res_flag = True is_better_chopper_coverage = True @@ -28,28 +29,28 @@ def __init__(self, workspace, read_options): self.read_options = read_options mt_run = workspace.getRun() - self.run_number = mt_run.getProperty('run_number').value + self.run_number = mt_run.getProperty("run_number").value - self.lambda_requested = float(mt_run.getProperty('LambdaRequest').value[0]) - self.lambda_requested_units = mt_run.getProperty('LambdaRequest').units - self.thi = mt_run.getProperty('thi').value[0] - self.thi_units = mt_run.getProperty('thi').units - self.tthd = mt_run.getProperty('tthd').value[0] - self.tthd_units = mt_run.getProperty('tthd').units - self.S1W = mt_run.getProperty('S1HWidth').value[0] - self.S1H = mt_run.getProperty('S1VHeight').value[0] + self.lambda_requested = float(mt_run.getProperty("LambdaRequest").value[0]) + self.lambda_requested_units = mt_run.getProperty("LambdaRequest").units + self.thi = mt_run.getProperty("thi").value[0] + self.thi_units = mt_run.getProperty("thi").units + self.tthd = mt_run.getProperty("tthd").value[0] + self.tthd_units = mt_run.getProperty("tthd").units + self.S1W = mt_run.getProperty("S1HWidth").value[0] + self.S1H = mt_run.getProperty("S1VHeight").value[0] try: - self.SiW = mt_run.getProperty('SiHWidth').value[0] - self.SiH = mt_run.getProperty('SiVHeight').value[0] + self.SiW = mt_run.getProperty("SiHWidth").value[0] + self.SiH = mt_run.getProperty("SiVHeight").value[0] self.isSiThere = True except: - self.S2W = mt_run.getProperty('S2HWidth').value[0] - self.S2H = mt_run.getProperty('S2VHeight').value[0] + self.S2W = mt_run.getProperty("S2HWidth").value[0] + self.S2H = mt_run.getProperty("S2VHeight").value[0] - self.attenuatorNbr = mt_run.getProperty('vATT').value[0] - 1 - self.date = mt_run.getProperty('run_start').value - self.full_file_name = mt_run.getProperty('Filename').value[0] + self.attenuatorNbr = mt_run.getProperty("vATT").value[0] - 1 + self.date = mt_run.getProperty("run_start").value + self.full_file_name = mt_run.getProperty("Filename").value[0] self.filename = os.path.basename(self.full_file_name) sample = workspace.getInstrument().getSample() @@ -71,7 +72,7 @@ def __init__(self, workspace, read_options): # calculate theta self.theta = self.calculate_theta() - self.frequency = float(mt_run.getProperty('Speed1').value[0]) + self.frequency = float(mt_run.getProperty("Speed1").value[0]) # Determine the range to select in TOF according to how the DAS computed the # chopper settings @@ -98,7 +99,7 @@ def __init__(self, workspace, read_options): tmin -= t_off + t_mult * wl_min tmax -= t_off + t_mult * wl_max - if self.read_options['is_auto_tof_finder'] or self.tof_range is None: + if self.read_options["is_auto_tof_finder"] or self.tof_range is None: autotmin = tmin autotmax = tmax else: @@ -108,15 +109,15 @@ def __init__(self, workspace, read_options): self.tof_range_auto = [autotmin, autotmax] # microS self.tof_range_auto_with_margin = [tmin, tmax] # microS self.tof_range = [autotmin, autotmax] # for the first time, initialize tof_range like auto (microS) - self.binning = [tmin, self.read_options['bins'], tmax] + self.binning = [tmin, self.read_options["bins"], tmax] self.calculate_lambda_range() self.q_range = self.calculate_q_range() self.incident_angle = self.calculate_theta(False) # Proton charge - _proton_charge = float(mt_run.getProperty('gd_prtn_chrg').value) + _proton_charge = float(mt_run.getProperty("gd_prtn_chrg").value) # _proton_charge_units = mt_run.getProperty('gd_prtn_chrg').units - new_proton_charge_units = 'mC' + new_proton_charge_units = "mC" self.proton_charge = _proton_charge * 3.6 # to go from microA/h to mC self.proton_charge_units = new_proton_charge_units @@ -130,12 +131,12 @@ def __init__(self, workspace, read_options): self.data_loaded = False self._read_data(workspace) - if self.read_options['is_auto_peak_finder']: + if self.read_options["is_auto_peak_finder"]: pf = PeakFinderDerivation(list(range(len(self.ycountsdata))), self.ycountsdata) [peak1, peak2] = pf.getPeaks() self.peak = [str(peak1), str(peak2)] - backOffsetFromPeak = self.read_options['back_offset_from_peak'] + backOffsetFromPeak = self.read_options["back_offset_from_peak"] back1 = int(peak1 - backOffsetFromPeak) back2 = int(peak2 + backOffsetFromPeak) self.back = [str(back1), str(back2)] @@ -221,9 +222,9 @@ def calculate_theta(self, with_offset=True): thi_units = self.thi_units # Make sure we have radians - if thi_units == 'degree': + if thi_units == "degree": thi_value *= math.pi / 180.0 - if tthd_units == 'degree': + if tthd_units == "degree": tthd_value *= math.pi / 180.0 theta = math.fabs(tthd_value - thi_value) / 2.0 @@ -233,7 +234,7 @@ def calculate_theta(self, with_offset=True): # Add the offset angle_offset = 0.0 if with_offset and "angle_offset" in self.read_options: - angle_offset = float(self.read_options['angle_offset']) + angle_offset = float(self.read_options["angle_offset"]) angle_offset_deg = angle_offset return theta + angle_offset_deg * math.pi / 180.0 diff --git a/RefRed/sf_calculator/reduction_sf_calculator.py b/RefRed/sf_calculator/reduction_sf_calculator.py index 1e5ca004..25600703 100644 --- a/RefRed/sf_calculator/reduction_sf_calculator.py +++ b/RefRed/sf_calculator/reduction_sf_calculator.py @@ -1,12 +1,12 @@ # standard-library imports -import sys import logging +import sys import time from typing import Optional, Union # third-party imports import numpy as np -from qtpy.QtWidgets import QApplication, QMessageBox, QFileDialog +from qtpy.QtWidgets import QApplication, QFileDialog, QMessageBox # RefRed imports from RefRed.utilities import convertTOF @@ -127,7 +127,7 @@ def _handle_request(self): tof_range=tof_range, ) - with open(self.export_script_file, 'w') as fd: + with open(self.export_script_file, "w") as fd: fd.write(script) self.sf_gui.updateProgressBar(float(i + 1) / float(nbr_scripts)) @@ -216,19 +216,19 @@ def generate_script( mantid_call = [ r"mantid_algorithm_exec(", r" LRScalingFactors.LRScalingFactors,", - r" DirectBeamRuns={0},".format(run_list), - r" IncidentMedium='{0}',".format(incident_medium), - r" Attenuators={0},".format(attenuators), - r" TOFRange={0},".format(tof_range), - r" TOFSteps={0},".format(self.sf_gui.deadtime_tof_step), - r" SignalPeakPixelRange={0},".format(peak_ranges), - r" SignalBackgroundPixelRange={0},".format(bck_ranges), - r" LowResolutionPixelRange={0},".format(low_res_ranges), - r" ScalingFactorFile='{0}',".format(output_file_name), - r" UseDeadTimeCorrection={0},".format(self.sf_gui.apply_deadtime), - r" ParalyzableDeadTime={0},".format(self.sf_gui.paralyzable_deadtime), - r" DeadTime={0},".format(self.sf_gui.deadtime_value), - r" DeadTimeTOFStep={0},".format(self.sf_gui.deadtime_tof_step), + rf" DirectBeamRuns={run_list},", + rf" IncidentMedium='{incident_medium}',", + rf" Attenuators={attenuators},", + rf" TOFRange={tof_range},", + rf" TOFSteps={self.sf_gui.deadtime_tof_step},", + rf" SignalPeakPixelRange={peak_ranges},", + rf" SignalBackgroundPixelRange={bck_ranges},", + rf" LowResolutionPixelRange={low_res_ranges},", + rf" ScalingFactorFile='{output_file_name}',", + rf" UseDeadTimeCorrection={self.sf_gui.apply_deadtime},", + rf" ParalyzableDeadTime={self.sf_gui.paralyzable_deadtime},", + rf" DeadTime={self.sf_gui.deadtime_value},", + rf" DeadTimeTOFStep={self.sf_gui.deadtime_tof_step},", r")", ] script += "\n".join(mantid_call) + "\n" diff --git a/RefRed/sf_calculator/sf_calculator.py b/RefRed/sf_calculator/sf_calculator.py index 0712b231..7a0c8250 100644 --- a/RefRed/sf_calculator/sf_calculator.py +++ b/RefRed/sf_calculator/sf_calculator.py @@ -1,33 +1,33 @@ """ - Scaling factor calculator - TODO: This need major cleanup +Scaling factor calculator +TODO: This need major cleanup """ -import sys +import logging import os +import sys +import time from pathlib import Path -from qtpy import QtGui, QtCore, QtWidgets -from qtpy.QtWidgets import QFileDialog + import numpy as np -import logging -import time +from qtpy import QtCore, QtGui, QtWidgets +from qtpy.QtWidgets import QFileDialog -from RefRed import ORGANIZATION, APPNAME import RefRed.colors +from RefRed import APPNAME, ORGANIZATION +from RefRed.calculations.run_sequence_breaker import RunSequenceBreaker from RefRed.interfaces import load_ui from RefRed.interfaces.deadtime_settings import DeadTimeSettingsView +from RefRed.sf_calculator.check_sf_run_reduction_button_status import ( + CheckSfRunReductionButtonStatus, +) from RefRed.sf_calculator.fill_sf_gui_table import FillSFGuiTable from RefRed.sf_calculator.incident_medium_list_editor import IncidentMediumListEditor from RefRed.sf_calculator.load_and_sort_nxsdata_for_sf_calculator import ( LoadAndSortNXSDataForSFcalculator, ) -from RefRed.sf_calculator.check_sf_run_reduction_button_status import ( - CheckSfRunReductionButtonStatus, -) from RefRed.sf_calculator.reduction_sf_calculator import ReductionSfCalculator from RefRed.sf_calculator.sf_calculator_right_click import SFCalculatorRightClick - -from RefRed.calculations.run_sequence_breaker import RunSequenceBreaker from RefRed.utilities import convert_tof_values_unit @@ -1058,6 +1058,6 @@ def show_dead_time_dialog(self): dt_settings.exec_() # Store dead time options - self.paralyzable_deadtime = dt_settings.options['paralyzable'] - self.deadtime_value = dt_settings.options['dead_time'] - self.deadtime_tof_step = dt_settings.options['tof_step'] + self.paralyzable_deadtime = dt_settings.options["paralyzable"] + self.deadtime_value = dt_settings.options["dead_time"] + self.deadtime_tof_step = dt_settings.options["tof_step"] diff --git a/RefRed/sf_calculator/sort_nxsdata.py b/RefRed/sf_calculator/sort_nxsdata.py index fe722c14..d930be57 100644 --- a/RefRed/sf_calculator/sort_nxsdata.py +++ b/RefRed/sf_calculator/sort_nxsdata.py @@ -1,4 +1,5 @@ import logging + from RefRed.sf_calculator.compare_two_nxsdata_for_sfcalculator import CompareTwoNXSDataForSFcalculator @@ -9,7 +10,6 @@ class Position(object): class SortNXSData(object): - sortedArrayOfNXSData = None sf_gui = None diff --git a/RefRed/sf_preview/sf_file_handler.py b/RefRed/sf_preview/sf_file_handler.py index e574e51c..a96d3c39 100644 --- a/RefRed/sf_preview/sf_file_handler.py +++ b/RefRed/sf_preview/sf_file_handler.py @@ -1,9 +1,9 @@ import numpy as np + from RefRed.status_message_handler import StatusMessageHandler class SFFileHandler(object): - full_sf_factor_table = [] full_sf_factor_labels = [] nbr_row = -1 diff --git a/RefRed/sf_preview/sf_preview.py b/RefRed/sf_preview/sf_preview.py index 25ad8d63..ac666cc2 100644 --- a/RefRed/sf_preview/sf_preview.py +++ b/RefRed/sf_preview/sf_preview.py @@ -1,11 +1,11 @@ -from qtpy import QtWidgets import numpy as np +from qtpy import QtWidgets + from RefRed.interfaces import load_ui from RefRed.sf_preview.sf_file_handler import SFFileHandler class SFPreview(QtWidgets.QMainWindow): - col_width = 100 col_width1 = col_width + 50 column_widths = [ @@ -21,14 +21,14 @@ class SFPreview(QtWidgets.QMainWindow): col_width1, ] - def __init__(self, parent=None, filename=''): + def __init__(self, parent=None, filename=""): self.parent = parent QtWidgets.QMainWindow.__init__(self, parent=parent) self.ui = load_ui("sf_preview_interface.ui", self) filename = self.parent.full_scaling_factor_file_name - if filename == '': + if filename == "": return self.filename = filename diff --git a/RefRed/status_message_handler.py b/RefRed/status_message_handler.py index 9df758fc..213dde1c 100644 --- a/RefRed/status_message_handler.py +++ b/RefRed/status_message_handler.py @@ -1,10 +1,12 @@ """ - TODO: refactor this +TODO: refactor this """ import sys import time + from qtpy import QtCore + from RefRed.utilities import get_index_free_thread @@ -16,7 +18,7 @@ def setup(self, parent): def run(self): time.sleep(5) try: - self.parent.ui.statusbar.showMessage('') + self.parent.ui.statusbar.showMessage("") except RuntimeError: # race condition: pytest-qt fixture qtbot kills the main window but fails to kill this thread. # As a result, after five seconds there's no self.parent and the previous line raises @@ -24,12 +26,12 @@ def run(self): class StatusMessageHandler(object): - def __init__(self, parent=None, message='', severity='good', is_threaded=True): + def __init__(self, parent=None, message="", severity="good", is_threaded=True): self.parent = parent - if severity == 'good': + if severity == "good": self.parent.ui.statusbar.setStyleSheet("QStatusBar{color: black;}") - elif severity == 'bad': + elif severity == "bad": self.parent.ui.statusbar.setStyleSheet("QStatusBar{color: red;}") self.parent.ui.statusbar.showMessage(message) diff --git a/RefRed/thread/locate_run.py b/RefRed/thread/locate_run.py index 2b184862..eded7f9f 100644 --- a/RefRed/thread/locate_run.py +++ b/RefRed/thread/locate_run.py @@ -1,4 +1,5 @@ from qtpy import QtCore + import RefRed.nexus_utilities @@ -12,9 +13,9 @@ def run(self): try: full_file_name = RefRed.nexus_utilities.findNeXusFullPath(self.run_number) except: - full_file_name = '' + full_file_name = "" - if full_file_name == '': + if full_file_name == "": self.parent.number_of_runs = self.parent.number_of_runs - 1 self.parent.list_nxs.pop() else: diff --git a/RefRed/utilities.py b/RefRed/utilities.py index 48328435..59163d8d 100644 --- a/RefRed/utilities.py +++ b/RefRed/utilities.py @@ -1,10 +1,12 @@ import math import os -import numpy as np from random import randint -from RefRed import nexus_utilities from typing import Union +import numpy as np + +from RefRed import nexus_utilities + def convert_angle(angle=0, from_units="degree", to_units="rad"): """ @@ -52,9 +54,7 @@ def convertTOF(TOFarray=None, from_units="micros", to_units="ms"): return None -def convert_tof_values_unit( - tof_array: Union[None, list, np.ndarray], from_units: str = "micros", to_units: str = "ms" -): +def convert_tof_values_unit(tof_array: Union[None, list, np.ndarray], from_units: str = "micros", to_units: str = "ms"): """Convert an array, supposed to be TOF values, from one unit to another Parameters @@ -80,9 +80,9 @@ def multiply_by_value(array, value: Union[float, int]): return array # Check input and output units - allowed_units = ['micros', 'ms'] + allowed_units = ["micros", "ms"] if from_units not in allowed_units or to_units not in allowed_units: - raise NameError(f'Input and output units can be micros and ms only but ' f'not {from_units} or {to_units}') + raise NameError(f"Input and output units can be micros and ms only but not {from_units} or {to_units}") if tof_array is None or from_units == to_units: # case 1: None input or @@ -97,7 +97,7 @@ def multiply_by_value(array, value: Union[float, int]): # convert from ms to micros return multiply_by_value(tof_array, 1000) - raise RuntimeError('Impossible') + raise RuntimeError("Impossible") def output_2d_ascii_file(filename, image): diff --git a/create_graph.py b/create_graph.py index 4e25c2e0..fe14a975 100644 --- a/create_graph.py +++ b/create_graph.py @@ -1,12 +1,13 @@ #!/usr/bin/env python -''' +""" Create and format a dependency graph for the project. -''' -from subprocess import Popen, PIPE +""" + +from subprocess import PIPE, Popen # create the graph file -result_1 = Popen(['sfood', 'quicknxs'], stdout=PIPE).communicate()[0] -dot = Popen(['sfood-graph'], stdout=PIPE, stdin=PIPE).communicate(result_1)[0] +result_1 = Popen(["sfood", "quicknxs"], stdout=PIPE).communicate()[0] +dot = Popen(["sfood-graph"], stdout=PIPE, stdin=PIPE).communicate(result_1)[0] # process result dot file data @@ -17,23 +18,23 @@ for line in dot.splitlines(): if ( line.startswith('"quicknxs"') - or 'version' in line + or "version" in line or '"logging"' in line - or 'sip' in line - or 'figureoptions' in line - or 'types' in line - or 'nxutils.so' in line - or 'output_templates' in line - or 'os' in line - or 'sys' in line + or "sip" in line + or "figureoptions" in line + or "types" in line + or "nxutils.so" in line + or "output_templates" in line + or "os" in line + or "sys" in line ): continue elif line.startswith('"quicknxs/'): - line = line.replace('style=filled', 'style=filled, color="#00aa00" shape=box, fontsize=24').replace( - 'quicknxs/', '' + line = line.replace("style=filled", 'style=filled, color="#00aa00" shape=box, fontsize=24').replace( + "quicknxs/", "" ) - if 'PyQt4' in line or 'email' in line or 'scipy' in line or 'matplotlib/' in line or 'IPython' in line: - line = line.split('/')[0] + '";' + if "PyQt4" in line or "email" in line or "scipy" in line or "matplotlib/" in line or "IPython" in line: + line = line.split("/")[0] + '";' if first_add: first_add = False out_dot.append('"PyQt4" [style=filled, color="#aa0000", fontsize=36];') @@ -43,28 +44,28 @@ out_dot.append('"IPython" [style=filled, color="#aaaa00", fontsize=24];') out_dot.append('"h5py" [style=filled, color="#aaffaa", fontsize=32];') for sys_module in [ - 'glob', - 'subprocess', - 'multiprocessing', - 'traceback', - 'zipfile', - 'StringIO', - 'cPickle', - 'atexit', - 'tempfile', - 'getpass', - 'time', - 'copy', - 'inspect', - 'email', - 'smtplib', - 'ConfigParser', - 'errno', + "glob", + "subprocess", + "multiprocessing", + "traceback", + "zipfile", + "StringIO", + "cPickle", + "atexit", + "tempfile", + "getpass", + "time", + "copy", + "inspect", + "email", + "smtplib", + "ConfigParser", + "errno", ]: out_dot.append('"%s" [shape=hexagon, fontsize=18];' % sys_module) - line = line.replace('pylab', 'matplotlib').replace('cStringIO', 'StringIO') - out_dot.append(line.replace('.py', '')) + line = line.replace("pylab", "matplotlib").replace("cStringIO", "StringIO") + out_dot.append(line.replace(".py", "")) -out_dot = '\n'.join(out_dot) +out_dot = "\n".join(out_dot) -Popen(['dot', '-Tps', '-o', 'import_graph.ps'], stdout=PIPE, stdin=PIPE).communicate(out_dot) +Popen(["dot", "-Tps", "-o", "import_graph.ps"], stdout=PIPE, stdin=PIPE).communicate(out_dot) diff --git a/docs/conf.py b/docs/conf.py index 52ef2647..ee7f36b8 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -13,14 +13,14 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys import os +import sys # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. -sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath(".")) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() @@ -41,30 +41,30 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.doctest', - 'sphinx.ext.todo', - 'sphinx.ext.coverage', - 'sphinx.ext.mathjax', - 'sphinx.ext.viewcode', - 'sphinx.ext.intersphinx', + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx.ext.mathjax", + "sphinx.ext.viewcode", + "sphinx.ext.intersphinx", ] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = {'.rst': 'restructuredtext'} +source_suffix = {".rst": "restructuredtext"} # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'RefRed' -copyright = u"2017, Jose Borreguero" +project = "RefRed" +copyright = "2017, Jose Borreguero" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout @@ -87,7 +87,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -105,10 +105,10 @@ # show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # some of the Python built-ins do no resolve correctly -nitpick_ignore = [('py:class', 'list')] +nitpick_ignore = [("py:class", "list")] # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] @@ -122,7 +122,7 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'sphinx_rtd_theme' # 'alabaster' +html_theme = "sphinx_rtd_theme" # 'alabaster' # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the @@ -199,7 +199,7 @@ # html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'refreddoc' +htmlhelp_basename = "refreddoc" # -- Options for LaTeX output ------------------------------------------ @@ -217,7 +217,7 @@ # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ - ('index', 'refred.tex', u'RefRed Developers Documentation', u'ORNL - Software Engineering Group', 'manual'), + ("index", "refred.tex", "RefRed Developers Documentation", "ORNL - Software Engineering Group", "manual"), ] # The name of an image file (relative to this directory) to place at @@ -245,7 +245,7 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [('index', 'refred', u'RefRed Developers Documentation', [u'ORNL - Software Engineering Group'], 1)] +man_pages = [("index", "refred", "RefRed Developers Documentation", ["ORNL - Software Engineering Group"], 1)] # If true, show URL addresses after external links. # man_show_urls = False @@ -258,13 +258,13 @@ # dir menu entry, description, category) texinfo_documents = [ ( - 'index', - 'refred', - u'RefRed Developers Documentation', - u'ORNL - Software Engineering Group', - 'refred', - 'Liquids Reflectometer Data Reduction Software.', - 'Miscellaneous', + "index", + "refred", + "RefRed Developers Documentation", + "ORNL - Software Engineering Group", + "refred", + "Liquids Reflectometer Data Reduction Software.", + "Miscellaneous", ), ] @@ -282,13 +282,13 @@ # Domains for intersphinx inventory file objects.inv intersphinx_mapping = { - 'lmfit': ('https://lmfit.github.io/lmfit-py', None), - 'matplotlib': ('https://matplotlib.org', None), - 'numpy': ('http://docs.scipy.org/doc/numpy', None), - 'python': ('https://docs.python.org/{}'.format(sys.version_info[0]), None), - 'scipy': ('https://docs.scipy.org/doc/scipy/reference', None), - 'pytest': ('https://docs.pytest.org/en/latest', None), + "lmfit": ("https://lmfit.github.io/lmfit-py", None), + "matplotlib": ("https://matplotlib.org", None), + "numpy": ("http://docs.scipy.org/doc/numpy", None), + "python": (f"https://docs.python.org/{sys.version_info[0]}", None), + "scipy": ("https://docs.scipy.org/doc/scipy/reference", None), + "pytest": ("https://docs.pytest.org/en/latest", None), } # Suppress certain warnings -suppress_warnings = ['image.nonlocal_uri'] +suppress_warnings = ["image.nonlocal_uri"] diff --git a/scripts/start_refred.py b/scripts/start_refred.py index b2a91e71..254277a7 100755 --- a/scripts/start_refred.py +++ b/scripts/start_refred.py @@ -1,22 +1,23 @@ #!/usr/bin/env python -''' - Small program for quick access to SNS liquids reflectometer raw data. -''' +""" +Small program for quick access to SNS liquids reflectometer raw data. +""" + import os import sys # import mantid once before qt, this fixes some issues with running in production import mantid # noqa: F401 +from qtpy.QtCore import Qt # type: ignore +from qtpy.QtGui import QPixmap # must be imported through qtpy before any other gui imports from qtpy.QtWidgets import QApplication, QSplashScreen -from qtpy.QtGui import QPixmap -from qtpy.QtCore import Qt # type: ignore # if script was run from commandline try: current_directory = os.path.dirname(os.path.abspath(__file__)) - if current_directory.endswith('RefRed/scripts'): + if current_directory.endswith("RefRed/scripts"): sys.path.insert(0, os.path.dirname(current_directory)) except NameError: pass @@ -24,7 +25,7 @@ def _run(argv=[]): app = QApplication(argv) - splash = QSplashScreen(QPixmap(':/General/logo_refl_hq.png')) + splash = QSplashScreen(QPixmap(":/General/logo_refl_hq.png")) splash.showMessage( """
 
@@ -45,7 +46,7 @@ def _run(argv=[]): return app.exec_() -if __name__ == '__main__': +if __name__ == "__main__": # from RefRed import config from RefRed import __version__ as version from RefRed.main import MainGui diff --git a/scripts/sync_dependencies.py b/scripts/sync_dependencies.py index e6b057aa..bb3f636e 100644 --- a/scripts/sync_dependencies.py +++ b/scripts/sync_dependencies.py @@ -15,8 +15,8 @@ def check_dependencies_synced(): reqs_env = open(os.path.join(repo_dir, "requirements.txt"), "r").read() # check for LiquidsReflectometer versions - lr_conda = re.search(r'LiquidsReflectometer\.git@([^#]+)', conda_env).group(1) - lr_reqs = re.search(r'LiquidsReflectometer\.git@([^#]+)', reqs_env).group(1) + lr_conda = re.search(r"LiquidsReflectometer\.git@([^#]+)", conda_env).group(1) + lr_reqs = re.search(r"LiquidsReflectometer\.git@([^#]+)", reqs_env).group(1) if lr_conda != lr_reqs: raise RuntimeError("environment.yml and requirements.txt ask different versions of LiquidsReflectometer") diff --git a/setup.py b/setup.py index ccf8e891..81fe7918 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,7 @@ import os + from setuptools import setup + import versioneer THIS_DIR = os.path.dirname(__file__) @@ -13,51 +15,51 @@ def read_requirements_from_file(filepath): :param str filepath: Path to the file to read :return List[str]: """ - with open(filepath, 'r') as req_file: + with open(filepath, "r") as req_file: return req_file.readlines() -install_requires = read_requirements_from_file(os.path.join(THIS_DIR, 'requirements.txt')) +install_requires = read_requirements_from_file(os.path.join(THIS_DIR, "requirements.txt")) # TODO can this be safely substituted with setuptools.find_packages? __packages__ = [ - 'RefRed', - 'RefRed.autopopulatemaintable', - 'RefRed.configuration', - 'RefRed.calculations', - 'RefRed.config', - 'RefRed.export', - 'RefRed.gui_handling', - 'RefRed.icons', - 'RefRed.initialization', - 'RefRed.interfaces', - 'RefRed.load_reduced_data_set', - 'RefRed.low_res_finder_algorithms', - 'RefRed.metadata', - 'RefRed.peak_finder_algorithms', - 'RefRed.plot', - 'RefRed.preview_config', - 'RefRed.reduction', - 'RefRed.reduction_table_handling', - 'RefRed.settings', - 'RefRed.sf_calculator', - 'RefRed.sf_preview', - 'RefRed.thread', + "RefRed", + "RefRed.autopopulatemaintable", + "RefRed.configuration", + "RefRed.calculations", + "RefRed.config", + "RefRed.export", + "RefRed.gui_handling", + "RefRed.icons", + "RefRed.initialization", + "RefRed.interfaces", + "RefRed.load_reduced_data_set", + "RefRed.low_res_finder_algorithms", + "RefRed.metadata", + "RefRed.peak_finder_algorithms", + "RefRed.plot", + "RefRed.preview_config", + "RefRed.reduction", + "RefRed.reduction_table_handling", + "RefRed.settings", + "RefRed.sf_calculator", + "RefRed.sf_preview", + "RefRed.thread", ] setup( - name='RefRed', + name="RefRed", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), - description='Liquids Reflectometer Data Reduction Software', - license='GPL version 3.0', - scripts=['scripts/RefRed', 'scripts/start_refred.py'], - author='Jean Bilheux', - author_email='bilheuxjm@ornl.gov', + description="Liquids Reflectometer Data Reduction Software", + license="GPL version 3.0", + scripts=["scripts/RefRed", "scripts/start_refred.py"], + author="Jean Bilheux", + author_email="bilheuxjm@ornl.gov", packages=__packages__, - url='http://', + url="http://", zip_safe=False, package_dir={}, - package_data={'': ['*.ui', '*.png', '*.qrc']}, + package_data={"": ["*.ui", "*.png", "*.qrc"]}, install_requires=install_requires, ) diff --git a/test/conftest.py b/test/conftest.py index b8d7f0d0..98b065ec 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -1,17 +1,17 @@ # standard imports import os -from qtpy import QtCore, QtWidgets import sys -# 3rd-party imports -from mantid.simpleapi import config import pytest +# 3rd-party imports +from mantid.simpleapi import config +from qtpy import QtCore, QtWidgets this_module_path = sys.modules[__name__].__file__ -@pytest.fixture(scope='session') +@pytest.fixture(scope="session") def data_server(): r"""Object containing info and functionality for data files Also, it adds the data directory to the list of Mantid data directories @@ -22,7 +22,7 @@ def data_server(): class _DataServe(object): def __init__(self): - self._directory = os.path.join(os.path.dirname(this_module_path), 'data') + self._directory = os.path.join(os.path.dirname(this_module_path), "data") config.appendDataSearchDir(self._directory) config["default.facility"] = "SNS" config["default.instrument"] = "REF_L" diff --git a/test/test_fixtures.py b/test/test_fixtures.py index 5bca16d3..13248f0a 100644 --- a/test/test_fixtures.py +++ b/test/test_fixtures.py @@ -1,15 +1,15 @@ # third party packages -import pytest - # standard packages from pathlib import Path +import pytest + def test_data_server(data_server): - assert Path(data_server.path_to('easy_data_set.csv')).exists() + assert Path(data_server.path_to("easy_data_set.csv")).exists() with pytest.raises(FileNotFoundError): - Path(data_server.path_to('impossibe_to_find.dat')).exists() + Path(data_server.path_to("impossibe_to_find.dat")).exists() -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/test_template.py b/test/test_template.py index 051e09c6..11070fc0 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -1,6 +1,6 @@ # third party packages -from numpy.testing import assert_allclose import pytest # PYTEST documentation at https://docs.pytest.org/ +from numpy.testing import assert_allclose # Helper functions to showcase some features of pytest @@ -25,7 +25,7 @@ def raises_exception(a, b): try: c = a / b # will raise an exception if b == 0.0 except ZeroDivisionError: - raise ZeroDivisionError('Do not divide by zero, please') # custom message + raise ZeroDivisionError("Do not divide by zero, please") # custom message return c @@ -50,17 +50,17 @@ def test_raises_exception(self): r"""How to test when your code is throwing an exception""" with pytest.raises(ZeroDivisionError) as exception_info: raises_exception(1.0, 0.0) # divide by zero raises exception - assert 'Do not divide by zero' in str(exception_info.value) # checks part of the error message + assert "Do not divide by zero" in str(exception_info.value) # checks part of the error message def test_read_file(self, data_server): # 'data_server' is a magic pytest fixture. See file conftest.py r"""Using data files located within directory tests/data/""" # read file tests/data/test_file_1.dat - path_to_file = data_server.path_to('easy_data_set.csv') - assert '285,3,1.732050808' in read_file(path_to_file) + path_to_file = data_server.path_to("easy_data_set.csv") + assert "285,3,1.732050808" in read_file(path_to_file) # read file tests/data/examples/test_file_2.dat # path_to_file = data_server.path_to('examples/test_file_2.dat') # assert 'Bye World!' in read_file(path_to_file) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/ui/test_basic_startup.py b/test/ui/test_basic_startup.py index af646bc7..00d42277 100644 --- a/test/ui/test_basic_startup.py +++ b/test/ui/test_basic_startup.py @@ -1,13 +1,15 @@ -from RefRed.main import MainGui -from qtpy import QtCore, QtWidgets import functools + import pytest +from qtpy import QtCore, QtWidgets + +from RefRed.main import MainGui wait = 200 def test_startup(qtbot): - pytest.importorskip('mantid') + pytest.importorskip("mantid") window = MainGui() qtbot.addWidget(window) diff --git a/test/ui/test_compute_scaling_factors.py b/test/ui/test_compute_scaling_factors.py index ec91eace..599d7eb5 100644 --- a/test/ui/test_compute_scaling_factors.py +++ b/test/ui/test_compute_scaling_factors.py @@ -1,17 +1,17 @@ # standard imports -import random import os +import random import string from unittest.mock import patch as mock_patch +import pytest + # third party imports from qtpy import QtCore -import pytest # RefRed imports from RefRed.main import MainGui - SECOND = 1000 # 1000 miliseconds @@ -42,7 +42,7 @@ def test_sf_calculator(qtbot, data_server, run_set, run_count, script_file): # Generate the structure factors # sfc._save_directory = "/tmp" # force the location of saving directory - file_name = ''.join([random.choice(string.ascii_letters) for i in range(10)]) + ".cfg" + file_name = "".join([random.choice(string.ascii_letters) for i in range(10)]) + ".cfg" with mock_patch("RefRed.sf_calculator.sf_calculator.QFileDialog.getSaveFileName") as mock_getSaveFileName: mock_getSaveFileName.return_value = os.path.join(sfc._save_directory, file_name), "" qtbot.mouseClick(sfc.sfFileNameBrowseButton, QtCore.Qt.LeftButton) @@ -54,17 +54,15 @@ def test_sf_calculator(qtbot, data_server, run_set, run_count, script_file): # Compare the contents of the file preview and the actual saved file cfg_file = os.path.join(sfc._save_directory, file_name) cfg = sfc.sfFileNamePreview.toPlainText() - contents = open(cfg_file, 'r').read() + contents = open(cfg_file, "r").read() assert cfg == contents os.remove(cfg_file) # # Export Python Script # - file_name = ''.join([random.choice(string.ascii_letters) for i in range(10)]) + ".py" - with mock_patch( - "RefRed.sf_calculator.reduction_sf_calculator.QFileDialog.getSaveFileName" - ) as mock_getSaveFileName: + file_name = "".join([random.choice(string.ascii_letters) for i in range(10)]) + ".py" + with mock_patch("RefRed.sf_calculator.reduction_sf_calculator.QFileDialog.getSaveFileName") as mock_getSaveFileName: mock_getSaveFileName.return_value = os.path.join(sfc._save_directory, file_name), "" qtbot.mouseClick(sfc.exportButton, QtCore.Qt.LeftButton) @@ -73,7 +71,7 @@ def test_sf_calculator(qtbot, data_server, run_set, run_count, script_file): # compare the contents of the script def to_compare(filename): # Load the script and compare lines that are not expected to change. - content = '\n'.join(open(filename, "r").read().split('\n')[8:16]) + content = "\n".join(open(filename, "r").read().split("\n")[8:16]) return content cfg_file = os.path.join(sfc._save_directory, file_name) @@ -81,5 +79,5 @@ def to_compare(filename): os.remove(cfg_file) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/ui/test_plot2d_dialog.py b/test/ui/test_plot2d_dialog.py index 77daf944..e1c42e8a 100644 --- a/test/ui/test_plot2d_dialog.py +++ b/test/ui/test_plot2d_dialog.py @@ -87,5 +87,5 @@ def mock_file_dialog_returns(self): qtbot.wait(wait) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/ui/test_popup_plot_1d.py b/test/ui/test_popup_plot_1d.py index 404f1b52..7bf54cf6 100644 --- a/test/ui/test_popup_plot_1d.py +++ b/test/ui/test_popup_plot_1d.py @@ -5,9 +5,10 @@ import pytest from qtpy import QtCore +from RefRed.main import MainGui + # RefRed imports from RefRed.plot.popup_plot_1d import PopupPlot1d -from RefRed.main import MainGui def test_popup_plot_1d(qtbot, data_server): @@ -72,5 +73,5 @@ def assert_boundary(boundary, spinbox, value, old_value=None): assert_boundary("background right boundary", popup.ui.plotBackToSpinBox, 145, old_value=144) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/ui/test_reduce_and_export_data.py b/test/ui/test_reduce_and_export_data.py index 8117c116..20c16ed0 100644 --- a/test/ui/test_reduce_and_export_data.py +++ b/test/ui/test_reduce_and_export_data.py @@ -5,13 +5,13 @@ # third-party imports import numpy as np -from qtpy import QtCore import pytest +from qtpy import QtCore -# RefRed imports -from RefRed.main import MainGui from RefRed.configuration.loading_configuration import LoadingConfiguration +# RefRed imports +from RefRed.main import MainGui wait = 200 @@ -68,7 +68,6 @@ @pytest.mark.parametrize("case", test_cases) def test_reduce_and_export_data(qtbot, tmp_path, data_server, case): - # set the current working directory as the root of the repo. Required because the path of scaling factor file # stored in the template file is 'test/data/sf_186529_Si_auto.cfg', thus relative to the root of the repo. os.chdir(Path(data_server.directory).parent.parent) @@ -129,7 +128,7 @@ def test_reduce_and_export_data(qtbot, tmp_path, data_server, case): expected_script = open(data_server.path_to(case["script"])).readlines() for value, expected in zip(reduction_script, expected_script): - if value.startswith('#') or value.startswith('reduction_pars'): + if value.startswith("#") or value.startswith("reduction_pars"): continue assert value.strip() == expected.strip() @@ -148,13 +147,13 @@ def compare_results(results_file, expected_results_file, tmp_path): ): continue - if value.startswith('# # 188'): - value_arr = value.replace('#', '').strip().split() - expected_arr = expected.replace('#', '').strip().split() + if value.startswith("# # 188"): + value_arr = value.replace("#", "").strip().split() + expected_arr = expected.replace("#", "").strip().split() for i in range(2): # DataRun and NormRun assert value_arr[i] == expected_arr[i] np.testing.assert_allclose(np.array(value_arr[2:], dtype=float), np.array(expected_arr[2:], dtype=float)) - elif value.startswith('#'): + elif value.startswith("#"): assert value.strip() == expected.strip() else: np.testing.assert_allclose(np.array(value.split(), dtype=float), np.array(expected.split(), dtype=float)) @@ -171,5 +170,5 @@ def export_ascii(qtbot, window, results_file): qtbot.wait(wait) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/ui/test_scaling_factors_preview.py b/test/ui/test_scaling_factors_preview.py index 4e95123e..71a30427 100644 --- a/test/ui/test_scaling_factors_preview.py +++ b/test/ui/test_scaling_factors_preview.py @@ -2,14 +2,15 @@ import os from unittest.mock import patch as mock_patch +import pytest + # third-party imports from qtpy import QtCore -import pytest -# RefRed imports -from RefRed.sf_preview.sf_preview import SFPreview from RefRed.main import MainGui +# RefRed imports +from RefRed.sf_preview.sf_preview import SFPreview SECOND = 1000 # 1000 miliseconds @@ -52,5 +53,5 @@ def mock_open_file(*args, **kwargs): assert sf_preview.ui.table_widget.item(4, 4).data(0) == "12.487" -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/calculations/test_load_nexus.py b/test/unit/RefRed/calculations/test_load_nexus.py index 973d0e4c..40ee7325 100644 --- a/test/unit/RefRed/calculations/test_load_nexus.py +++ b/test/unit/RefRed/calculations/test_load_nexus.py @@ -1,10 +1,10 @@ # package imports -from RefRed.calculations.load_nexus import LoadNexus - # third party imports import pytest from mantid.simpleapi import mtd +from RefRed.calculations.load_nexus import LoadNexus + class TestLoadNexus(object): def test_load_nexus(self, data_server): diff --git a/test/unit/RefRed/calculations/test_run_sequence_breaker.py b/test/unit/RefRed/calculations/test_run_sequence_breaker.py index f3bfe449..d591e045 100644 --- a/test/unit/RefRed/calculations/test_run_sequence_breaker.py +++ b/test/unit/RefRed/calculations/test_run_sequence_breaker.py @@ -1,4 +1,5 @@ import pytest + from RefRed.calculations.run_sequence_breaker import RunSequenceBreaker @@ -10,7 +11,7 @@ def test_run_sequence_breaker(): Expected result is obtained by RefRed-production release (python 2.7 version) """ # Test input - test_run_sequence = '184975-184989' + test_run_sequence = "184975-184989" gold_run_list = [ 184975, 184976, @@ -39,5 +40,5 @@ def test_run_sequence_breaker(): assert final_list == gold_run_list -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/configuration/test_export_xml_config.py b/test/unit/RefRed/configuration/test_export_xml_config.py index f71b9b0a..8a558a96 100644 --- a/test/unit/RefRed/configuration/test_export_xml_config.py +++ b/test/unit/RefRed/configuration/test_export_xml_config.py @@ -20,8 +20,8 @@ def test_header_part(self, mantid_mock, refred_mock): assert len(config.str_array) == 7 header = "".join(config.str_array) assert datetime.now().strftime("%A, %d. %B %Y %I:%M%p") in header - assert '1.0.0' in header - assert 'RefRed-2.0.0' in header + assert "1.0.0" in header + assert "RefRed-2.0.0" in header def test_main_part(self): config = ExportXMLConfig(MagicMock()) diff --git a/test/unit/RefRed/configuration/test_loading_configuration.py b/test/unit/RefRed/configuration/test_loading_configuration.py index 9e322567..290c657b 100644 --- a/test/unit/RefRed/configuration/test_loading_configuration.py +++ b/test/unit/RefRed/configuration/test_loading_configuration.py @@ -1,7 +1,8 @@ # third party packages -import pytest import unittest.mock as mock +import pytest + # RefRed imports from RefRed.configuration.loading_configuration import LoadingConfiguration from RefRed.tabledata import TableData @@ -9,7 +10,7 @@ class TestLoadingConfiguration(object): def test_init(self): - with mock.patch('RefRed.configuration.loading_configuration.StatusMessageHandler') as mockStatusMessageHandler: + with mock.patch("RefRed.configuration.loading_configuration.StatusMessageHandler") as mockStatusMessageHandler: m = mock.Mock() loadingConfiguration = LoadingConfiguration(parent=m) mockStatusMessageHandler.assert_called() @@ -23,8 +24,8 @@ def test_init(self): ("", "File not found"), ], ) - @mock.patch('RefRed.configuration.loading_configuration.QFileDialog') - @mock.patch('RefRed.configuration.loading_configuration.StatusMessageHandler') + @mock.patch("RefRed.configuration.loading_configuration.QFileDialog") + @mock.patch("RefRed.configuration.loading_configuration.StatusMessageHandler") def test_run_file_search(self, StatusMessageHandlerMock, QFileDialogMock, filepath, message, data_server): def add_abspath(input_filepath): r"""helper to add the absolute path to file REF_L_188298_tiny_template.xml""" @@ -52,8 +53,8 @@ def add_abspath(input_filepath): loader.run() # test is the file is found StatusMessageHandlerMock.assert_called_with(parent=parent, message=message, is_threaded=True) - @mock.patch('RefRed.tabledata.TableData._validate_type') - @mock.patch('RefRed.configuration.loading_configuration.LoadingConfiguration.getMetadataObject') + @mock.patch("RefRed.tabledata.TableData._validate_type") + @mock.patch("RefRed.configuration.loading_configuration.LoadingConfiguration.getMetadataObject") def test_populate_big_table_data_with_lconfig(self, mockGetMetadataObject, mock_validate_type): mockGetMetadataObject.return_value = mock.Mock() mock_validate_type.return_value = None # don't check the type of elements when inserted in the table @@ -74,15 +75,15 @@ def test_populate_main_gui_general_settings(self): loadingConfiguration.parent.ui.selectIncidentMediumList.count.return_value = 2 values = { - 'q_step': 1.001, - 'q_min': 2.002, + "q_step": 1.001, + "q_min": 2.002, # Applying normalization is a global setting - 'norm_flag': True, - 'angle_offset': 2.5025, - 'angle_offset_error': 3.003, - 'scaling_factor_file': 'scaling_factor_file', - 'incident_medium_index_selected': 5.005, - 'scaling_factor_flag': 6.006, + "norm_flag": True, + "angle_offset": 2.5025, + "angle_offset_error": 3.003, + "scaling_factor_file": "scaling_factor_file", + "incident_medium_index_selected": 5.005, + "scaling_factor_flag": 6.006, } def side_effect(node, arg): @@ -129,34 +130,34 @@ def test_getMetadataObject(self): node_mock = mock.Mock() # mocks the Node instance associated to an XML block of an input configuration file values = { - 'from_peak_pixels': 1, - 'to_peak_pixels': 2, - 'back_roi1_from': 3, - 'back_roi1_to': 4, - 'x_min_pixel': 5.005, - 'x_max_pixel': 6.006, - 'background_flag': 'background_flag', - 'x_range_flag': 'x_range_flag', - 'from_tof_range': 7.007, - 'to_tof_range': 8.008, - 'from_q_range': 9.009, - 'to_q_range': 10.010, - 'from_lambda_range': 11.011, - 'to_lambda_range': 12.012, - 'data_sets': 'dataset1, dataset2', - 'tof_range_flag': 'tof_range_flag', - 'norm_from_peak_pixels': 13.013, - 'norm_to_peak_pixels': 14.014, - 'norm_from_back_pixels': 15.015, - 'norm_to_back_pixels': 16.016, - 'norm_dataset': 'normData1, normData2', - 'norm_x_min': 17.017, - 'norm_x_max': 18.018, - 'norm_background_flag': 'norm_background_flag', - 'norm_x_range_flag': 'norm_x_range_flag', - 'data_full_file_name': 'dataFullFileName1,dataFullFileName2', - 'norm_full_file_name': 'normFullFileName1,normFullFileName2', - 'const_q': True, + "from_peak_pixels": 1, + "to_peak_pixels": 2, + "back_roi1_from": 3, + "back_roi1_to": 4, + "x_min_pixel": 5.005, + "x_max_pixel": 6.006, + "background_flag": "background_flag", + "x_range_flag": "x_range_flag", + "from_tof_range": 7.007, + "to_tof_range": 8.008, + "from_q_range": 9.009, + "to_q_range": 10.010, + "from_lambda_range": 11.011, + "to_lambda_range": 12.012, + "data_sets": "dataset1, dataset2", + "tof_range_flag": "tof_range_flag", + "norm_from_peak_pixels": 13.013, + "norm_to_peak_pixels": 14.014, + "norm_from_back_pixels": 15.015, + "norm_to_back_pixels": 16.016, + "norm_dataset": "normData1, normData2", + "norm_x_min": 17.017, + "norm_x_max": 18.018, + "norm_background_flag": "norm_background_flag", + "norm_x_range_flag": "norm_x_range_flag", + "data_full_file_name": "dataFullFileName1,dataFullFileName2", + "norm_full_file_name": "normFullFileName1,normFullFileName2", + "const_q": True, } def side_effect(_, arg, default=""): @@ -168,13 +169,13 @@ def side_effect(_, arg, default=""): config = loader.getMetadataObject(node_mock) - assert config.data_peak[0] == values['from_peak_pixels'] - assert config.data_peak[1] == values['to_peak_pixels'] - assert config.data_back[0] == values['back_roi1_from'] - assert config.data_back[1] == values['back_roi1_to'] - assert config.data_low_res == [values['x_min_pixel'], values['x_max_pixel']] - assert config.const_q == values['const_q'] + assert config.data_peak[0] == values["from_peak_pixels"] + assert config.data_peak[1] == values["to_peak_pixels"] + assert config.data_back[0] == values["back_roi1_from"] + assert config.data_back[1] == values["back_roi1_to"] + assert config.data_low_res == [values["x_min_pixel"], values["x_max_pixel"]] + assert config.const_q == values["const_q"] -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/export/test_ascii_loader.py b/test/unit/RefRed/export/test_ascii_loader.py index 4dc177d5..90651307 100644 --- a/test/unit/RefRed/export/test_ascii_loader.py +++ b/test/unit/RefRed/export/test_ascii_loader.py @@ -1,11 +1,13 @@ # package imports -from RefRed.export import ascii_loader +import tempfile +from pathlib import Path + +import numpy as np # 3rd party imports import pytest -import tempfile -import numpy as np -from pathlib import Path + +from RefRed.export import ascii_loader class TestAsciiLoader: diff --git a/test/unit/RefRed/export/test_export_plot_ascii.py b/test/unit/RefRed/export/test_export_plot_ascii.py index 120502f2..5ed6ba89 100644 --- a/test/unit/RefRed/export/test_export_plot_ascii.py +++ b/test/unit/RefRed/export/test_export_plot_ascii.py @@ -1,13 +1,15 @@ # package imports -import RefRed -from RefRed.export import export_plot_ascii +import tempfile +import unittest.mock as mock +from pathlib import Path + +import numpy as np # 3rd party imports import pytest -import unittest.mock as mock -import tempfile -import numpy as np -from pathlib import Path + +import RefRed +from RefRed.export import export_plot_ascii class TestExportPlotAscii: diff --git a/test/unit/RefRed/export/test_reduced_ascii_loader.py b/test/unit/RefRed/export/test_reduced_ascii_loader.py index 1aecb83a..61361319 100644 --- a/test/unit/RefRed/export/test_reduced_ascii_loader.py +++ b/test/unit/RefRed/export/test_reduced_ascii_loader.py @@ -1,13 +1,15 @@ # package imports -from RefRed.export.reduced_ascii_loader import ReducedAsciiLoader - -# 3rd party imports -import pytest import tempfile import unittest.mock as mock -import numpy as np from pathlib import Path +import numpy as np + +# 3rd party imports +import pytest + +from RefRed.export.reduced_ascii_loader import ReducedAsciiLoader + class TestReducedAsciiLoader: def setup_class(self): diff --git a/test/unit/RefRed/interfaces/test_deadtime_entry.py b/test/unit/RefRed/interfaces/test_deadtime_entry.py index efb34eeb..226fbb4f 100644 --- a/test/unit/RefRed/interfaces/test_deadtime_entry.py +++ b/test/unit/RefRed/interfaces/test_deadtime_entry.py @@ -38,5 +38,5 @@ def test_uncheck_checkbox(dead_time_entry_point, qtbot): assert not dead_time_entry_point.settingsButton.isEnabled() -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/interfaces/test_deadtime_settings.py b/test/unit/RefRed/interfaces/test_deadtime_settings.py index 2c718719..95bedf5f 100644 --- a/test/unit/RefRed/interfaces/test_deadtime_settings.py +++ b/test/unit/RefRed/interfaces/test_deadtime_settings.py @@ -25,10 +25,10 @@ def test_initialization_with_custom_values(self): def test_to_xml(self): expected_xml = ( - 'True\n' - 'True\n' - '4.2\n' - '150.0' + "True\n" + "True\n" + "4.2\n" + "150.0" ) model = DeadTimeSettingsModel(apply_deadtime=True, paralyzable=True, dead_time=4.2, tof_step=150) xml_output = model.to_xml() @@ -36,14 +36,14 @@ def test_to_xml(self): def test_from_xml(self): xml_input = ( - '' - 'True\n' - 'False\n' - 'False\n' - '2.1\n' - '100.0\n' - 'True\n' - '' + "" + "True\n" + "False\n" + "False\n" + "2.1\n" + "100.0\n" + "True\n" + "" ) dom = parseString(xml_input) model = DeadTimeSettingsModel().from_xml(dom.documentElement) diff --git a/test/unit/RefRed/interfaces/test_mytablewidget.py b/test/unit/RefRed/interfaces/test_mytablewidget.py index 1f761e3a..6783fe38 100644 --- a/test/unit/RefRed/interfaces/test_mytablewidget.py +++ b/test/unit/RefRed/interfaces/test_mytablewidget.py @@ -1,11 +1,12 @@ # package imports -from RefRed.interfaces.mytablewidget import MyTableWidget +import unittest.mock as mock + +import pytest # third party packages from qtpy.QtCore import Qt # type: ignore -import unittest.mock as mock -import pytest +from RefRed.interfaces.mytablewidget import MyTableWidget class Event(object): @@ -39,5 +40,5 @@ def test_keypress_event_enter_key(self, mockSuperInit, mockSuperKeyPressEvent): m.table_reduction_cell_enter_pressed.assert_called() -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py b/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py index de1556c0..aed478ba 100644 --- a/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py +++ b/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py @@ -1,10 +1,11 @@ # package imports -from RefRed.file_loading_utility import loadCsvFile -from RefRed.low_res_finder_algorithms.low_res_finder import LowResFinder +import numpy as np # 3rd party imports import pytest -import numpy as np + +from RefRed.file_loading_utility import loadCsvFile +from RefRed.low_res_finder_algorithms.low_res_finder import LowResFinder @pytest.fixture(scope="function") @@ -32,7 +33,7 @@ def csv_hard(data_server): def test_loadcsvfile_easy(csv_easy): - '''Step0 - Loading: checking that loadCsvFile works correctly on easy''' + """Step0 - Loading: checking that loadCsvFile works correctly on easy""" [xdata, ydata, edata] = csv_easy # x-axis xdata10 = xdata[0:10] @@ -49,7 +50,7 @@ def test_loadcsvfile_easy(csv_easy): def test_loadcsvfile_medium(csv_medium): - '''Step0 - Loading: checking that loadCsvFile works correctly on medium''' + """Step0 - Loading: checking that loadCsvFile works correctly on medium""" [xdata, ydata, edata] = csv_medium # x-axis xdata10 = xdata[0:10] @@ -66,7 +67,7 @@ def test_loadcsvfile_medium(csv_medium): def test_loadcsvfile_hard(csv_hard): - '''Step0 - Loading: checking that loadCsvFile works correctly on hard''' + """Step0 - Loading: checking that loadCsvFile works correctly on hard""" [xdata, ydata, edata] = csv_hard # x-axis xdata10 = xdata[0:10] @@ -83,7 +84,7 @@ def test_loadcsvfile_hard(csv_hard): def test_calculate_first_derivative_easy(csv_easy): - '''Step1 - derivative: testing the first derivative calculation of easy data set''' + """Step1 - derivative: testing the first derivative calculation of easy data set""" [xdata, ydata, edata] = csv_easy peakfinder = LowResFinder(xdata, ydata, edata) [xdata_first, ydata_first] = peakfinder.get_first_derivative() @@ -98,7 +99,7 @@ def test_calculate_first_derivative_easy(csv_easy): def test_calculate_first_derivative_yaxis_medium(csv_medium): - '''Step1 - derivative: testing the first derivative calculation of medium data set - axis y''' + """Step1 - derivative: testing the first derivative calculation of medium data set - axis y""" [xdata, ydata, edata] = csv_medium peakfinder = LowResFinder(xdata, ydata, edata) [_, ydata_first] = peakfinder.get_first_derivative() @@ -109,7 +110,7 @@ def test_calculate_first_derivative_yaxis_medium(csv_medium): def test_calculatefirstderivative_yaxis_hard(csv_hard): - '''Step1 - derivative: testing the first derivative calculation of hard data set - axis y''' + """Step1 - derivative: testing the first derivative calculation of hard data set - axis y""" [xdata, ydata, edata] = csv_hard peakfinder = LowResFinder(xdata, ydata, edata) [_, ydata_first] = peakfinder.get_first_derivative() @@ -120,7 +121,7 @@ def test_calculatefirstderivative_yaxis_hard(csv_hard): def test_calculateMinMaxDervativePixels_easy(csv_easy): - '''Step2 - calculate derivative counts value of easy data set''' + """Step2 - calculate derivative counts value of easy data set""" [xdata, ydata, edata] = csv_easy peakfinder = LowResFinder(xdata, ydata, edata) # minValue @@ -138,7 +139,7 @@ def test_calculateMinMaxDervativePixels_easy(csv_easy): def test_calculateMinMaxDervativePixels_medium(csv_medium): - '''Step2 - calculate derivative counts value of medium data set''' + """Step2 - calculate derivative counts value of medium data set""" [xdata, ydata, edata] = csv_medium peakfinder = LowResFinder(xdata, ydata, edata) # minValue @@ -150,7 +151,7 @@ def test_calculateMinMaxDervativePixels_medium(csv_medium): def test_calculateMinMaxDervativePixels_hard(csv_hard): - '''Step2 - calculate derivative counts value of hard data set''' + """Step2 - calculate derivative counts value of hard data set""" [xdata, ydata, edata] = csv_hard peakfinder = LowResFinder(xdata, ydata, edata) # minValue @@ -162,7 +163,7 @@ def test_calculateMinMaxDervativePixels_hard(csv_hard): def test_calculateAvgAndStdDerivation_counts_firstderi_easy(csv_easy): - '''Step3 - calculate mean and std of first derivation counts of easy data set''' + """Step3 - calculate mean and std of first derivation counts of easy data set""" [xdata, ydata, edata] = csv_easy peakfinder = LowResFinder(xdata, ydata, edata) # mean @@ -174,7 +175,7 @@ def test_calculateAvgAndStdDerivation_counts_firstderi_easy(csv_easy): def test_calculateAvgAndStdDerivation_counts_firstderi_medium(csv_medium): - '''Step3 - calculate mean and std of first derivation counts of medium data set''' + """Step3 - calculate mean and std of first derivation counts of medium data set""" [xdata, ydata, edata] = csv_medium peakfinder = LowResFinder(xdata, ydata, edata) # mean @@ -186,7 +187,7 @@ def test_calculateAvgAndStdDerivation_counts_firstderi_medium(csv_medium): def test_calculateAvgAndStdDerivation_counts_firstderi_hard(csv_hard): - '''Step3 - calculate mean and std of first derivation counts of hard data set''' + """Step3 - calculate mean and std of first derivation counts of hard data set""" [xdata, ydata, edata] = csv_hard peakfinder = LowResFinder(xdata, ydata, edata) # mean @@ -198,7 +199,7 @@ def test_calculateAvgAndStdDerivation_counts_firstderi_hard(csv_hard): def test_calculateLowResPixel_easy(csv_easy): - '''Step4 - assert the min&max value of low res for an easy data set''' + """Step4 - assert the min&max value of low res for an easy data set""" [xdata, ydata, edata] = csv_easy peakfinder = LowResFinder(xdata, ydata, edata) low_res_range = peakfinder.get_low_res() @@ -209,7 +210,7 @@ def test_calculateLowResPixel_easy(csv_easy): def test_calculateLowResPixel_medium(csv_medium): - '''Step4 - assert the min&max value of low res for a medium data set''' + """Step4 - assert the min&max value of low res for a medium data set""" [xdata, ydata, edata] = csv_medium peakfinder = LowResFinder(xdata, ydata, edata) low_res_range = peakfinder.get_low_res() @@ -220,7 +221,7 @@ def test_calculateLowResPixel_medium(csv_medium): def test_calculateLowResPixel_hard(csv_hard): - '''Step4 - assert the min&max value of low res for a hard data set''' + """Step4 - assert the min&max value of low res for a hard data set""" [xdata, ydata, edata] = csv_hard peakfinder = LowResFinder(xdata, ydata, edata) low_res_range = peakfinder.get_low_res() @@ -230,5 +231,5 @@ def test_calculateLowResPixel_hard(csv_hard): np.testing.assert_equal(low_res_range[1], 197) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py b/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py index 01f0c424..9c75f9b1 100644 --- a/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py +++ b/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py @@ -1,128 +1,128 @@ # package imports -from RefRed.peak_finder_algorithms.peak_finder_derivation import PeakFinderDerivation -from RefRed.file_loading_utility import loadCsvFile - # third party packages import pytest +from RefRed.file_loading_utility import loadCsvFile +from RefRed.peak_finder_algorithms.peak_finder_derivation import PeakFinderDerivation + class TestPeakFinderDerivation(object): def test_get5HighestPoints_xdata(self, data_server): - '''Step2 - 5highest points: using run 125682 to check calculation of 5 highest points - xdata''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step2 - 5highest points: using run 125682 to check calculation of 5 highest points - xdata""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) [high_x, _] = peakfinder1.get5HighestPoints() high_x = high_x.tolist() assert high_x == pytest.approx([155.0, 156.0, 154.0, 157.0, 153.0]) def test_get5HighestPoints_ydata(self, data_server): - '''Step2 - 5highest points: using run 125682 to check calculation of 5 highest points - ydata''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step2 - 5highest points: using run 125682 to check calculation of 5 highest points - ydata""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) [_, high_y] = peakfinder1.get5HighestPoints() high_y = high_y.tolist() assert high_y == pytest.approx([32351.0, 28999.0, 19351.0, 9503.0, 2796.0]) def test_calculatePeakPixel_sumPeakCounts(self, data_server): - '''Step3 - calculate peak pixel using run 125682 to check calculation of 5 highest points - sum_xdata''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step3 - calculate peak pixel using run 125682 to check calculation of 5 highest points - sum_xdata""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) sum_five_highest_xdata = peakfinder1.getSumPeakCounts() assert sum_five_highest_xdata == pytest.approx(93000.0) def test_calcuatePeakPixel_sumPeakCountTimePixel(self, data_server): - '''Step3 - calculate peak pixel using run 125682 to check calculation of 5 highest points - sum_ydata''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step3 - calculate peak pixel using run 125682 to check calculation of 5 highest points - sum_ydata""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) sum_five_highest_ydata = peakfinder1.getSumPeakCountsTimePixel() assert sum_five_highest_ydata == pytest.approx(14438061.0) def test_calculatePeakPixel_peakPixelValue(self, data_server): - '''Step3 - calculate peak pixel value using run 125682''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step3 - calculate peak pixel value using run 125682""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) peak_pixel = peakfinder1.getPeakPixel() assert peak_pixel == pytest.approx(155.0) def test_calculatefirstderivative_xaxis(self, data_server): - '''Step4 - derivative: testing the first derivative calculation - axis x''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step4 - derivative: testing the first derivative calculation - axis x""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) [xdata_first, _] = peakfinder.getFirstDerivative() xdata10 = xdata_first[0:10] assert xdata10 == pytest.approx([0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]) def test_calculatefirstderivative_yaxis(self, data_server): - '''Step4 - derivative: testing the first derivative calculation - axis y''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step4 - derivative: testing the first derivative calculation - axis y""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) [_, ydata_first] = peakfinder.getFirstDerivative() ydata10 = ydata_first[0:10] assert ydata10 == pytest.approx([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 1.0, -1.0]) def test_calculateMinMaxDervativePixels_minValue(self, data_server): - '''Step5 - calculate min derivative counts value''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step5 - calculate min derivative counts value""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) min_derivative_value = peakfinder.getMinDerivativeValue() assert min_derivative_value == pytest.approx(-19496.0) def test_calculateMinMaxDervativePixels_maxValue(self, data_server): - '''Step5 - calculate max derivative counts value''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step5 - calculate max derivative counts value""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) max_derivative_value = peakfinder.getMaxDerivativeValue() assert max_derivative_value == pytest.approx(16555.0) def test_calculateMinMaxDervativePixels_minPixelValue(self, data_server): - '''Step5 - calculate pixel of min derivative counts value''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step5 - calculate pixel of min derivative counts value""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) min_pixel_derivative_value = peakfinder.getMinDerivationPixelValue() assert min_pixel_derivative_value == pytest.approx(153.5) def test_calculateMinMaxDervativePixels_maxPixelValue(self, data_server): - '''Step5 - calculate pixel of max derivative counts value''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step5 - calculate pixel of max derivative counts value""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) max_pixel_derivative_value = peakfinder.getMaxDerivationPixelValue() assert max_pixel_derivative_value == pytest.approx(156.5) def test_calculateAvgAndStdDerivation_mean_counts_firstderi(self, data_server): - '''Step6 - calculate average of first derivation counts''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step6 - calculate average of first derivation counts""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) mean_counts_firstderi = peakfinder.getAverageOfFirstDerivationCounts() assert mean_counts_firstderi == pytest.approx(0) def test_calculateAvgAndStdDerivation_std_deviation_counts_firstderi(self, data_server): - '''Step6 - calculate standard deviation of first derivation counts''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step6 - calculate standard deviation of first derivation counts""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder = PeakFinderDerivation(xdata, ydata, edata) std_deviation_counts_firstderi = peakfinder.getStdDeviationOfFirstDerivationCounts() assert std_deviation_counts_firstderi == pytest.approx(1741.838, abs=0.001) def test_case_easy_data_set(self, data_server): - '''Step7 - calculate final peak range using run 125682 (easy data set)''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('easy_data_set.csv')) + """Step7 - calculate final peak range using run 125682 (easy data set)""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("easy_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) peaks = peakfinder1.getPeaks() assert peaks == pytest.approx([151, 159]) def test_case_medium_data_set(self, data_server): - '''Step7 - calculate final peak range using run 124211 (medium data set)''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('medium_data_set.csv')) + """Step7 - calculate final peak range using run 124211 (medium data set)""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("medium_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) peaks = peakfinder1.getPeaks() assert peaks == pytest.approx([151, 159]) def test_case_hard_data_set(self, data_server): - '''Step7 - calculate final peak range using run 124135 (hard data set)''' - [xdata, ydata, edata] = loadCsvFile(data_server.path_to('hard_data_set.csv')) + """Step7 - calculate final peak range using run 124135 (hard data set)""" + [xdata, ydata, edata] = loadCsvFile(data_server.path_to("hard_data_set.csv")) peakfinder1 = PeakFinderDerivation(xdata, ydata, edata) peaks = peakfinder1.getPeaks() assert peaks == pytest.approx([145, 167], abs=0.001) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py b/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py index e685ec19..bf904075 100644 --- a/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py +++ b/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py @@ -1,7 +1,8 @@ # third party packages. -import pytest from unittest.mock import Mock +import pytest + # RefRed imports from RefRed.reduction.individual_reduction_settings_handler import IndividualReductionSettingsHandler @@ -18,5 +19,5 @@ def __init__(self, **kwargs): assert handler.get_back_range(data, is_data=True) == [2, 3, 0, 1] -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/reduction_table_handling/test_const_q_checkbox_handler.py b/test/unit/RefRed/reduction_table_handling/test_const_q_checkbox_handler.py index d8cddb3d..f832b0a0 100644 --- a/test/unit/RefRed/reduction_table_handling/test_const_q_checkbox_handler.py +++ b/test/unit/RefRed/reduction_table_handling/test_const_q_checkbox_handler.py @@ -1,11 +1,11 @@ from unittest import mock from unittest.mock import Mock +from qtpy.QtCore import Qt # type: ignore + from RefRed.calculations.lr_data import LRData from RefRed.lconfigdataset import LConfigDataset from RefRed.reduction_table_handling.const_q_checkbox_handler import ConstQCheckBoxHandler -from qtpy.QtCore import Qt # type: ignore - from RefRed.tabledata import TableData @@ -13,7 +13,7 @@ def test_const_q_checkbox_handler(): big_table_data = TableData(max_row_count=1) row = 0 - with mock.patch.object(LRData, '__init__', return_value=None): + with mock.patch.object(LRData, "__init__", return_value=None): instance = LRData() big_table_data.set_reflectometry_data(row, instance) big_table_data.set_normalization_data(row, instance) diff --git a/test/unit/RefRed/reduction_table_handling/test_reduction_table_handling.py b/test/unit/RefRed/reduction_table_handling/test_reduction_table_handling.py index cbd8fc8e..b8371696 100644 --- a/test/unit/RefRed/reduction_table_handling/test_reduction_table_handling.py +++ b/test/unit/RefRed/reduction_table_handling/test_reduction_table_handling.py @@ -1,4 +1,5 @@ from unittest import mock + import pytest from qtpy import QtWidgets @@ -6,7 +7,6 @@ from RefRed.main import MainGui from RefRed.reduction_table_handling.reduction_table_handler import ReductionTableHandler - NBR_ROWS = 6 @@ -65,7 +65,7 @@ def test_clear_rows_selected(self, setup_main_window_reduction_table, qtbot): nbr_deleted = to_row + 1 - from_row # clear selected rows - with mock.patch.object(ReductionTableHandler, '_ReductionTableHandler__get_range_row_selected'): + with mock.patch.object(ReductionTableHandler, "_ReductionTableHandler__get_range_row_selected"): handler = ReductionTableHandler(parent=window_main) handler.from_row = from_row handler.to_row = to_row diff --git a/test/unit/RefRed/reduction_table_handling/test_update_reduction_table.py b/test/unit/RefRed/reduction_table_handling/test_update_reduction_table.py index 2358f50c..1bf6fb65 100644 --- a/test/unit/RefRed/reduction_table_handling/test_update_reduction_table.py +++ b/test/unit/RefRed/reduction_table_handling/test_update_reduction_table.py @@ -1,9 +1,10 @@ -from RefRed.main import MainGui -from test.utilities import load_run_from_reduction_table +import unittest.mock as mock # third party packages import pytest -import unittest.mock as mock + +from RefRed.main import MainGui +from test.utilities import load_run_from_reduction_table wait = 1000 @@ -108,5 +109,5 @@ def test_load_run_auto_peak_finder(mock_file_finder_find_runs, mock_display_plot assert window_main.big_table_data[0, 0].tof_range_auto == pytest.approx(user_set_tof, 1e-6) -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/settings/test_edit_settings.py b/test/unit/RefRed/settings/test_edit_settings.py index ceba74c3..3f3eda8f 100644 --- a/test/unit/RefRed/settings/test_edit_settings.py +++ b/test/unit/RefRed/settings/test_edit_settings.py @@ -1,25 +1,26 @@ # package imports -from RefRed.settings.settings_editor import SettingsEditor -from RefRed.settings.list_settings import ListSettings +import unittest.mock as mock # third party packages import pytest -import unittest.mock as mock + +from RefRed.settings.list_settings import ListSettings +from RefRed.settings.settings_editor import SettingsEditor DEFAULT_SETTINGS = ListSettings() class TestEditSettings(object): gui_metadata = { - 'q_min': DEFAULT_SETTINGS.q_min, - 'd_q0': DEFAULT_SETTINGS.d_q0, - 'dq_over_q': DEFAULT_SETTINGS.dq_over_q, - 'tof_bin': DEFAULT_SETTINGS.tof_bin, - 'q_bin': DEFAULT_SETTINGS.q_bin, - 'angle_offset': DEFAULT_SETTINGS.angle_offset, - 'angle_offset_error': DEFAULT_SETTINGS.angle_offset_error, + "q_min": DEFAULT_SETTINGS.q_min, + "d_q0": DEFAULT_SETTINGS.d_q0, + "dq_over_q": DEFAULT_SETTINGS.dq_over_q, + "tof_bin": DEFAULT_SETTINGS.tof_bin, + "q_bin": DEFAULT_SETTINGS.q_bin, + "angle_offset": DEFAULT_SETTINGS.angle_offset, + "angle_offset_error": DEFAULT_SETTINGS.angle_offset_error, } - ''' + """ {'q_min': 1.005, 'd_q0': 1.0004, 'dq_over_q': 1.005, @@ -27,7 +28,7 @@ class TestEditSettings(object): 'q_bin': 1.01, 'angle_offset': 1.016, 'angle_offset_error': 1.001} - ''' + """ @mock.patch("qtpy.QtWidgets.QMainWindow.__init__") def test_reset_button(self, mockSuperInit): @@ -40,12 +41,12 @@ def test_reset_button(self, mockSuperInit): editor.ui = mock.Mock() editor.populate_table() # modify a value - parent_item.gui_metadata['d_q0'] = 1.0004 + parent_item.gui_metadata["d_q0"] = 1.0004 assert parent_item.gui_metadata != DEFAULT_SETTINGS, "should have changed" # reset everything editor.reset_button() assert parent_item.gui_metadata == DEFAULT_SETTINGS, "should be identical" -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/settings/test_initialize_settings.py b/test/unit/RefRed/settings/test_initialize_settings.py index af2499d5..6afb2046 100644 --- a/test/unit/RefRed/settings/test_initialize_settings.py +++ b/test/unit/RefRed/settings/test_initialize_settings.py @@ -1,15 +1,15 @@ # package imports -from RefRed.settings.initialize_settings import InitializeSettings -from RefRed.settings.list_settings import ListSettings -from qtpy.QtCore import QSettings # type: ignore - # third party packages import pytest +from qtpy.QtCore import QSettings # type: ignore + +from RefRed.settings.initialize_settings import InitializeSettings +from RefRed.settings.list_settings import ListSettings class SettingsContext: - def __init__(self, suffix='', items={}): - self.settings = QSettings('neutron', 'RefRed' + suffix) + def __init__(self, suffix="", items={}): + self.settings = QSettings("neutron", "RefRed" + suffix) for key, value in items.items(): self.settings.setValue(key, str(value)) @@ -24,26 +24,26 @@ class TestInitializeSettings(object): gui_metadata = {} def test_initialize_default_settings(self): - with SettingsContext('-TestInitializeSettings') as settings: + with SettingsContext("-TestInitializeSettings") as settings: InitializeSettings(self, settings) assert self.gui_metadata == ListSettings() def test_initialize_qsettings(self): values = { - 'q_min': 1.005, - 'd_q0': 1.0004, - 'dq_over_q': 1.005, - 'tof_bin': 41, - 'q_bin': 1.01, - 'angle_offset': 1.016, - 'angle_offset_error': 1.001, + "q_min": 1.005, + "d_q0": 1.0004, + "dq_over_q": 1.005, + "tof_bin": 41, + "q_bin": 1.01, + "angle_offset": 1.016, + "angle_offset_error": 1.001, } - with SettingsContext('-TestInitializeSettings', values) as settings: + with SettingsContext("-TestInitializeSettings", values) as settings: InitializeSettings(self, settings) for k in values.keys(): assert self.gui_metadata[k] == values[k], k -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py b/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py index 44801277..43336cdd 100644 --- a/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py +++ b/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py @@ -24,7 +24,7 @@ def mock_table_row_item(row, col): try: real_col = index_col.index(col) except ValueError: - assert False, f'Column {col} content are not float/int' + assert False, f"Column {col} content are not float/int" cell_value = str(GoldValues.gold_table_setting[row, real_col]) @@ -38,7 +38,7 @@ def mock_table_row_cell(row, col): real_col = index_col.index(col) cell_value = GoldValues.gold_table_setting[row, real_col] except ValueError: - assert False, f'Column {col} content are not float/int' + assert False, f"Column {col} content are not float/int" spin_box_instance = qtpy.QtWidgets.QSpinBox() spin_box_instance.setValue(int(cell_value)) @@ -46,7 +46,7 @@ def mock_table_row_cell(row, col): return spin_box_instance -@mock.patch('RefRed.sf_calculator.reduction_sf_calculator.QApplication.processEvents') +@mock.patch("RefRed.sf_calculator.reduction_sf_calculator.QApplication.processEvents") def test_init_reduction_sf_calculator(processEvents_mock, qtbot): """Test reduction sf calculator""" main_app = MainGui() @@ -61,9 +61,9 @@ def test_init_reduction_sf_calculator(processEvents_mock, qtbot): sf_gui.tableWidget.item = mock.MagicMock(side_effect=mock_table_row_item) sf_gui.incidentMediumComboBox = qtpy.QtWidgets.QComboBox() - sf_gui.incidentMediumComboBox.addItem('air') + sf_gui.incidentMediumComboBox.addItem("air") sf_gui.incidentMediumComboBox.setCurrentIndex(0) - sf_gui.sfFileNameLabel = qtpy.QtWidgets.QLabel('/tmp/testscale.cfg') + sf_gui.sfFileNameLabel = qtpy.QtWidgets.QLabel("/tmp/testscale.cfg") # Set up mock for mantid LRScalingFactors lr_reduction.scaling_factors.LRScalingFactors.LRScalingFactors = mock.Mock(side_effect=mock_lr_scaling_factor) @@ -121,19 +121,19 @@ def PyInit(self): def setProperty(self, key, value): assert key in { - 'DirectBeamRuns', - 'IncidentMedium', - 'Attenuators', - 'TOFRange', - 'TOFSteps', - 'SignalPeakPixelRange', - 'SignalBackgroundPixelRange', - 'LowResolutionPixelRange', - 'ScalingFactorFile', - 'UseDeadTimeCorrection', - 'ParalyzableDeadTime', - 'DeadTime', - 'DeadTimeTOFStep', + "DirectBeamRuns", + "IncidentMedium", + "Attenuators", + "TOFRange", + "TOFSteps", + "SignalPeakPixelRange", + "SignalBackgroundPixelRange", + "LowResolutionPixelRange", + "ScalingFactorFile", + "UseDeadTimeCorrection", + "ParalyzableDeadTime", + "DeadTime", + "DeadTimeTOFStep", } def PyExec(self): @@ -142,5 +142,5 @@ def PyExec(self): return Algo() -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/sf_calculator/test_sf_calculator.py b/test/unit/RefRed/sf_calculator/test_sf_calculator.py index 2d431820..c5003241 100644 --- a/test/unit/RefRed/sf_calculator/test_sf_calculator.py +++ b/test/unit/RefRed/sf_calculator/test_sf_calculator.py @@ -37,18 +37,18 @@ class MockDeadTimeSettingsView: def __init__(self, parent=None): r"""Mocking the DeadTimeSettingsView to return default values without user interaction""" self.options = { - 'paralyzable': calculator.paralyzable_deadtime, - 'dead_time': calculator.deadtime_value, - 'tof_step': calculator.deadtime_tof_step, + "paralyzable": calculator.paralyzable_deadtime, + "dead_time": calculator.deadtime_value, + "tof_step": calculator.deadtime_tof_step, } def exec_(self): return QtWidgets.QDialog.Accepted def set_state(self, paralyzable, dead_time, tof_step): - self.options['paralyzable'] = paralyzable - self.options['dead_time'] = dead_time - self.options['tof_step'] = tof_step + self.options["paralyzable"] = paralyzable + self.options["dead_time"] = dead_time + self.options["tof_step"] = tof_step monkeypatch.setattr("RefRed.sf_calculator.sf_calculator.DeadTimeSettingsView", MockDeadTimeSettingsView) self.app.show_dead_time_dialog() @@ -65,7 +65,7 @@ def test_show_dead_time_dialog_updated_values(self, monkeypatch): class MockDeadTimeSettingsView: def __init__(self, parent=None): r"""Mocking the DeadTimeSettingsView to return values without user interaction""" - self.options = {'paralyzable': new_paralyzable, 'dead_time': new_dead_time, 'tof_step': new_tof_step} + self.options = {"paralyzable": new_paralyzable, "dead_time": new_dead_time, "tof_step": new_tof_step} def exec_(self): return QtWidgets.QDialog.Accepted @@ -80,5 +80,5 @@ def set_state(self, paralyzable, dead_time, tof_step): assert self.app.deadtime_tof_step == new_tof_step -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/test_file_loading_utility.py b/test/unit/RefRed/test_file_loading_utility.py index 105603c8..62c1aa97 100644 --- a/test/unit/RefRed/test_file_loading_utility.py +++ b/test/unit/RefRed/test_file_loading_utility.py @@ -1,31 +1,31 @@ # package imports -from RefRed.file_loading_utility import loadCsvFile - # third party packages import pytest +from RefRed.file_loading_utility import loadCsvFile + -@pytest.fixture(scope='function') +@pytest.fixture(scope="function") def csv_data(data_server): - return loadCsvFile(data_server.path_to('easy_data_set.csv')) + return loadCsvFile(data_server.path_to("easy_data_set.csv")) def test_loadcsvfile_xaxis(csv_data): - '''Step1 - Loading: checking that loadCsvFile works correctly on xaxis''' + """Step1 - Loading: checking that loadCsvFile works correctly on xaxis""" [xdata, _, _] = csv_data xdata10 = xdata[0:10] assert xdata10 == pytest.approx([0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]) def test_loadcsvfile_yaxis(csv_data): - '''Step1 - Loading: checking that loadCsvFile works correctly on yaxis''' + """Step1 - Loading: checking that loadCsvFile works correctly on yaxis""" [_, ydata, _] = csv_data ydata10 = ydata[0:10] assert ydata10 == pytest.approx([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 5.0]) def test_loadcsvfile_eaxis(csv_data): - '''Step1 - Loading: checking that loadCsvFile works correctly on eaxis''' + """Step1 - Loading: checking that loadCsvFile works correctly on eaxis""" [_, _, edata] = csv_data edata10 = edata[0:10] assert edata10 == pytest.approx([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.236067977]) diff --git a/test/unit/RefRed/test_main.py b/test/unit/RefRed/test_main.py index 8936e1bb..386344f7 100644 --- a/test/unit/RefRed/test_main.py +++ b/test/unit/RefRed/test_main.py @@ -21,10 +21,10 @@ def test_init(self): def test_run_reduction_button(self): assert self.app.run_reduction_button() is None - @mock.patch('RefRed.main.MainGui.file_loaded_signal') - @mock.patch('RefRed.main.InitializeGui') - @mock.patch('RefRed.main.load_ui') - @mock.patch('qtpy.QtWidgets.QMainWindow.__init__') + @mock.patch("RefRed.main.MainGui.file_loaded_signal") + @mock.patch("RefRed.main.InitializeGui") + @mock.patch("RefRed.main.load_ui") + @mock.patch("qtpy.QtWidgets.QMainWindow.__init__") def test_mock_init(self, mockMainWindowInit, mockLoadUI, mockInitializeGui, mockFileLoadedSignal): parent = mock.Mock() MainGui(parent=parent) @@ -33,11 +33,11 @@ def test_mock_init(self, mockMainWindowInit, mockLoadUI, mockInitializeGui, mock mockInitializeGui.assert_called() mockFileLoadedSignal.connect.assert_called() - @mock.patch('RefRed.main.LoadingConfiguration') - @mock.patch('RefRed.main.MainGui.file_loaded_signal') - @mock.patch('RefRed.main.InitializeGui') - @mock.patch('RefRed.main.load_ui') - @mock.patch('qtpy.QtWidgets.QMainWindow.__init__') + @mock.patch("RefRed.main.LoadingConfiguration") + @mock.patch("RefRed.main.MainGui.file_loaded_signal") + @mock.patch("RefRed.main.InitializeGui") + @mock.patch("RefRed.main.load_ui") + @mock.patch("qtpy.QtWidgets.QMainWindow.__init__") def test_load_configuration( self, mockMainWindowInit, mockLoadUI, mockInitializeGui, mockFileLoadedSignal, mockLoadConfiguration ): @@ -71,18 +71,18 @@ class MockDeadTimeSettingsView: def __init__(self, parent=None): r"""Mocking the DeadTimeSettingsView to return default values without user interaction""" self.options = { - 'paralyzable': main_gui.deadtime_settings.paralyzable, - 'dead_time': main_gui.deadtime_settings.dead_time, - 'tof_step': main_gui.deadtime_settings.tof_step, + "paralyzable": main_gui.deadtime_settings.paralyzable, + "dead_time": main_gui.deadtime_settings.dead_time, + "tof_step": main_gui.deadtime_settings.tof_step, } def exec_(self): return QtWidgets.QDialog.Accepted def set_state(self, paralyzable, dead_time, tof_step): - self.options['paralyzable'] = paralyzable - self.options['dead_time'] = dead_time - self.options['tof_step'] = tof_step + self.options["paralyzable"] = paralyzable + self.options["dead_time"] = dead_time + self.options["tof_step"] = tof_step monkeypatch.setattr("RefRed.main.DeadTimeSettingsView", MockDeadTimeSettingsView) self.app.show_deadtime_settings() @@ -100,9 +100,9 @@ class MockDeadTimeSettingsView: def __init__(self, parent=None): r"""Mocking the DeadTimeSettingsView to return default values without user interaction""" self.options = { - 'paralyzable': new_paralyzable, - 'dead_time': new_dead_time, - 'tof_step': new_tof_step, + "paralyzable": new_paralyzable, + "dead_time": new_dead_time, + "tof_step": new_tof_step, } def exec_(self): @@ -118,5 +118,5 @@ def set_state(self, paralyzable, dead_time, tof_step): assert self.app.deadtime_settings.tof_step == new_tof_step -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/test_tabledata.py b/test/unit/RefRed/test_tabledata.py index 7cc7617f..6ba16151 100644 --- a/test/unit/RefRed/test_tabledata.py +++ b/test/unit/RefRed/test_tabledata.py @@ -26,20 +26,20 @@ def test_set_data_by_column_enum_raises(self): assert "Wrong type for wrong_type" in str(exception.value) def test_set_data_by_column_enum(self): - with patch.object(LRData, '__init__', return_value=None): + with patch.object(LRData, "__init__", return_value=None): instance = LRData() self.table.set_data_by_column_enum(0, TableDataColumIndex.LR_DATA, instance) self.table.set_data_by_column_enum(0, TableDataColumIndex.LR_NORM, instance) self.table.set_data_by_column_enum(0, TableDataColumIndex.LR_CONFIG, LConfigDataset()) def test_reflectometry_data(self): - with patch.object(LRData, '__init__', return_value=None): + with patch.object(LRData, "__init__", return_value=None): self.table.set_reflectometry_data(0, LRData()) assert isinstance(self.table.reflectometry_data(0), LRData) assert isinstance(self.table[0, int(TableDataColumIndex.LR_DATA)], LRData) def test_normalization_data(self): - with patch.object(LRData, '__init__', return_value=None): + with patch.object(LRData, "__init__", return_value=None): self.table.set_normalization_data(0, LRData()) assert isinstance(self.table.normalization_data(0), LRData) assert isinstance(self.table[0, int(TableDataColumIndex.LR_NORM)], LRData) @@ -82,5 +82,5 @@ def test_expunge_rows(self): assert new_counters == counters -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) diff --git a/test/unit/RefRed/test_utilities.py b/test/unit/RefRed/test_utilities.py index 769782cd..5921cced 100644 --- a/test/unit/RefRed/test_utilities.py +++ b/test/unit/RefRed/test_utilities.py @@ -1,5 +1,6 @@ -import pytest import numpy as np +import pytest + from RefRed.utilities import convert_tof_values_unit @@ -9,11 +10,11 @@ def test_convert_tof_list(): tof_list = [2000.0, 32100.0] # Test same unit - same_list_micros = convert_tof_values_unit(tof_list, 'micros', 'micros') + same_list_micros = convert_tof_values_unit(tof_list, "micros", "micros") assert tof_list == same_list_micros # Test conversion - to_list_micros = convert_tof_values_unit(tof_list, 'ms', 'micros') + to_list_micros = convert_tof_values_unit(tof_list, "ms", "micros") # the change will be changed in place assert to_list_micros[0] == tof_list[0] assert to_list_micros[1] == tof_list[1] @@ -28,11 +29,11 @@ def test_convert_tof_array(): tof_list = np.array([2000.0, 32100.0]) # Test same unit - same_list_ms = convert_tof_values_unit(tof_list, 'ms', 'ms') + same_list_ms = convert_tof_values_unit(tof_list, "ms", "ms") np.testing.assert_allclose(tof_list, same_list_ms) # Test conversion - to_list_ms = convert_tof_values_unit(tof_list, 'micros', 'ms') + to_list_ms = convert_tof_values_unit(tof_list, "micros", "ms") # the change will be changed in place assert to_list_ms[0] == tof_list[0] assert to_list_ms[1] == tof_list[1] @@ -47,13 +48,13 @@ def test_convert_tof_none(): none_tofs = None # Output - none_output = convert_tof_values_unit(none_tofs, 'ms', 'ms') + none_output = convert_tof_values_unit(none_tofs, "ms", "ms") assert none_output is None # assert throw with pytest.raises(NameError): - convert_tof_values_unit(none_tofs, 'micro', 'ms') + convert_tof_values_unit(none_tofs, "micro", "ms") -if __name__ == '__main__': +if __name__ == "__main__": pytest.main([__file__]) From 9ce7b203e8ef922cd2b26a68ce567020d5ba678b Mon Sep 17 00:00:00 2001 From: glass-ships Date: Mon, 27 Jan 2025 11:57:15 -0500 Subject: [PATCH 3/6] remove flake8 step from GH action --- .github/workflows/test-and-deploy.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml index 3f39c17c..0366152f 100644 --- a/.github/workflows/test-and-deploy.yml +++ b/.github/workflows/test-and-deploy.yml @@ -23,8 +23,6 @@ jobs: auto-update-conda: true miniforge-version: latest environment-file: environment.yml - - name: flake8 - run: flake8 --statistics RefRed test scripts - name: mypy type annotations run: mypy RefRed test scripts - name: dependencies synced From 0718a84b7fa15319e3bf81e751ae87ea932e808e Mon Sep 17 00:00:00 2001 From: glass-ships Date: Fri, 14 Feb 2025 12:02:40 -0500 Subject: [PATCH 4/6] restore from next, ignore rules for 113 errors --- RefRed/about_dialog.py | 29 +- RefRed/calculations/lr_data.py | 25 +- .../update_reduction_table_metadata.py | 2 +- RefRed/config/gui.py | 13 +- RefRed/configuration/export_xml_config.py | 10 +- ...oad_reduction_table_from_lconfigdataset.py | 18 +- RefRed/configuration/loading_configuration.py | 9 +- .../user_configuration_handler.py | 7 - RefRed/initialization/gui.py | 2 +- RefRed/interfaces/deadtime_entry.py | 8 +- RefRed/interfaces/deadtime_settings.py | 9 +- RefRed/interfaces/instrument_settings.py | 213 ++++++++ RefRed/interfaces/instrument_settings.ui | 312 ++++++++++++ RefRed/interfaces/refred_main_interface.ui | 41 +- RefRed/interfaces/settings.ui | 144 ------ RefRed/interfaces/settings_password.ui | 106 ---- RefRed/interfaces/sf_calculator_interface.ui | 19 +- RefRed/main.py | 121 ++++- .../global_reduction_settings_handler.py | 2 +- RefRed/reduction/live_reduction_handler.py | 26 +- RefRed/settings/__init__.py | 0 RefRed/settings/initialize_settings.py | 36 -- RefRed/settings/list_settings.py | 28 -- RefRed/settings/settings_editor.py | 79 --- RefRed/settings/settings_password_editor.py | 26 - RefRed/sf_calculator/lr_data.py | 10 +- pyproject.toml | 11 +- setup.py | 1 - test/data/test_instrument_settings.xml | 464 ++++++++++++++++++ .../configuration/test_export_xml_config.py | 2 +- .../test_loading_configuration.py | 25 +- .../RefRed/interfaces/test_deadtime_entry.py | 4 +- .../interfaces/test_instrument_settings.py | 109 ++++ .../RefRed/settings/test_edit_settings.py | 52 -- .../settings/test_initialize_settings.py | 49 -- test/unit/RefRed/test_main.py | 147 +++++- 36 files changed, 1495 insertions(+), 664 deletions(-) create mode 100644 RefRed/interfaces/instrument_settings.py create mode 100644 RefRed/interfaces/instrument_settings.ui delete mode 100644 RefRed/interfaces/settings.ui delete mode 100644 RefRed/interfaces/settings_password.ui delete mode 100644 RefRed/settings/__init__.py delete mode 100644 RefRed/settings/initialize_settings.py delete mode 100644 RefRed/settings/list_settings.py delete mode 100644 RefRed/settings/settings_editor.py delete mode 100644 RefRed/settings/settings_password_editor.py create mode 100644 test/data/test_instrument_settings.xml create mode 100644 test/unit/RefRed/interfaces/test_instrument_settings.py delete mode 100644 test/unit/RefRed/settings/test_edit_settings.py delete mode 100644 test/unit/RefRed/settings/test_initialize_settings.py diff --git a/RefRed/about_dialog.py b/RefRed/about_dialog.py index 7831da18..218fd5ec 100644 --- a/RefRed/about_dialog.py +++ b/RefRed/about_dialog.py @@ -6,7 +6,7 @@ from numpy.version import version as numpy_version_str from qtpy import PYQT_VERSION, QT_VERSION, QtWidgets -from RefRed import __version__ as RefRed_version_str +from RefRed import __version__ as refred_version_str class AboutDialog(object): @@ -23,27 +23,18 @@ def display(self): qt_version = QT_VERSION pyqt_version = PYQT_VERSION - message = """RefRed - Liquids Reflectrometry Reduction program + message = f"""RefRed - Liquids Reflectrometry Reduction program - RefRed version %s - Reduction version %s + RefRed version {refred_version_str} + Reduction version {lr_reduction.__version__} Library versions: - - Python: %s - - Numpy: %s - - Mantid: %s - - Matplotlib: %s - - Qt: %s - - PyQt: %s""" % ( - RefRed_version_str, - lr_reduction.__version__, - python_version, - numpy_version, - mantid_version, - matplotlib_version, - qt_version, - pyqt_version, - ) + - Python: {python_version} + - Numpy: {numpy_version} + - Mantid: {mantid_version} + - Matplotlib: {matplotlib_version} + - Qt: {qt_version} + - PyQt: {pyqt_version}""" QtWidgets.QMessageBox.about(self.parent, "About RefRed", message) diff --git a/RefRed/calculations/lr_data.py b/RefRed/calculations/lr_data.py index 59e7f9bb..d105a832 100644 --- a/RefRed/calculations/lr_data.py +++ b/RefRed/calculations/lr_data.py @@ -41,7 +41,7 @@ class LRData(object): ipts = "N/A" total_counts = 0 - def __init__( + def __init__( # noqa: C901 self, workspace, lconfig: Optional[LConfigDataset] = None, @@ -89,12 +89,13 @@ def __init__( self.S1H = mt_run.getProperty("S1VHeight").value[0] self.parent.current_ipts = mt_run.getProperty("experiment_identifier").value self.total_counts = workspace.getNumberEvents() + self.theta_theta_mode = mt_run.getProperty("BL4B:CS:ExpPl:OperatingMode").value[0] == "Free Liquid" try: self.SiW = mt_run.getProperty("SiHWidth").value[0] self.SiH = mt_run.getProperty("SiVHeight").value[0] self.isSiThere = True - except: + except: # noqa: E722 self.S2W = mt_run.getProperty("S2HWidth").value[0] self.S2H = mt_run.getProperty("S2VHeight").value[0] self.isSiThere = False @@ -193,7 +194,7 @@ def __init__( self.all_plot_axis = AllPlotAxis() self.tof_auto_flag = True - self.new_detector_geometry_flag = self.is_nexus_taken_after_refDate() + self.new_detector_geometry_flag = self.is_nexus_taken_after_ref_date() self.data_loaded = False self.read_data() @@ -319,12 +320,16 @@ def calculate_lambda_range(self, tof_range=None): def calculate_theta(self, with_offset=True): """ - calculate theta + Calculate theta + If we are in free-liquid mode (theta-theta), return the incident angle. + Otherwise, return the sample theta. """ - tthd_value = self.tthd - thi_value = self.thi + if self.theta_theta_mode: + theta = self.thi + else: + theta = self.ths - theta = math.fabs(tthd_value - thi_value) / 2.0 + theta = np.fabs(theta) if theta < 0.001: logging.debug("thi and tthd are equal: is this a direct beam?") @@ -337,7 +342,7 @@ def calculate_theta(self, with_offset=True): return theta - def _getIxyt(self, nxs_histo): + def _get_Ixyt(self, nxs_histo): # noqa: N802 """ will format the histogrma NeXus to retrieve the full 3D data set """ @@ -355,7 +360,7 @@ def read_data(self): PreserveEvents=True, ) # retrieve 3D array - self._getIxyt(nxs_histo) + self._get_Ixyt(nxs_histo) nxs_histo.delete() self.tof_axis_auto_with_margin = self._tof_axis @@ -376,7 +381,7 @@ def read_data(self): self.data_loaded = True - def is_nexus_taken_after_refDate(self): + def is_nexus_taken_after_ref_date(self): """ This function parses the output.date and returns true if this date is after the ref date """ diff --git a/RefRed/calculations/update_reduction_table_metadata.py b/RefRed/calculations/update_reduction_table_metadata.py index 99917968..a0bdf4ca 100644 --- a/RefRed/calculations/update_reduction_table_metadata.py +++ b/RefRed/calculations/update_reduction_table_metadata.py @@ -17,7 +17,7 @@ def update(self): q_range = lrdata.q_range lambda_range = lrdata.lambda_range - incident_angle = lrdata.incident_angle + incident_angle = lrdata.incident_angle / 2.0 const_q = lrdata.const_q [qmin, qmax] = q_range diff --git a/RefRed/config/gui.py b/RefRed/config/gui.py index f1cb13c3..e0b1b3de 100644 --- a/RefRed/config/gui.py +++ b/RefRed/config/gui.py @@ -14,7 +14,7 @@ # plot options color_selection = 0 show_colorbars = False -normalizeXTof = False +normalize_x_tof = False # plot borders figure_params = [ {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # xy_overview @@ -23,3 +23,14 @@ {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # x_project {"top": 0.95, "right": 0.95, "bottom": 0.1, "left": 0.15}, # y_project ] + +# Default values to populate in the GUI +gui_metadata = dict( + q_min=0.005, + d_q0=0.0, + dq_over_q=0.028, + tof_bin=40, # micros + q_bin=0.01, # logarithmic binning + angle_offset=0.0, + angle_offset_error=0.001, +) diff --git a/RefRed/configuration/export_xml_config.py b/RefRed/configuration/export_xml_config.py index 3a0eaaa8..b1851ef2 100644 --- a/RefRed/configuration/export_xml_config.py +++ b/RefRed/configuration/export_xml_config.py @@ -11,7 +11,9 @@ # package imports import RefRed from RefRed.calculations.lr_data import LRData -from RefRed.reduction.global_reduction_settings_handler import GlobalReductionSettingsHandler +from RefRed.reduction.global_reduction_settings_handler import ( + GlobalReductionSettingsHandler, +) class ExportXMLConfig(object): @@ -173,7 +175,11 @@ def main_part(self): str_array.append(" True\n") - str_array.append(o_general_settings.dead_time.to_xml(indent=" ") + "\n") # dead time settings + # dead time settings + str_array.append(o_general_settings.dead_time.to_xml(indent=" ") + "\n") + + # instrument settings + str_array.append(o_general_settings.instrument_settings.to_xml(indent=" ") + "\n") str_array.append(" " + str(const_q) + "\n") diff --git a/RefRed/configuration/load_reduction_table_from_lconfigdataset.py b/RefRed/configuration/load_reduction_table_from_lconfigdataset.py index 2a1d78fd..176ba1a8 100644 --- a/RefRed/configuration/load_reduction_table_from_lconfigdataset.py +++ b/RefRed/configuration/load_reduction_table_from_lconfigdataset.py @@ -4,7 +4,9 @@ from RefRed.calculations.add_list_nexus import AddListNexus from RefRed.calculations.locate_list_run import LocateListRun from RefRed.calculations.lr_data import LRData -from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata +from RefRed.calculations.update_reduction_table_metadata import ( + UpdateReductionTableMetadata, +) from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.progressbar_handler import ProgressBarHandler from RefRed.plot.display_plots import DisplayPlots @@ -29,7 +31,7 @@ def __init__(self, parent=None): list_data_run = lconfig.data_sets o_list_data_nexus = LocateListRun(list_run=list_data_run) list_data_nexus = o_list_data_nexus.list_nexus_found - # list_data_nexus= o_list_data_nexus.list_run_found + # list_data_nexus= o_list_data_nexus.list_run_found _add_data_nexus = AddListNexus( list_nexus=list_data_nexus, list_run=list_data_run, @@ -38,7 +40,7 @@ def __init__(self, parent=None): prefix="data", ) data_lrdata = LRData(_add_data_nexus.wks, lconfig=lconfig, is_data=True, parent=self.parent) - self.update_lrdata(lrdata=data_lrdata, lconfig=lconfig, type="data", row=index_row) + self.update_lrdata(lrdata=data_lrdata, lconfig=lconfig, data_type="data", row=index_row) list_norm_run = lconfig.norm_sets o_list_norm_nexus = LocateListRun(list_run=list_norm_run) @@ -52,7 +54,7 @@ def __init__(self, parent=None): prefix="norm", ) norm_lrdata = LRData(_add_norm_nexus.wks, is_data=False, parent=self.parent) - self.update_lrdata(lrdata=norm_lrdata, lconfig=lconfig, type="norm", row=index_row) + self.update_lrdata(lrdata=norm_lrdata, lconfig=lconfig, data_type="norm", row=index_row) is_display_requested = self.display_of_this_row_checked(index_row) if is_display_requested: @@ -89,10 +91,10 @@ def get_nbr_lconfig(self): nbr_row += 1 return nbr_row - def update_lrdata(self, lrdata=None, lconfig=None, type="data", row=0): + def update_lrdata(self, lrdata=None, lconfig=None, data_type="data", row=0): big_table_data = self.parent.big_table_data - if type == "data": + if data_type == "data": peak1 = int(lconfig.data_peak[0]) peak2 = int(lconfig.data_peak[1]) back1_1 = int(lconfig.data_back[0]) @@ -137,12 +139,12 @@ def update_lrdata(self, lrdata=None, lconfig=None, type="data", row=0): lrdata.full_file_name = full_file_name lrdata.const_q = const_q - index_col = 0 if type == "data" else 1 + index_col = 0 if data_type == "data" else 1 reduction_table_index_col = index_col + 1 big_table_data[row, index_col] = lrdata self.parent.big_table_data = big_table_data - if type == "data": + if data_type == "data": UpdateReductionTableMetadata(parent=self.parent, lrdata=lrdata, row=row) QtWidgets.QApplication.processEvents() diff --git a/RefRed/configuration/loading_configuration.py b/RefRed/configuration/loading_configuration.py index 23e20c72..c38572e7 100644 --- a/RefRed/configuration/loading_configuration.py +++ b/RefRed/configuration/loading_configuration.py @@ -55,7 +55,8 @@ def run(self): try: self.loading() message = "Done!" - except: + except Exception as e: # noqa: BLE001 + logging.error(f"Error loading file: {e}") message = "Error loading file: aborted" else: message = "Loading aborted" @@ -186,6 +187,12 @@ def populate_main_gui_general_settings(self): self.parent.deadtime_settings.from_xml(node_0) self.parent.ui.deadtime_entry.applyCheckBox.setChecked(self.parent.deadtime_settings.apply_deadtime) + # initialize the instrument settings + self.parent.instrument_settings.from_xml(node_0) + self.parent.ui.instrument_settings_entry.applyCheckBox.setChecked( + self.parent.instrument_settings.apply_instrument_settings + ) + def getMetadataObject(self, node) -> LConfigDataset: r"""Populate an instance of type LConfigDataset using the information contained in one of the 'RefLData XML blocks within a configuration file.""" diff --git a/RefRed/configuration/user_configuration_handler.py b/RefRed/configuration/user_configuration_handler.py index be282eff..05f2eb4c 100644 --- a/RefRed/configuration/user_configuration_handler.py +++ b/RefRed/configuration/user_configuration_handler.py @@ -6,8 +6,6 @@ from RefRed.configuration.user_configuration import UserConfiguration from RefRed.utilities import str2bool -# from RefRed.settings.list_settings import ListSettings - class RetrieveUserConfiguration(object): def __init__(self, parent=None): @@ -39,8 +37,3 @@ def __init__(self, parent=None): o_user_config = self.parent.o_user_configuration settings.setValue("is_reduced_plot_stitching_tab_xlog", str(o_user_config.is_reduced_plot_stitching_tab_xlog)) settings.setValue("is_reduced_plot_stitching_tab_ylog", str(o_user_config.is_reduced_plot_stitching_tab_ylog)) - - _gui_metadata = self.parent.gui_metadata - for _key in _gui_metadata.keys(): - _value = str(_gui_metadata[_key]) - settings.setValue(_key, _value) diff --git a/RefRed/initialization/gui.py b/RefRed/initialization/gui.py index 887e6b9b..317ebccd 100644 --- a/RefRed/initialization/gui.py +++ b/RefRed/initialization/gui.py @@ -15,7 +15,7 @@ class Gui(object): "Plotted", "Data Run #", "Norm. Run #", - "2\u03b8 (\u00b0)", + "\u03b8 (\u00b0)", "\u03bbmin (\u00c5)", "\u03bbmax (\u00c5)", "Qmin (1/\u00c5)", diff --git a/RefRed/interfaces/deadtime_entry.py b/RefRed/interfaces/deadtime_entry.py index e7593641..f7937bb3 100644 --- a/RefRed/interfaces/deadtime_entry.py +++ b/RefRed/interfaces/deadtime_entry.py @@ -1,4 +1,3 @@ -# third party imports from qtpy.QtWidgets import QCheckBox, QGroupBox, QHBoxLayout, QPushButton @@ -25,13 +24,16 @@ def initUI(self): self.applyCheckBox = QCheckBox("Apply", self) self.applyCheckBox.stateChanged.connect(self.toggleSettingsButton) self.settingsButton = QPushButton("Settings", self) - self.settingsButton.setEnabled(self.applyCheckBox.isChecked()) # enabled if we use the correction + self.settingsButton.setEnabled( + # enabled if we use the correction + self.applyCheckBox.isChecked() + ) # Create a horizontal layout for the checkbox and settings button hbox = QHBoxLayout() hbox.addWidget(self.applyCheckBox) hbox.addWidget(self.settingsButton) - hbox.addStretch(1) # This adds a stretchable space after the button (optional) + # hbox.addStretch(1) # This adds a stretchable space after the button (optional) # Set the layout for the group box self.setLayout(hbox) diff --git a/RefRed/interfaces/deadtime_settings.py b/RefRed/interfaces/deadtime_settings.py index 77ed77e2..90f01121 100644 --- a/RefRed/interfaces/deadtime_settings.py +++ b/RefRed/interfaces/deadtime_settings.py @@ -1,10 +1,8 @@ -# third-party imports from typing import Any, Callable, Dict from xml.dom.minidom import Document, Element from qtpy.QtWidgets import QDialog, QWidget -# RefRed imports from RefRed.configuration.global_settings import GlobalSettings from RefRed.interfaces import load_ui from RefRed.utilities import str2bool @@ -54,7 +52,7 @@ def _to_xml(field: str) -> str: element.appendChild(element_text) return element.toxml() - return "\n".join([indent + _to_xml(field) for field in self.dict()]) + return "\n".join([indent + _to_xml(field) for field in self.model_dump()]) def from_xml(self, node: Element): r"""Update the settings from the contents of an XML element @@ -105,7 +103,7 @@ def as_template_reader_dict(self) -> Dict[str, Any]: "dead_time": "dead_time_value", "tof_step": "dead_time_tof_step", } - return {_to_reader_key[field]: value for field, value in self.dict().items()} + return {_to_reader_key[field]: value for field, value in self.model_dump().items()} class DeadTimeSettingsView(QDialog): @@ -146,8 +144,7 @@ def get_state_from_form(self) -> dict: def accept(self): """ - Read in the options on the form when the OK button is - clicked. + Read in the options on the form when the OK button is clicked. """ self.options = self.get_state_from_form() self.close() diff --git a/RefRed/interfaces/instrument_settings.py b/RefRed/interfaces/instrument_settings.py new file mode 100644 index 00000000..47f565d7 --- /dev/null +++ b/RefRed/interfaces/instrument_settings.py @@ -0,0 +1,213 @@ +from dataclasses import dataclass +from typing import Any, Callable, Dict +from xml.dom.minidom import Document, Element + +from qtpy.QtWidgets import ( + QCheckBox, + QDialog, + QGroupBox, + QHBoxLayout, + QPushButton, + QWidget, +) + +from RefRed.configuration.global_settings import GlobalSettings +from RefRed.interfaces import load_ui + + +@dataclass +class DEFAULT_INSTRUMENT_SETTINGS: # noqa: N801 + apply_instrument_settings: bool = False + source_detector_distance: float = 15.75 + sample_detector_distance: float = 1.83 + num_x_pixels: int = 256 + num_y_pixels: int = 304 + pixel_width: float = 0.70 + xi_reference: float = 445 + s1_sample_distance: float = 1.485 + + +class InstrumentSettingsEntryPoint(QGroupBox): + def __init__(self, title="Instrument Settings"): + super().__init__(title) + self.initUI() + + def initUI(self): + # Set the stylesheet for the group box to have a border + self.setStyleSheet( + "QGroupBox {" + " border: 1px solid gray;" + " border-radius: 5px;" + " margin-top: 1ex;" # space above the group box + "} " + "QGroupBox::title {" + " subcontrol-origin: margin;" + " subcontrol-position: top center;" # align the title to the center + " padding: 0 3px;" + "}" + ) + + self.applyCheckBox = QCheckBox("Apply", self) + self.applyCheckBox.stateChanged.connect(self.toggleSettingsButton) + self.settingsButton = QPushButton("Settings", self) + self.settingsButton.setEnabled(self.applyCheckBox.isChecked()) + + # Create a horizontal layout for the checkbox and settings button + hbox = QHBoxLayout() + hbox.addWidget(self.applyCheckBox) + hbox.addWidget(self.settingsButton) + + # Set the layout for the group box + self.setLayout(hbox) + + def toggleSettingsButton(self, state): + # Enable the settings button if the checkbox is checked, disable otherwise + self.settingsButton.setEnabled(state) + + +class InstrumentSettingsDialog(QDialog): + """ + Dialog to specify instrument geometry parameters. + """ + + def __init__(self, parent: QWidget): + super().__init__(parent) + self.ui = load_ui(ui_filename="instrument_settings.ui", baseinstance=self) + self.options = self.get_state_from_form() + + def set_state( + self, + # apply_instrument_settings, + source_detector_distance, + sample_detector_distance, + num_x_pixels, + num_y_pixels, + pixel_width, + xi_reference, + s1_sample_distance, + ): + """ + Store options and populate the form + + :param source_detector_distance: Source to detector distance in meters + :param sample_detector_distance: Sample to detector distance in meters + :param num_x_pixels: Number of pixels in the x direction + :param num_y_pixels: Number of pixels in the y direction + :param pixel_width: Pixel width in mm + :param xi_reference: Reference xi value in mm + :param s1_sample_distance: S1 to sample distance in meters + """ + self.ui.source_detector_distance.setValue(source_detector_distance) + self.ui.sample_detector_distance.setValue(sample_detector_distance) + self.ui.num_x_pixels.setValue(num_x_pixels) + self.ui.num_y_pixels.setValue(num_y_pixels) + self.ui.pixel_width.setValue(pixel_width) + self.ui.xi_reference.setValue(xi_reference) + self.ui.s1_sample_distance.setValue(s1_sample_distance) + self.options = self.get_state_from_form() + + def get_state_from_form(self) -> dict: + r"""Read the options from the form. + + Returns + ------- + Dictionary whose keys must match fields of class `InstrumentSettings` + """ + return { + "source_detector_distance": self.ui.source_detector_distance.value(), + "sample_detector_distance": self.ui.sample_detector_distance.value(), + "num_x_pixels": self.ui.num_x_pixels.value(), + "num_y_pixels": self.ui.num_y_pixels.value(), + "pixel_width": self.ui.pixel_width.value(), + "xi_reference": self.ui.xi_reference.value(), + "s1_sample_distance": self.ui.s1_sample_distance.value(), + } + + def accept(self): + """ + Read in the options on the form when the OK button is clicked. + """ + self.options = self.get_state_from_form() + self.close() + + +class InstrumentSettings(GlobalSettings): + """Dataclass to store instrument geometry parameters. These are global options + + Default values are determined by settings.json from lr_reduction + """ + + # pydantic fields + apply_instrument_settings: bool = DEFAULT_INSTRUMENT_SETTINGS.apply_instrument_settings + source_detector_distance: float = DEFAULT_INSTRUMENT_SETTINGS.source_detector_distance + sample_detector_distance: float = DEFAULT_INSTRUMENT_SETTINGS.sample_detector_distance + num_x_pixels: int = DEFAULT_INSTRUMENT_SETTINGS.num_x_pixels + num_y_pixels: int = DEFAULT_INSTRUMENT_SETTINGS.num_y_pixels + pixel_width: float = DEFAULT_INSTRUMENT_SETTINGS.pixel_width + xi_reference: float = DEFAULT_INSTRUMENT_SETTINGS.xi_reference + s1_sample_distance: float = DEFAULT_INSTRUMENT_SETTINGS.s1_sample_distance + + # class variable, translates fields to XML tag names, same names as the lr_reduction package + def to_xml(self, indent: str = "") -> str: + r"""Convert the settings to an XML string + + The XML tag names are same as those used by lr_reduction.reduction_template_reader.to_xml() + + Example + ------- + The XML string would look like: + + value1 + value2 + value3 + + """ + doc: Document = Document() + xml = "" + for field, value in self.model_dump().items(): + # if field == "apply_instrument_settings": + # continue + child: Element = doc.createElement(field) + child.appendChild(doc.createTextNode(str(value))) + xml += f"{indent}{child.toxml()}\n" + return xml + + def from_xml(self, node: Element): + r""" + Update the settings from the contents of an XML element + XML tag names name are same as those produced by lr_reduction.reduction_template_reader.to_xml() + + Example + ------- + A valid input XML element would look like: + + value1 + value2 + value3 + + """ + # cast each value (of type `str`) to the type appropriate to the corresponding pydantic field + converters: Dict[str, Callable[[str], Any]] = { + "apply_instrument_settings": bool, + "source_detector_distance": float, + "sample_detector_distance": float, + "num_x_pixels": int, + "num_y_pixels": int, + "pixel_width": float, + "xi_reference": float, + "s1_sample_distance": float, + } + for field, converter in converters.items(): + tmp: list = node.getElementsByTagName(field) + if len(tmp): + value = tmp[0].childNodes[0].nodeValue + setattr(self, field, converter(value)) + else: + # if the field is not found in the XML, we use the default value + setattr(self, field, DEFAULT_INSTRUMENT_SETTINGS.__dict__[field]) + + return self + + def as_template_reader_dict(self) -> Dict[str, Any]: + r"""Save the settings as a dictionary for lr_reduction.reduction_template_reader.from_dict()""" + return self.model_dump() diff --git a/RefRed/interfaces/instrument_settings.ui b/RefRed/interfaces/instrument_settings.ui new file mode 100644 index 00000000..7ec6176d --- /dev/null +++ b/RefRed/interfaces/instrument_settings.ui @@ -0,0 +1,312 @@ + + + Dialog + + + Qt::NonModal + + + + 0 + 0 + 392 + 309 + + + + Instrument Geometry Settings + + + true + + + true + + + + + 10 + 260 + 371 + 31 + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + 9 + 9 + 371 + 241 + + + + + + + + + 1000000000.000000000000000 + + + 3 + + + 0.1 + + + + + + + 1000000000.000000000000000 + + + 3 + + + 0.1 + + + + + + + Number of pixels (x-axis) + + + + + + + s1 sample distance (m) + + + + + + + 1000000000 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + 1000000000.000000000000000 + + + 3 + + + 0.1 + + + + + + + Sample detector distance (m) + + + + + + + Number of pixels (y-axis) + + + + + + + 1000000000.000000000000000 + + + 3 + + + 0.1 + + + + + + + xi reference (mm) + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Pixel width (mm) + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Source detector distance (m) + + + + + + + 1000000000 + + + + + + + 1000000000.000000000000000 + + + 3 + + + 0.1 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + buttonBox + accepted() + Dialog + accept() + + + 228 + 274 + + + 157 + 274 + + + + + buttonBox + rejected() + Dialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/RefRed/interfaces/refred_main_interface.ui b/RefRed/interfaces/refred_main_interface.ui index 82240b0c..ae4eccd6 100644 --- a/RefRed/interfaces/refred_main_interface.ui +++ b/RefRed/interfaces/refred_main_interface.ui @@ -39,7 +39,7 @@ 0 0 1540 - 1321 + 1315 @@ -1099,6 +1099,19 @@ + + + + + 0 + 0 + + + + Instrument Settings + + + @@ -4305,7 +4318,7 @@ false - 21 + 23 false @@ -5326,7 +5339,7 @@ p, li { white-space: pre-wrap; } 0 0 1560 - 20 + 24 @@ -5658,6 +5671,12 @@ p, li { white-space: pre-wrap; }
RefRed/interfaces/deadtime_entry.h
1 + + InstrumentSettingsEntryPoint + QGroupBox +
RefRed/interfaces/instrument_settings.h
+ 1 +
@@ -6479,22 +6498,6 @@ p, li { white-space: pre-wrap; } - - actionSettings - triggered() - MainWindow - settings_editor() - - - -1 - -1 - - - 784 - 563 - - - actionNew triggered() diff --git a/RefRed/interfaces/settings.ui b/RefRed/interfaces/settings.ui deleted file mode 100644 index d1007e85..00000000 --- a/RefRed/interfaces/settings.ui +++ /dev/null @@ -1,144 +0,0 @@ - - - MainWindow - - - Qt::NonModal - - - - 0 - 0 - 800 - 600 - - - - Settings - - - - - - - Default Values - - - - - - - false - - - true - - - - New Row - - - - - New Row - - - - - New Column - - - - - - - - NB: Hit ENTER to validate changes in each cell! - - - - - - - UNLOCK ! - - - - - - - - - 0 - 0 - 800 - 25 - - - - - File - - - - - - - - - - false - - - Save - - - - - true - - - Reset - - - - - - - lockButton - clicked() - MainWindow - edit_button() - - - 399 - 555 - - - 399 - 299 - - - - - actionReset - triggered() - MainWindow - reset_button() - - - -1 - -1 - - - 399 - 299 - - - - - - edit_button() - reset_button() - - diff --git a/RefRed/interfaces/settings_password.ui b/RefRed/interfaces/settings_password.ui deleted file mode 100644 index c206d48a..00000000 --- a/RefRed/interfaces/settings_password.ui +++ /dev/null @@ -1,106 +0,0 @@ - - - Dialog - - - Qt::WindowModal - - - - 0 - 0 - 400 - 78 - - - - - 0 - 0 - - - - - 400 - 78 - - - - - 400 - 78 - - - - Dialog - - - - - - - - PASSWORD : - - - - - - - Qt::ImhHiddenText - - - QLineEdit::Password - - - - - - - - - Qt::Vertical - - - QDialogButtonBox::Cancel|QDialogButtonBox::Ok - - - - - - - - - buttonBox - accepted() - Dialog - accept() - - - 248 - 254 - - - 157 - 274 - - - - - buttonBox - rejected() - Dialog - reject() - - - 316 - 260 - - - 286 - 274 - - - - - diff --git a/RefRed/interfaces/sf_calculator_interface.ui b/RefRed/interfaces/sf_calculator_interface.ui index 0f28ef2c..76174055 100644 --- a/RefRed/interfaces/sf_calculator_interface.ui +++ b/RefRed/interfaces/sf_calculator_interface.ui @@ -7,7 +7,7 @@ 0 0 1221 - 776 + 774 @@ -26,10 +26,23 @@ 0 0 1187 - 914 + 1010 + + + + <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> +<html><head><meta name="qrichtext" content="1" /><style type="text/css"> +p, li { white-space: pre-wrap; } +</style></head><body style=" font-family:'Ubuntu Sans'; font-size:11pt; font-weight:400; font-style:normal;"> +<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; text-decoration: underline; color:#e01b24;">WARNING</span><span style=" color:#e01b24;"> </span></p> +<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000;">The Scaling Factor Calculator is now obsolete, and may not use the most recent instrument geometry parameters. </span></p> +<p align="center" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" color:#000000;">Please speak to an instrument team member for details. </span></p></body></html> + + + @@ -1139,7 +1152,7 @@ 0 0 1221 - 22 + 24 diff --git a/RefRed/main.py b/RefRed/main.py index 352c87c7..c5b89b6e 100644 --- a/RefRed/main.py +++ b/RefRed/main.py @@ -1,20 +1,28 @@ -# import sys import logging import os import numpy as np from qtpy import QtCore, QtWidgets +import RefRed.config.gui from RefRed.about_dialog import AboutDialog from RefRed.autopopulatemaintable.reductiontable_auto_fill import ReductionTableAutoFill from RefRed.browsing_runs import BrowsingRuns from RefRed.config.mantid_config import MantidConfig from RefRed.configuration.loading_configuration import LoadingConfiguration from RefRed.configuration.saving_configuration import SavingConfiguration -from RefRed.configuration.user_configuration_handler import RetrieveUserConfiguration, SaveUserConfiguration -from RefRed.decorators import config_file_has_been_modified, config_file_modification_reset +from RefRed.configuration.user_configuration_handler import ( + RetrieveUserConfiguration, + SaveUserConfiguration, +) +from RefRed.decorators import ( + config_file_has_been_modified, + config_file_modification_reset, +) from RefRed.export.export_plot_ascii import ExportPlotAscii -from RefRed.gui_handling.auto_tof_range_radio_button_handler import AutoTofRangeRadioButtonHandler +from RefRed.gui_handling.auto_tof_range_radio_button_handler import ( + AutoTofRangeRadioButtonHandler, +) from RefRed.gui_handling.data_norm_spinboxes import ( DataBackSpinbox, DataLowResSpinbox, @@ -30,14 +38,29 @@ from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.observer import SpinBoxObserver from RefRed.gui_handling.refred_interface_handler import RefRedInterfaceHandler -from RefRed.gui_handling.scaling_factor_widgets_handler import ScalingFactorWidgetsHandler -from RefRed.gui_handling.stitching_yscale_options_radio_button_handler import StitchingYScaleOptionsRadioButtonHandler +from RefRed.gui_handling.scaling_factor_widgets_handler import ( + ScalingFactorWidgetsHandler, +) +from RefRed.gui_handling.stitching_yscale_options_radio_button_handler import ( + StitchingYScaleOptionsRadioButtonHandler, +) from RefRed.initialization.gui import Gui as InitializeGui from RefRed.initialization.gui_connections import GuiConnections as MakeGuiConnections from RefRed.interfaces import load_ui -from RefRed.interfaces.deadtime_settings import DeadTimeSettingsModel, DeadTimeSettingsView -from RefRed.load_reduced_data_set.load_reduced_data_set_handler import LoadReducedDataSetHandler -from RefRed.load_reduced_data_set.reduced_ascii_data_right_click import ReducedAsciiDataRightClick +from RefRed.interfaces.deadtime_settings import ( + DeadTimeSettingsModel, + DeadTimeSettingsView, +) +from RefRed.interfaces.instrument_settings import ( + InstrumentSettings, + InstrumentSettingsDialog, +) +from RefRed.load_reduced_data_set.load_reduced_data_set_handler import ( + LoadReducedDataSetHandler, +) +from RefRed.load_reduced_data_set.reduced_ascii_data_right_click import ( + ReducedAsciiDataRightClick, +) from RefRed.metadata.metadata_finder import MetadataFinder from RefRed.plot.background_settings import BackgroundSettingsView, backgrounds_settings from RefRed.plot.display_plots import DisplayPlots @@ -48,13 +71,19 @@ from RefRed.preview_config.preview_config import PreviewConfig from RefRed.reduction.live_reduction_handler import LiveReductionHandler from RefRed.reduction.reduced_data_handler import ReducedDataHandler -from RefRed.reduction_table_handling.const_q_checkbox_handler import ConstQCheckBoxHandler -from RefRed.reduction_table_handling.reduction_table_check_box import ReductionTableCheckBox -from RefRed.reduction_table_handling.reduction_table_handler import ReductionTableHandler -from RefRed.reduction_table_handling.reduction_table_right_click import ReductionTableRightClick +from RefRed.reduction_table_handling.const_q_checkbox_handler import ( + ConstQCheckBoxHandler, +) +from RefRed.reduction_table_handling.reduction_table_check_box import ( + ReductionTableCheckBox, +) +from RefRed.reduction_table_handling.reduction_table_handler import ( + ReductionTableHandler, +) +from RefRed.reduction_table_handling.reduction_table_right_click import ( + ReductionTableRightClick, +) from RefRed.reduction_table_handling.update_reduction_table import UpdateReductionTable -from RefRed.settings.initialize_settings import InitializeSettings -from RefRed.settings.settings_editor import SettingsEditor from RefRed.sf_calculator.sf_calculator import SFCalculator from RefRed.sf_preview.sf_preview import SFPreview from RefRed.tabledata import TableData @@ -132,7 +161,9 @@ def __init__(self, argv=[], parent=None): QtWidgets.QMainWindow.__init__(self, parent, QtCore.Qt.Window) self.ui = load_ui("refred_main_interface.ui", self) - InitializeSettings(self) + # Get default values for widgets + self.gui_metadata = RefRed.config.gui.gui_metadata + self.config = MantidConfig(self) InitializeGui(self) self.ui.reductionTable.setUI(self) @@ -160,6 +191,11 @@ def __init__(self, argv=[], parent=None): self.ui.deadtime_entry.applyCheckBox.stateChanged.connect(self.apply_deadtime_update) self.ui.deadtime_entry.settingsButton.clicked.connect(self.show_deadtime_settings) + # instrument_settings connections + self.instrument_settings = InstrumentSettings() + self.ui.instrument_settings_entry.applyCheckBox.stateChanged.connect(self.toggle_instrument_settings) + self.ui.instrument_settings_entry.settingsButton.clicked.connect(self.show_instrument_settings) + # home button of plots def home_clicked_yi_plot(self): HomePlotButtonClicked(parent=self, plot_type="yi") @@ -475,7 +511,11 @@ def data_norm_sequence_event(self, *args, **kwargs): @config_file_has_been_modified def data_sequence_event(self, *args, **kwargs): str_data_input = self.ui.data_sequence_lineEdit.text() - ReductionTableAutoFill(parent=self, list_of_run_from_input=str_data_input, data_type_selected="data") + ReductionTableAutoFill( + parent=self, + list_of_run_from_input=str_data_input, + data_type_selected="data", + ) self.ui.data_sequence_lineEdit.setText("") self.norm_sequence_event() @@ -488,7 +528,11 @@ def data_browse_button(self, *args, **kwargs): @config_file_has_been_modified def norm_sequence_event(self, *args, **kwargs): str_norm_input = self.ui.norm_sequence_lineEdit.text() - ReductionTableAutoFill(parent=self, list_of_run_from_input=str_norm_input, data_type_selected="norm") + ReductionTableAutoFill( + parent=self, + list_of_run_from_input=str_norm_input, + data_type_selected="norm", + ) self.ui.norm_sequence_lineEdit.setText("") @config_file_has_been_modified @@ -666,10 +710,6 @@ def about_message(self): o_about_message = AboutDialog(parent=self) o_about_message.display() - def settings_editor(self): - o_settings_editor = SettingsEditor(parent=self) - o_settings_editor.show() - def apply_deadtime_update(self): r"""Update option apply_deadtime of field deadtime_settings when the associated checkbox changes its state""" @@ -681,12 +721,47 @@ def show_deadtime_settings(self): r"""Show the dialog for dead-time options. Update attribue deadtime options upon closing the dialog.""" view = DeadTimeSettingsView(parent=self) view.set_state( - self.deadtime_settings.paralyzable, self.deadtime_settings.dead_time, self.deadtime_settings.tof_step + self.deadtime_settings.paralyzable, + self.deadtime_settings.dead_time, + self.deadtime_settings.tof_step, ) view.exec_() # update the dead time settings of the Main GUI after user has closed the dialog for option in ["paralyzable", "dead_time", "tof_step"]: setattr(self.deadtime_settings, option, view.options[option]) + # Instrument settings + + def toggle_instrument_settings(self): + """Update option apply_deadtime of field deadtime_settings when the associated checkbox + changes its state""" + self.instrument_settings.apply_instrument_settings = self.ui.instrument_settings_entry.applyCheckBox.isChecked() + + def show_instrument_settings(self): + """Show the dialog for instrument settings. Update attribues options upon closing the dialog.""" + view = InstrumentSettingsDialog(parent=self) + view.set_state( + self.instrument_settings.source_detector_distance, + self.instrument_settings.sample_detector_distance, + self.instrument_settings.num_x_pixels, + self.instrument_settings.num_y_pixels, + self.instrument_settings.pixel_width, + self.instrument_settings.xi_reference, + self.instrument_settings.s1_sample_distance, + ) + view.exec_() + + # update the instrument settings of the Main GUI after user has closed the dialog + for option in [ + "source_detector_distance", + "sample_detector_distance", + "num_x_pixels", + "num_y_pixels", + "pixel_width", + "xi_reference", + "s1_sample_distance", + ]: + setattr(self.instrument_settings, option, view.options[option]) + def closeEvent(self, event=None): SaveUserConfiguration(parent=self) diff --git a/RefRed/reduction/global_reduction_settings_handler.py b/RefRed/reduction/global_reduction_settings_handler.py index c25d9114..8a6ceff3 100644 --- a/RefRed/reduction/global_reduction_settings_handler.py +++ b/RefRed/reduction/global_reduction_settings_handler.py @@ -1,4 +1,3 @@ -# RefRed imports from RefRed.configuration.global_settings import GlobalSettings @@ -37,6 +36,7 @@ def retrieve_settings(self): "tof_steps": float(self.parent.ui.eventTofBins.text()), "apply_normalization": self.parent.ui.useNormalizationFlag.isChecked(), "dead_time": self.parent.deadtime_settings, # an instance of `DeadTimeSettingsModel` + "instrument_settings": self.parent.instrument_settings, # an instance of `InstrumentSettings` } ) diff --git a/RefRed/reduction/live_reduction_handler.py b/RefRed/reduction/live_reduction_handler.py index c7ccbf42..0676de0c 100644 --- a/RefRed/reduction/live_reduction_handler.py +++ b/RefRed/reduction/live_reduction_handler.py @@ -1,4 +1,3 @@ -# standard imports import json import logging import os @@ -6,17 +5,18 @@ import time import numpy as np - -# third-party imports from lr_reduction import reduction_template_reader, template from qtpy.QtWidgets import QApplication, QFileDialog -# RefRed imports from RefRed.gui_handling.progressbar_handler import ProgressBarHandler from RefRed.lconfigdataset import LConfigDataset from RefRed.mantid_utility import MantidUtility -from RefRed.reduction.global_reduction_settings_handler import GlobalReductionSettingsHandler -from RefRed.reduction.individual_reduction_settings_handler import IndividualReductionSettingsHandler +from RefRed.reduction.global_reduction_settings_handler import ( + GlobalReductionSettingsHandler, +) +from RefRed.reduction.individual_reduction_settings_handler import ( + IndividualReductionSettingsHandler, +) from RefRed.reduction.live_calculate_sf import LiveCalculateSF from RefRed.reduction.live_reduced_data_handler import LiveReducedDataHandler from RefRed.status_message_handler import StatusMessageHandler @@ -37,7 +37,9 @@ def recalculate(self, replot_only=False): # scale if not replot_only: o_calculate_sf = LiveCalculateSF( - parent=self.parent, row_index=row_index, n_runs=self.nbr_reduction_process + parent=self.parent, + row_index=row_index, + n_runs=self.nbr_reduction_process, ) o_calculate_sf.run() @@ -86,8 +88,7 @@ def run(self): normalize=reduction_pars["apply_normalization"], ) self.save_reduction(row_index, refl=[q, r, dr], info=info) - # TODO: catch specific exceptions - except: # noqa: E722 + except: logging.error(sys.exc_info()[1]) self.parent.ui.reduceButton.setEnabled(True) StatusMessageHandler(parent=self.parent, message="Failed!", is_threaded=True) @@ -154,7 +155,12 @@ def save_stitching_plot_view(self): data = big_table_data[0, 0] [xmin, xmax] = self.parent.ui.data_stitching_plot.canvas.ax.xaxis.get_view_interval() [ymin, ymax] = self.parent.ui.data_stitching_plot.canvas.ax.yaxis.get_view_interval() - data.all_plot_axis.reduced_plot_stitching_tab_data_interval = [xmin, xmax, ymin, ymax] + data.all_plot_axis.reduced_plot_stitching_tab_data_interval = [ + xmin, + xmax, + ymin, + ymax, + ] big_table_data[0, 0] = data self.parent.big_table_data = big_table_data diff --git a/RefRed/settings/__init__.py b/RefRed/settings/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/RefRed/settings/initialize_settings.py b/RefRed/settings/initialize_settings.py deleted file mode 100644 index 7063d41e..00000000 --- a/RefRed/settings/initialize_settings.py +++ /dev/null @@ -1,36 +0,0 @@ -from qtpy.QtCore import QSettings # type: ignore - -from RefRed import APPNAME, ORGANIZATION -from RefRed.settings.list_settings import ListSettings - - -class InitializeSettings(object): - def __init__(self, parent=None, qsettings=None): - self.parent = parent - - o_list_settings = ListSettings() - - if qsettings: - _settings = qsettings - else: # load from filesystem - _settings = QSettings(ORGANIZATION, APPNAME) - - _gui_metadata = {} - for _key in list(o_list_settings.__dict__.keys()): - _gui_metadata[_key] = self.__getValue(_key, o_list_settings, _settings) - - self.parent.gui_metadata = _gui_metadata - - def __getValue(self, key: str, lsettings, qsettings): - # default value - value = lsettings.__dict__[key] - # value from qsettings - if qsettings.contains(key): - _value = str(qsettings.value(key) or "").strip() - if _value: - value = _value - - # convert to correct primative type - value = float(value) - - return value diff --git a/RefRed/settings/list_settings.py b/RefRed/settings/list_settings.py deleted file mode 100644 index 961c3240..00000000 --- a/RefRed/settings/list_settings.py +++ /dev/null @@ -1,28 +0,0 @@ -class ListSettings(object): - def __init__(self): - self.q_min = 0.005 - self.d_q0 = 0.0 - self.dq_over_q = 0.028 - self.tof_bin = 40 # micros - self.q_bin = 0.01 # logarithmic binning - self.angle_offset = 0.0 - self.angle_offset_error = 0.001 - - def __eq__(self, other) -> bool: - if isinstance(other, dict): - for attrname in [ - "q_min", - "d_q0", - "dq_over_q", - "tof_bin", - "q_bin", - "angle_offset", - "angle_offset_error", - ]: - if getattr(self, attrname) != other[attrname]: - return False - - return True - - # don't know how to compare so must be different - return False diff --git a/RefRed/settings/settings_editor.py b/RefRed/settings/settings_editor.py deleted file mode 100644 index bbc6611b..00000000 --- a/RefRed/settings/settings_editor.py +++ /dev/null @@ -1,79 +0,0 @@ -from qtpy import QtCore, QtWidgets - -from RefRed.gui_handling.gui_utility import GuiUtility -from RefRed.interfaces import load_ui -from RefRed.settings.list_settings import ListSettings -from RefRed.settings.settings_password_editor import SettingsPasswordEditor - - -class SettingsEditor(QtWidgets.QMainWindow): - is_super_user = False - - def __init__(self, parent=None, loadUI: bool = True): - self.parent = parent - QtWidgets.QMainWindow.__init__(self, parent=parent) - if loadUI: - # in testing populate_table should be called once self.ui has been mocked - self.ui = load_ui("settings.ui", self) - self.populate_table() - - def populate_table(self): - _gui_metadata = self.parent.gui_metadata - - _list_keys = list(_gui_metadata.keys()) - nbr_key = len(_list_keys) - self.ui.tableWidget.setColumnCount(1) - self.ui.tableWidget.setRowCount(nbr_key) - self.ui.tableWidget.setVerticalHeaderLabels(_list_keys) - self.ui.tableWidget.setHorizontalHeaderLabels(["Value"]) - - for _index, _key in enumerate(_gui_metadata.keys()): - _item = QtWidgets.QTableWidgetItem() - _item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable) - _value = str(_gui_metadata[_key]) - _item.setText(_value) - self.ui.tableWidget.setItem(_index, 0, _item) - - def reset_button(self): - """reset all the settings to default value hard coded in program""" - o_list_settings = ListSettings() - _list_keys = list(o_list_settings.__dict__.keys()) - - _gui_metadata = {} - for _key in _list_keys: - _value = o_list_settings.__dict__[_key] - _gui_metadata[_key] = _value - self.parent.gui_metadata = _gui_metadata - - # refresh table - self.populate_table() - - def edit_button(self): - if str(self.ui.lockButton.text()) == "LOCK !": - self.ui.lockButton.setText("UNLOCK !") - self.is_super_user = False - self.check_editor_button() - return - - o_pass = SettingsPasswordEditor(parent=self) - o_pass.show() - - def check_editor_button(self): - self.ui.tableWidget.setEnabled(self.is_super_user) - self.ui.actionReset.setEnabled(self.is_super_user) - self.ui.actionSave.setEnabled(self.is_super_user) - - def closeEvent(self, event=None): - # saving back all the settings - nbr_row = self.ui.tableWidget.rowCount() - _gui_metadata = {} - for _row in range(nbr_row): - _label = str(self.ui.tableWidget.verticalHeaderItem(_row).text()) - _value = float(self.ui.tableWidget.item(_row, 0).text()) - _gui_metadata[_label] = _value - self.parent.gui_metadata = _gui_metadata - print(self.parent.gui_metadata) - - # update GUI widgets - o_gui = GuiUtility(parent=self.parent) - o_gui.init_widgets_value() diff --git a/RefRed/settings/settings_password_editor.py b/RefRed/settings/settings_password_editor.py deleted file mode 100644 index 0f8af60a..00000000 --- a/RefRed/settings/settings_password_editor.py +++ /dev/null @@ -1,26 +0,0 @@ -from qtpy import QtWidgets - -from RefRed.interfaces import load_ui - - -class SettingsPasswordEditor(QtWidgets.QDialog): - password = "5" - - def __init__(self, parent=None): - self.parent = parent - QtWidgets.QDialog.__init__(self, parent=parent) - self.ui = load_ui("settings_password.ui", self) - - def closeEvent(self, event=None): - pass - - def accept(self): - _user_pass = str(self.ui.lineEdit.text()) - if _user_pass == self.password: - self.parent.is_super_user = True - else: - self.parent.is_super_user = False - self.parent.check_editor_button() - if self.parent.is_super_user: - self.parent.ui.lockButton.setText("LOCK !") - self.close() diff --git a/RefRed/sf_calculator/lr_data.py b/RefRed/sf_calculator/lr_data.py index bdf9bb02..b6658fea 100644 --- a/RefRed/sf_calculator/lr_data.py +++ b/RefRed/sf_calculator/lr_data.py @@ -136,9 +136,9 @@ def __init__(self, workspace, read_options): [peak1, peak2] = pf.getPeaks() self.peak = [str(peak1), str(peak2)] - backOffsetFromPeak = self.read_options["back_offset_from_peak"] - back1 = int(peak1 - backOffsetFromPeak) - back2 = int(peak2 + backOffsetFromPeak) + back_offset_from_peak = self.read_options["back_offset_from_peak"] + back1 = int(peak1 - back_offset_from_peak) + back2 = int(peak2 + back_offset_from_peak) self.back = [str(back1), str(back2)] # Properties for easy data access # @@ -238,7 +238,7 @@ def calculate_theta(self, with_offset=True): angle_offset_deg = angle_offset return theta + angle_offset_deg * math.pi / 180.0 - def _getIxyt(self, nxs_histo): + def _get_Ixyt(self, nxs_histo): """ will format the histogrma NeXus to retrieve the full 3D data set """ @@ -252,7 +252,7 @@ def _getIxyt(self, nxs_histo): def _read_data(self, workspace): nxs_histo = Rebin(InputWorkspace=workspace, Params=self.binning, PreserveEvents=True) # retrieve 3D array - [_tof_axis, Ixyt] = self._getIxyt(nxs_histo) + [_tof_axis, Ixyt] = self._get_Ixyt(nxs_histo) nxs_histo.delete() self.tof_axis_auto_with_margin = _tof_axis diff --git a/pyproject.toml b/pyproject.toml index 9e889120..c52b2c18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,7 +17,16 @@ extend-exclude = [ [tool.ruff.lint] select = ["A", "ARG", "ASYNC", "BLE", "C90", "E", "F", "I", "N", "UP032", "W"] -ignore = ["F821", "E402"] +ignore = [ + "ARG001", # Unused function argument + "ARG002", # Unused method argument + "E402", # module level import not at top of file + "E722", # do not use bare 'except' + "F821", # undefined name + "N802", # function name should be lowercase + "N803", # argument name should be lowercase + "N806", # variable in function should be lowercase +] [tool.mypy] ignore_missing_imports = true diff --git a/setup.py b/setup.py index 81fe7918..fa550cea 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,6 @@ def read_requirements_from_file(filepath): "RefRed.preview_config", "RefRed.reduction", "RefRed.reduction_table_handling", - "RefRed.settings", "RefRed.sf_calculator", "RefRed.sf_preview", "RefRed.thread", diff --git a/test/data/test_instrument_settings.xml b/test/data/test_instrument_settings.xml new file mode 100644 index 00000000..dd7fe665 --- /dev/null +++ b/test/data/test_instrument_settings.xml @@ -0,0 +1,464 @@ + + REFL + Tuesday, 04. February 2025 01:55PM + 2.2.0.dev44+d202502041807 + 6.10.0 +RefRed-5.1.0+52.g206bd51.dirty + + + narrow + 128 + 141 + N/A + True + False + 125 + 144 + 0 + 0 + True + 51977.0051592 + 65268.5238077 + 0.007880615154094448 + 0.009895208501757688 + 13.30 + 16.70 + 1.2001272419410811 + 188298 + 70 + 185 + True + N/A + N/A + 15.0 + True + True + 187 + 75 + 130 + 139 + True + False + 127 + 142 + 0 + 0 + 15.0 + 188230 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + narrow + 129 + 141 + N/A + True + False + 126 + 144 + 0 + 0 + True + 41761.0114019 + 55052.5300504 + 0.009332213946679904 + 0.012300364313257236 + 10.69 + 14.09 + 1.1990750579410812 + 188299 + 70 + 181 + True + N/A + N/A + 12.386 + True + True + 193 + 74 + 131 + 139 + True + False + 128 + 142 + 0 + 0 + 12.386 + 188231 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + narrow + 128 + 141 + N/A + True + False + 125 + 144 + 0 + 0 + True + 31419.955747 + 44711.4743955 + 0.011493959310202783 + 0.016354588869243764 + 8.04 + 11.44 + 1.1990750579410812 + 188300 + 72 + 185 + True + N/A + N/A + 9.74 + True + True + 184 + 78 + 131 + 139 + True + False + 128 + 142 + 0 + 0 + 9.74 + 188232 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + narrow + 129 + 142 + N/A + True + False + 126 + 145 + 0 + 0 + True + 20879.5826929 + 34171.1013413 + 0.01504472477216474 + 0.024623763016614203 + 5.34 + 8.74 + 1.1990750579410812 + 188301 + 74 + 183 + True + N/A + N/A + 7.043 + True + True + 157 + 111 + 131 + 139 + True + False + 128 + 142 + 0 + 0 + 7.043 + 188233 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + narrow + 129 + 141 + N/A + True + False + 126 + 144 + 0 + 0 + True + 9964.0239461 + 23255.5425945 + 0.02209931000146552 + 0.051565056670086214 + 2.55 + 5.95 + 1.1990750579410812 + 188302 + 70 + 183 + True + N/A + N/A + 4.25 + True + True + 147 + 120 + 131 + 139 + True + False + 128 + 142 + 0 + 0 + 4.25 + 188234 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + narrow + 130 + 140 + N/A + True + False + 127 + 143 + 0 + 0 + True + 9964.0239461 + 23255.5425945 + 0.04360142191654566 + 0.10173665113860655 + 2.55 + 5.95 + 2.3658719579410814 + 188303 + 75 + 181 + True + N/A + N/A + 4.25 + True + True + 147 + 120 + 131 + 139 + True + False + 128 + 142 + 0 + 0 + 4.25 + 188234 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + narrow + 129 + 138 + N/A + True + False + 126 + 141 + 0 + 0 + True + 9964.0239461 + 23255.5425945 + 0.08630890118114465 + 0.20138743608933754 + 2.55 + 5.95 + 4.684209089941081 + 188304 + 75 + 180 + True + N/A + N/A + 4.25 + True + True + 147 + 120 + 131 + 139 + True + False + 128 + 142 + 0 + 0 + 4.25 + 188234 + False + 0 + 0 + 0.02 + 0.005 + True + test/data/sf_186529_Si_auto.cfg + Si + 0 + True + True + True + 9.2 + 400.0 + True + 2.0 + 3.0 + 4 + 5 + 6.0 + 7.0 + 8.0 + + False + + + diff --git a/test/unit/RefRed/configuration/test_export_xml_config.py b/test/unit/RefRed/configuration/test_export_xml_config.py index 8a558a96..27e8c2c4 100644 --- a/test/unit/RefRed/configuration/test_export_xml_config.py +++ b/test/unit/RefRed/configuration/test_export_xml_config.py @@ -26,7 +26,7 @@ def test_header_part(self, mantid_mock, refred_mock): def test_main_part(self): config = ExportXMLConfig(MagicMock()) config.main_part() - assert len(config.str_array) == 55 + assert len(config.str_array) == 56 if __name__ == "__main__": diff --git a/test/unit/RefRed/configuration/test_loading_configuration.py b/test/unit/RefRed/configuration/test_loading_configuration.py index 290c657b..90135124 100644 --- a/test/unit/RefRed/configuration/test_loading_configuration.py +++ b/test/unit/RefRed/configuration/test_loading_configuration.py @@ -107,9 +107,19 @@ def side_effect(node, arg): loadingConfiguration.parent.deadtime_settings = mock_deadtime_settings # Mock the applyCheckBox object and its method - mock_applyCheckBox = mock.MagicMock() - mock_applyCheckBox.setChecked = mock.Mock() - loadingConfiguration.parent.ui.deadtime_entry.applyCheckBox = mock_applyCheckBox + mock_apply_deadtime_checkbox = mock.MagicMock() + mock_apply_deadtime_checkbox.setChecked = mock.Mock() + loadingConfiguration.parent.ui.deadtime_entry.applyCheckBox = mock_apply_deadtime_checkbox + + # Mock instrument_settings object and its method + mock_instrument_settings = mock.MagicMock() + mock_instrument_settings.from_xml = mock.Mock() + loadingConfiguration.parent.instrument_settings = mock_instrument_settings + + # Mock the applyCheckBox object and its method + mock_apply_instrument_settings_checkbox = mock.MagicMock() + mock_apply_instrument_settings_checkbox.setChecked = mock.Mock() + loadingConfiguration.parent.ui.instrument_settings_entry.applyCheckBox = mock_apply_instrument_settings_checkbox # call the method of interest loadingConfiguration.populate_main_gui_general_settings() @@ -120,10 +130,17 @@ def side_effect(node, arg): # Assert if the 'from_xml' method of 'deadtime_settings' is called mock_deadtime_settings.from_xml.assert_called_once_with(node_0) # Assert if the 'setChecked' method of 'applyCheckBox' is called - mock_applyCheckBox.setChecked.assert_called_once_with( + mock_apply_deadtime_checkbox.setChecked.assert_called_once_with( loadingConfiguration.parent.deadtime_settings.apply_deadtime ) + # Assert if the 'from_xml' method of 'instrument_settings' is called + mock_instrument_settings.from_xml.assert_called_once_with(node_0) + # Assert if the 'setChecked' method of 'applyCheckBox' is called + mock_apply_instrument_settings_checkbox.setChecked.assert_called_once_with( + loadingConfiguration.parent.instrument_settings.apply_instrument_settings + ) + # test that iMetadata.data_peak gets set properly def test_getMetadataObject(self): loader = self.test_init() diff --git a/test/unit/RefRed/interfaces/test_deadtime_entry.py b/test/unit/RefRed/interfaces/test_deadtime_entry.py index 226fbb4f..338b35cb 100644 --- a/test/unit/RefRed/interfaces/test_deadtime_entry.py +++ b/test/unit/RefRed/interfaces/test_deadtime_entry.py @@ -1,9 +1,7 @@ -# third party imports import pytest from qtpy.QtCore import Qt # type: ignore -# RefRed imports -from RefRed.interfaces.deadtime_entry import DeadTimeEntryPoint # Make sure to import your class correctly +from RefRed.interfaces.deadtime_entry import DeadTimeEntryPoint @pytest.fixture diff --git a/test/unit/RefRed/interfaces/test_instrument_settings.py b/test/unit/RefRed/interfaces/test_instrument_settings.py new file mode 100644 index 00000000..a644b688 --- /dev/null +++ b/test/unit/RefRed/interfaces/test_instrument_settings.py @@ -0,0 +1,109 @@ +from xml.dom.minidom import parseString + +import pytest +from qtpy.QtCore import Qt # type: ignore + +from RefRed.interfaces.instrument_settings import InstrumentSettings, InstrumentSettingsEntryPoint + +# Test the InstrumentSettingsEntryPoint + + +@pytest.fixture +def instrument_settings_entry_point(qtbot): + widget = InstrumentSettingsEntryPoint() + qtbot.addWidget(widget) + return widget + + +def test_initial_state(instrument_settings_entry_point): + assert not instrument_settings_entry_point.applyCheckBox.isChecked() + assert not instrument_settings_entry_point.settingsButton.isEnabled() + + +def test_checkbox_interaction(instrument_settings_entry_point, qtbot): + # Simulate checking the checkbox + qtbot.mouseClick(instrument_settings_entry_point.applyCheckBox, Qt.LeftButton) + # Test if the checkbox is checked + assert instrument_settings_entry_point.applyCheckBox.isChecked() + # Test if the settings button is now enabled + assert instrument_settings_entry_point.settingsButton.isEnabled() + + +def test_uncheck_checkbox(instrument_settings_entry_point, qtbot): + # First, check the checkbox + qtbot.mouseClick(instrument_settings_entry_point.applyCheckBox, Qt.LeftButton) + # Now, uncheck it + qtbot.mouseClick(instrument_settings_entry_point.applyCheckBox, Qt.LeftButton) + # Test if the checkbox is unchecked + assert not instrument_settings_entry_point.applyCheckBox.isChecked() + # Test if the settings button is now disabled + assert not instrument_settings_entry_point.settingsButton.isEnabled() + + +# Test the InstrumentSettings Model + + +class TestInstrumentSettingsModel: + custom_settings = { + "apply_instrument_settings": True, + "source_detector_distance": 1.0, + "sample_detector_distance": 2.0, + "num_x_pixels": 3, + "num_y_pixels": 4, + "pixel_width": 5.0, + "xi_reference": 6.0, + "s1_sample_distance": 7.0, + } + + def test_initialization_with_defaults(self): + model = InstrumentSettings() + assert model.apply_instrument_settings is False + assert model.source_detector_distance == 15.75 + assert model.sample_detector_distance == 1.83 + assert model.num_x_pixels == 256 + assert model.num_y_pixels == 304 + assert model.pixel_width == 0.70 + assert model.xi_reference == 445 + assert model.s1_sample_distance == 1.485 + + def test_initialization_with_custom_values(self): + model = InstrumentSettings(**self.custom_settings) + assert model.__dict__ == self.custom_settings + + def test_to_xml(self): + expected_xml = ( + "True\n" + "1.0\n" + "2.0\n" + "3\n" + "4\n" + "5.0\n" + "6.0\n" + "7.0\n" + ) + model = InstrumentSettings(**self.custom_settings) + xml_output = model.to_xml() + assert xml_output == expected_xml + + def test_from_xml(self): + xml_input = ( + "" + "True\n" + "True\n" + "1.0\n" + "2.0\n" + "3\n" + "4\n" + "5.0\n" + "6.0\n" + "7.0\n" + "True\n" + "" + ) + dom = parseString(xml_input) + model = InstrumentSettings().from_xml(dom.documentElement) + assert model.__dict__ == self.custom_settings + + +if __name__ == "__main__": + pytest.main([__file__]) diff --git a/test/unit/RefRed/settings/test_edit_settings.py b/test/unit/RefRed/settings/test_edit_settings.py deleted file mode 100644 index 3f3eda8f..00000000 --- a/test/unit/RefRed/settings/test_edit_settings.py +++ /dev/null @@ -1,52 +0,0 @@ -# package imports -import unittest.mock as mock - -# third party packages -import pytest - -from RefRed.settings.list_settings import ListSettings -from RefRed.settings.settings_editor import SettingsEditor - -DEFAULT_SETTINGS = ListSettings() - - -class TestEditSettings(object): - gui_metadata = { - "q_min": DEFAULT_SETTINGS.q_min, - "d_q0": DEFAULT_SETTINGS.d_q0, - "dq_over_q": DEFAULT_SETTINGS.dq_over_q, - "tof_bin": DEFAULT_SETTINGS.tof_bin, - "q_bin": DEFAULT_SETTINGS.q_bin, - "angle_offset": DEFAULT_SETTINGS.angle_offset, - "angle_offset_error": DEFAULT_SETTINGS.angle_offset_error, - } - """ - {'q_min': 1.005, - 'd_q0': 1.0004, - 'dq_over_q': 1.005, - 'tof_bin': 41, - 'q_bin': 1.01, - 'angle_offset': 1.016, - 'angle_offset_error': 1.001} - """ - - @mock.patch("qtpy.QtWidgets.QMainWindow.__init__") - def test_reset_button(self, mockSuperInit): - # create a parent widget - parent_item = mock.Mock() - parent_item.gui_metadata = self.gui_metadata - # create the object to test - editor = SettingsEditor(parent_item, loadUI=False) - assert mockSuperInit.called - editor.ui = mock.Mock() - editor.populate_table() - # modify a value - parent_item.gui_metadata["d_q0"] = 1.0004 - assert parent_item.gui_metadata != DEFAULT_SETTINGS, "should have changed" - # reset everything - editor.reset_button() - assert parent_item.gui_metadata == DEFAULT_SETTINGS, "should be identical" - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/test/unit/RefRed/settings/test_initialize_settings.py b/test/unit/RefRed/settings/test_initialize_settings.py deleted file mode 100644 index 6afb2046..00000000 --- a/test/unit/RefRed/settings/test_initialize_settings.py +++ /dev/null @@ -1,49 +0,0 @@ -# package imports -# third party packages -import pytest -from qtpy.QtCore import QSettings # type: ignore - -from RefRed.settings.initialize_settings import InitializeSettings -from RefRed.settings.list_settings import ListSettings - - -class SettingsContext: - def __init__(self, suffix="", items={}): - self.settings = QSettings("neutron", "RefRed" + suffix) - for key, value in items.items(): - self.settings.setValue(key, str(value)) - - def __enter__(self): - return self.settings - - def __exit__(self, type, value, traceback): - self.settings.clear() - - -class TestInitializeSettings(object): - gui_metadata = {} - - def test_initialize_default_settings(self): - with SettingsContext("-TestInitializeSettings") as settings: - InitializeSettings(self, settings) - assert self.gui_metadata == ListSettings() - - def test_initialize_qsettings(self): - values = { - "q_min": 1.005, - "d_q0": 1.0004, - "dq_over_q": 1.005, - "tof_bin": 41, - "q_bin": 1.01, - "angle_offset": 1.016, - "angle_offset_error": 1.001, - } - - with SettingsContext("-TestInitializeSettings", values) as settings: - InitializeSettings(self, settings) - for k in values.keys(): - assert self.gui_metadata[k] == values[k], k - - -if __name__ == "__main__": - pytest.main([__file__]) diff --git a/test/unit/RefRed/test_main.py b/test/unit/RefRed/test_main.py index 386344f7..17b6082f 100644 --- a/test/unit/RefRed/test_main.py +++ b/test/unit/RefRed/test_main.py @@ -1,11 +1,8 @@ -# standard imports import unittest.mock as mock -# third-party imports import pytest from qtpy import QtCore, QtWidgets # type: ignore -# RefRed imports from RefRed.main import MainGui @@ -25,13 +22,13 @@ def test_run_reduction_button(self): @mock.patch("RefRed.main.InitializeGui") @mock.patch("RefRed.main.load_ui") @mock.patch("qtpy.QtWidgets.QMainWindow.__init__") - def test_mock_init(self, mockMainWindowInit, mockLoadUI, mockInitializeGui, mockFileLoadedSignal): + def test_mock_init(self, mock_main_window_init, mock_load_ui, mock_initialize_gui, mock_file_loaded_signal): parent = mock.Mock() MainGui(parent=parent) - mockMainWindowInit.assert_called() - mockLoadUI.assert_called() - mockInitializeGui.assert_called() - mockFileLoadedSignal.connect.assert_called() + mock_main_window_init.assert_called() + mock_load_ui.assert_called() + mock_initialize_gui.assert_called() + mock_file_loaded_signal.connect.assert_called() @mock.patch("RefRed.main.LoadingConfiguration") @mock.patch("RefRed.main.MainGui.file_loaded_signal") @@ -39,12 +36,19 @@ def test_mock_init(self, mockMainWindowInit, mockLoadUI, mockInitializeGui, mock @mock.patch("RefRed.main.load_ui") @mock.patch("qtpy.QtWidgets.QMainWindow.__init__") def test_load_configuration( - self, mockMainWindowInit, mockLoadUI, mockInitializeGui, mockFileLoadedSignal, mockLoadConfiguration + self, + mock_main_window_init, # noqa: ARG002 + mock_load_ui, # noqa: ARG002 + mock_initialize_gui, # noqa: ARG002 + mock_file_loaded_signal, # noqa: ARG002 + mock_load_configuration, ): parent = mock.Mock() - mainGui = MainGui(parent=parent) - mainGui.load_configuration() - mockLoadConfiguration.assert_called() + main_gui = MainGui(parent=parent) + main_gui.load_configuration() + mock_load_configuration.assert_called() + + # Deadtime Settings tests def test_apply_deadtime_update_checked(self, qtbot): """Test the apply_deadtime_update function when the checkbox is checked.""" @@ -68,7 +72,7 @@ def test_show_deadtime_settings_default_values(self, monkeypatch): main_gui = self.app # endow closure environment to MockDeadTimeSettingsView class MockDeadTimeSettingsView: - def __init__(self, parent=None): + def __init__(self, parent=None): # noqa: ARG002 r"""Mocking the DeadTimeSettingsView to return default values without user interaction""" self.options = { "paralyzable": main_gui.deadtime_settings.paralyzable, @@ -97,7 +101,7 @@ def test_show_deadtime_settings_updated_values(self, monkeypatch): new_tof_step = 200 class MockDeadTimeSettingsView: - def __init__(self, parent=None): + def __init__(self, parent=None): # noqa: ARG002 r"""Mocking the DeadTimeSettingsView to return default values without user interaction""" self.options = { "paralyzable": new_paralyzable, @@ -117,6 +121,121 @@ def set_state(self, paralyzable, dead_time, tof_step): assert self.app.deadtime_settings.dead_time == new_dead_time assert self.app.deadtime_settings.tof_step == new_tof_step + # Instrument Settings tests + + def test_instrument_settings_checked(self, qtbot): + """Test the toggle_instrument_settings function when the checkbox is checked.""" + # Ensure checkbox starts unchecked + self.app.ui.instrument_settings_entry.applyCheckBox.setChecked(False) + # Simulate checking the checkbox + qtbot.mouseClick(self.app.ui.instrument_settings_entry.applyCheckBox, QtCore.Qt.LeftButton) + # Assert that the apply_instrument_settings attribute is now True + assert self.app.instrument_settings.apply_instrument_settings is True + + def test_instrument_settings_unchecked(self, qtbot): + """Test the toggle_instrument_settings function when the checkbox is unchecked.""" + # Ensure checkbox starts checked + self.app.ui.instrument_settings_entry.applyCheckBox.setChecked(True) + # Simulate unchecking the checkbox + qtbot.mouseClick(self.app.ui.instrument_settings_entry.applyCheckBox, QtCore.Qt.LeftButton) + # Assert that the apply_instrument_settings attribute is now False + assert self.app.instrument_settings.apply_instrument_settings is False + + def test_show_instrument_settings_default_values(self, monkeypatch): + main_gui = self.app # endow closure environment to MockInstrumentSettingsDialog + + class MockInstrumentSettingsDialog: + def __init__(self, parent=None): # noqa: ARG002 + r"""Mocking the InstrumentSettingsDialog to return default values without user interaction""" + self.options = { + "source_detector_distance": main_gui.instrument_settings.source_detector_distance, + "sample_detector_distance": main_gui.instrument_settings.sample_detector_distance, + "num_x_pixels": main_gui.instrument_settings.num_x_pixels, + "num_y_pixels": main_gui.instrument_settings.num_y_pixels, + "pixel_width": main_gui.instrument_settings.pixel_width, + "xi_reference": main_gui.instrument_settings.xi_reference, + "s1_sample_distance": main_gui.instrument_settings.s1_sample_distance, + } + + def exec_(self): + return QtWidgets.QDialog.Accepted + + def set_state( + self, + source_detector_distance, + sample_detector_distance, + num_x_pixels, + num_y_pixels, + pixel_width, + xi_reference, + s1_sample_distance, + ): + self.options["source_detector_distance"] = source_detector_distance + self.options["sample_detector_distance"] = sample_detector_distance + self.options["num_x_pixels"] = num_x_pixels + self.options["num_y_pixels"] = num_y_pixels + self.options["pixel_width"] = pixel_width + self.options["xi_reference"] = xi_reference + self.options["s1_sample_distance"] = s1_sample_distance + + monkeypatch.setattr("RefRed.main.InstrumentSettingsDialog", MockInstrumentSettingsDialog) + self.app.show_instrument_settings() + assert self.app.instrument_settings.source_detector_distance == 15.75 + assert self.app.instrument_settings.sample_detector_distance == 1.83 + assert self.app.instrument_settings.num_x_pixels == 256 + assert self.app.instrument_settings.num_y_pixels == 304 + assert self.app.instrument_settings.pixel_width == 0.70 + assert self.app.instrument_settings.xi_reference == 445 + assert self.app.instrument_settings.s1_sample_distance == 1.485 + + def test_show_instrument_settings_updated_values(self, monkeypatch): + # endow closure environment to MockInstrumentSettingsDialog + new_source_detector_distance = 1.0 + new_sample_detector_distance = 2.0 + new_num_x_pixels = 3 + new_num_y_pixels = 4 + new_pixel_width = 5.0 + new_xi_reference = 6.0 + new_s1_sample_distance = 7.0 + + class MockInstrumentSettingsDialog: + def __init__(self, parent=None): # noqa: ARG002 + r"""Mocking the InstrumentSettingsDialog to return default values without user interaction""" + self.options = { + "source_detector_distance": new_source_detector_distance, + "sample_detector_distance": new_sample_detector_distance, + "num_x_pixels": new_num_x_pixels, + "num_y_pixels": new_num_y_pixels, + "pixel_width": new_pixel_width, + "xi_reference": new_xi_reference, + "s1_sample_distance": new_s1_sample_distance, + } + + def exec_(self): + return QtWidgets.QDialog.Accepted + + def set_state( + self, + source_detector_distance, + sample_detector_distance, + num_x_pixels, + num_y_pixels, + pixel_width, + xi_reference, + s1_sample_distance, + ): + pass + + monkeypatch.setattr("RefRed.main.InstrumentSettingsDialog", MockInstrumentSettingsDialog) + self.app.show_instrument_settings() + assert self.app.instrument_settings.source_detector_distance == new_source_detector_distance + assert self.app.instrument_settings.sample_detector_distance == new_sample_detector_distance + assert self.app.instrument_settings.num_x_pixels == new_num_x_pixels + assert self.app.instrument_settings.num_y_pixels == new_num_y_pixels + assert self.app.instrument_settings.pixel_width == new_pixel_width + assert self.app.instrument_settings.xi_reference == new_xi_reference + assert self.app.instrument_settings.s1_sample_distance == new_s1_sample_distance + if __name__ == "__main__": pytest.main([__file__]) From 136bf21c45bd7cd1265058c98889215c830b7b5d Mon Sep 17 00:00:00 2001 From: glass-ships Date: Fri, 14 Feb 2025 12:43:43 -0500 Subject: [PATCH 5/6] remaining errors --- RefRed/_version.py | 2 +- RefRed/config/__init__.py | 2 +- RefRed/export/export_plot_ascii.py | 4 +- RefRed/interfaces/mplwidgets.py | 2 +- .../peak_finder_derivation.py | 182 +++++++++--------- .../reduction/calculate_sf_overlap_range.py | 8 +- docs/conf.py | 2 +- pyproject.toml | 5 + 8 files changed, 106 insertions(+), 101 deletions(-) diff --git a/RefRed/_version.py b/RefRed/_version.py index 71bd5ded..d9f0a50f 100644 --- a/RefRed/_version.py +++ b/RefRed/_version.py @@ -47,7 +47,7 @@ def get_config(): return cfg -class NotThisMethod(Exception): +class NotThisMethod(Exception): # noqa: N818 """Exception raised if a method is not valid for the current scenario.""" diff --git a/RefRed/config/__init__.py b/RefRed/config/__init__.py index 6fbccde8..182a8ac0 100644 --- a/RefRed/config/__init__.py +++ b/RefRed/config/__init__.py @@ -74,7 +74,7 @@ def _create_proxy(): continue try: modi = __import__("RefRed.config." + name, fromlist=[name]) - except Exception as error: + except Exception as error: # noqa: BLE001 _warn("Could not import module %s,\n %s: %s" % (name, error.__class__.__name__, error)) continue if "config_path" in modi.__dict__: diff --git a/RefRed/export/export_plot_ascii.py b/RefRed/export/export_plot_ascii.py index b18e0ad8..a221a1e2 100644 --- a/RefRed/export/export_plot_ascii.py +++ b/RefRed/export/export_plot_ascii.py @@ -202,8 +202,8 @@ def export_stitched(self): path = Path(self.parent.path_ascii) default_filename = path / default_filename caption = "Select Location and Name" - filter = "Reduced Ascii (*.txt);; All (*.*)" - filename, filter = QFileDialog.getSaveFileName( + filter = "Reduced Ascii (*.txt);; All (*.*)" # noqa: A001 + filename, filter = QFileDialog.getSaveFileName( # noqa: A001 self.parent, caption, str(default_filename), diff --git a/RefRed/interfaces/mplwidgets.py b/RefRed/interfaces/mplwidgets.py index 79f54ae8..1a6572b8 100644 --- a/RefRed/interfaces/mplwidgets.py +++ b/RefRed/interfaces/mplwidgets.py @@ -271,7 +271,7 @@ def save_figure(self, *args): if figname: try: self.canvas.print_figure(str(figname)) - except Exception as e: + except Exception as e: # noqa: BLE001 QtWidgets.QMessageBox.critical( self, "Error saving file", diff --git a/RefRed/peak_finder_algorithms/peak_finder_derivation.py b/RefRed/peak_finder_algorithms/peak_finder_derivation.py index db652cf4..feb21f64 100644 --- a/RefRed/peak_finder_algorithms/peak_finder_derivation.py +++ b/RefRed/peak_finder_algorithms/peak_finder_derivation.py @@ -22,63 +22,63 @@ class PeakFinderDerivation(object): peak_max_final_value = -1 peak_min_final_value = -1 - def __init__(cls, xdata, ydata, edata=[], back_offset=3): - cls.initArrays() - - cls.xdata = np.array(xdata) - cls.ydata = np.array(ydata) - cls.edata = np.array(edata) - - cls.calculate5HighestPoints() # step2 - cls.calculatePeakPixel() # step3 - - cls.calculateFirstDerivative() # step4 - cls.calculateMinMaxDerivativePixels() # step5 - cls.calculateAvgAndStdDerivative() # step6 - cls.calculateMinMaxSignalPixel() # step7 - - def initArrays(cls): - cls.xdata_firstderi = [] - cls.ydata_firstderi = [] - cls.edata_firstderi = [] - cls.peaks = [-1, -1] - cls.five_highest_ydata = [] - cls.five_highest_xdata = [] - cls.sum_five_highest_ydata = -1 - cls.peak_pixel = -1 - cls.deri_min = 1 - cls.deri_max = -1 - cls.deri_min_pixel_value = -1 - cls.deri_max_pixel_value = -1 - cls.mean_counts_firstderi = -1 - cls.std_deviation_counts_firstderi = -1 - cls.peak_max_final_value = -1 - cls.peak_min_final_value = -1 - - def calculate5HighestPoints(cls): - _xdata = cls.xdata - _ydata = cls.ydata + def __init__(self, xdata, ydata, edata=[], back_offset=3): + self.initArrays() + + self.xdata = np.array(xdata) + self.ydata = np.array(ydata) + self.edata = np.array(edata) + + self.calculate5HighestPoints() # step2 + self.calculatePeakPixel() # step3 + + self.calculateFirstDerivative() # step4 + self.calculateMinMaxDerivativePixels() # step5 + self.calculateAvgAndStdDerivative() # step6 + self.calculateMinMaxSignalPixel() # step7 + + def initArrays(self): + self.xdata_firstderi = [] + self.ydata_firstderi = [] + self.edata_firstderi = [] + self.peaks = [-1, -1] + self.five_highest_ydata = [] + self.five_highest_xdata = [] + self.sum_five_highest_ydata = -1 + self.peak_pixel = -1 + self.deri_min = 1 + self.deri_max = -1 + self.deri_min_pixel_value = -1 + self.deri_max_pixel_value = -1 + self.mean_counts_firstderi = -1 + self.std_deviation_counts_firstderi = -1 + self.peak_max_final_value = -1 + self.peak_min_final_value = -1 + + def calculate5HighestPoints(self): + _xdata = self.xdata + _ydata = self.ydata _sort_ydata = np.sort(_ydata) _decreasing_sort_ydata = _sort_ydata[::-1] - cls.five_highest_ydata = _decreasing_sort_ydata[0:5] + self.five_highest_ydata = _decreasing_sort_ydata[0:5] _sort_index = np.argsort(_ydata) _decreasing_sort_index = _sort_index[::-1] _5decreasing_sort_index = _decreasing_sort_index[0:5] - cls.five_highest_xdata = _xdata[_5decreasing_sort_index] + self.five_highest_xdata = _xdata[_5decreasing_sort_index] - def calculatePeakPixel(cls): - cls.sum_peak_counts = sum(cls.five_highest_ydata) + def calculatePeakPixel(self): + self.sum_peak_counts = sum(self.five_highest_ydata) _sum_peak_counts_time_pixel = -1 - for index, yvalue in enumerate(cls.five_highest_ydata): - _sum_peak_counts_time_pixel += yvalue * cls.five_highest_xdata[index] - cls.sum_peak_counts_time_pixel = _sum_peak_counts_time_pixel - cls.peak_pixel = round(cls.sum_peak_counts_time_pixel / cls.sum_peak_counts) + for index, yvalue in enumerate(self.five_highest_ydata): + _sum_peak_counts_time_pixel += yvalue * self.five_highest_xdata[index] + self.sum_peak_counts_time_pixel = _sum_peak_counts_time_pixel + self.peak_pixel = round(self.sum_peak_counts_time_pixel / self.sum_peak_counts) - def calculateFirstDerivative(cls): - xdata = cls.xdata - ydata = cls.ydata + def calculateFirstDerivative(self): + xdata = self.xdata + ydata = self.ydata _xdata_firstderi = [] _ydata_firstderi = [] @@ -91,35 +91,35 @@ def calculateFirstDerivative(cls): _right_y = ydata[i + 1] _ydata_firstderi.append((_right_y - _left_y) / (_right_x - _left_x)) - cls.xdata_firstderi = _xdata_firstderi - cls.ydata_firstderi = _ydata_firstderi + self.xdata_firstderi = _xdata_firstderi + self.ydata_firstderi = _ydata_firstderi - def calculateMinMaxDerivativePixels(cls): - _pixel = cls.xdata_firstderi - _counts_firstderi = cls.ydata_firstderi + def calculateMinMaxDerivativePixels(self): + _pixel = self.xdata_firstderi + _counts_firstderi = self.ydata_firstderi _sort_counts_firstderi = np.sort(_counts_firstderi) - cls.deri_min = _sort_counts_firstderi[0] - cls.deri_max = _sort_counts_firstderi[-1] + self.deri_min = _sort_counts_firstderi[0] + self.deri_max = _sort_counts_firstderi[-1] _sort_index = np.argsort(_counts_firstderi) - cls.deri_min_pixel_value = min([_pixel[_sort_index[0]], _pixel[_sort_index[-1]]]) - cls.deri_max_pixel_value = max([_pixel[_sort_index[0]], _pixel[_sort_index[-1]]]) + self.deri_min_pixel_value = min([_pixel[_sort_index[0]], _pixel[_sort_index[-1]]]) + self.deri_max_pixel_value = max([_pixel[_sort_index[0]], _pixel[_sort_index[-1]]]) - def calculateAvgAndStdDerivative(cls): - _counts_firstderi = np.array(cls.ydata_firstderi) - cls.mean_counts_firstderi = np.mean(_counts_firstderi) + def calculateAvgAndStdDerivative(self): + _counts_firstderi = np.array(self.ydata_firstderi) + self.mean_counts_firstderi = np.mean(_counts_firstderi) _mean_counts_firstderi = np.mean(_counts_firstderi * _counts_firstderi) - cls.std_deviation_counts_firstderi = math.sqrt(_mean_counts_firstderi) + self.std_deviation_counts_firstderi = math.sqrt(_mean_counts_firstderi) - def calculateMinMaxSignalPixel(cls): - _counts = cls.ydata_firstderi - _pixel = cls.xdata_firstderi + def calculateMinMaxSignalPixel(self): + _counts = self.ydata_firstderi + _pixel = self.xdata_firstderi - _deri_min_pixel_value = cls.deri_min_pixel_value - _deri_max_pixel_value = cls.deri_max_pixel_value + _deri_min_pixel_value = self.deri_min_pixel_value + _deri_max_pixel_value = self.deri_max_pixel_value - _std_deviation_counts_firstderi = cls.std_deviation_counts_firstderi + _std_deviation_counts_firstderi = self.std_deviation_counts_firstderi px_offset = 0 while abs(_counts[int(_deri_min_pixel_value - px_offset)]) > _std_deviation_counts_firstderi: @@ -131,45 +131,45 @@ def calculateMinMaxSignalPixel(cls): px_offset += 1 _peak_max_final_value = _pixel[int(round(_deri_max_pixel_value + px_offset))] - cls.peaks = [int(_peak_min_final_value), int(np.ceil(_peak_max_final_value))] + self.peaks = [int(_peak_min_final_value), int(np.ceil(_peak_max_final_value))] # getters - def getAverageOfFirstDerivationCounts(cls): - return cls.mean_counts_firstderi + def getAverageOfFirstDerivationCounts(self): + return self.mean_counts_firstderi - def getStdDeviationOfFirstDerivationCounts(cls): - return cls.std_deviation_counts_firstderi + def getStdDeviationOfFirstDerivationCounts(self): + return self.std_deviation_counts_firstderi - def getMinDerivativeValue(cls): - return cls.deri_min + def getMinDerivativeValue(self): + return self.deri_min - def getMaxDerivativeValue(cls): - return cls.deri_max + def getMaxDerivativeValue(self): + return self.deri_max - def getMinDerivationPixelValue(cls): - return cls.deri_min_pixel_value + def getMinDerivationPixelValue(self): + return self.deri_min_pixel_value - def getMaxDerivationPixelValue(cls): - return cls.deri_max_pixel_value + def getMaxDerivationPixelValue(self): + return self.deri_max_pixel_value - def getPeakPixel(cls): - return cls.peak_pixel + def getPeakPixel(self): + return self.peak_pixel - def getSumPeakCounts(cls): - return cls.sum_peak_counts + def getSumPeakCounts(self): + return self.sum_peak_counts - def getSumPeakCountsTimePixel(cls): - return cls.sum_peak_counts_time_pixel + def getSumPeakCountsTimePixel(self): + return self.sum_peak_counts_time_pixel - def get5HighestPoints(cls): - return [cls.five_highest_xdata, cls.five_highest_ydata] + def get5HighestPoints(self): + return [self.five_highest_xdata, self.five_highest_ydata] - def getFirstDerivative(cls): - return [cls.xdata_firstderi, cls.ydata_firstderi] + def getFirstDerivative(self): + return [self.xdata_firstderi, self.ydata_firstderi] - def getPeaks(cls): - return cls.peaks + def getPeaks(self): + return self.peaks if __name__ == "__main__": diff --git a/RefRed/reduction/calculate_sf_overlap_range.py b/RefRed/reduction/calculate_sf_overlap_range.py index 21c43a63..f262c3b5 100644 --- a/RefRed/reduction/calculate_sf_overlap_range.py +++ b/RefRed/reduction/calculate_sf_overlap_range.py @@ -30,8 +30,8 @@ def getSF(self): _sf = 1 else: - [a_left, b_left] = self.fitData(left_set, index_min_in_left, type="left") - [a_right, b_right] = self.fitData(right_set, index_max_in_right, type="right") + [a_left, b_left] = self.fitData(left_set, index_min_in_left, data_type="left") + [a_right, b_right] = self.fitData(right_set, index_max_in_right, data_type="right") nbr_points = 10 fit_range_to_use = self.gitFittingOverlapRange(min_x, max_x, nbr_points) @@ -83,11 +83,11 @@ def calculateOverlapAxis(self, left_axis, right_axis): return [_min_x, _max_x, left_min_index, right_max_index, no_overlap] - def fitData(self, data_set, threshold_index, type="right"): + def fitData(self, data_set, threshold_index, data_type="right"): """ will fit the data with linear fitting y=ax + b """ - if type == "left": + if data_type == "left": x_axis = data_set.reduce_q_axis[threshold_index:] y_axis = data_set.tmp_y_axis[threshold_index:] e_axis = data_set.tmp_e_axis[threshold_index:] diff --git a/docs/conf.py b/docs/conf.py index ee7f36b8..32274db7 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -64,7 +64,7 @@ # General information about the project. project = "RefRed" -copyright = "2017, Jose Borreguero" +copyright = "2017, Jose Borreguero" # noqa: A001 # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout diff --git a/pyproject.toml b/pyproject.toml index c52b2c18..039cae47 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,12 +20,17 @@ select = ["A", "ARG", "ASYNC", "BLE", "C90", "E", "F", "I", "N", "UP032", "W"] ignore = [ "ARG001", # Unused function argument "ARG002", # Unused method argument + "ARG003", # Unused class method argument + "C901", # function is too complex "E402", # module level import not at top of file "E722", # do not use bare 'except' "F821", # undefined name "N802", # function name should be lowercase "N803", # argument name should be lowercase "N806", # variable in function should be lowercase + "N815", # mixed case class variable name + "N816", # mixed case global variable name + "N999", # invalid module name ] [tool.mypy] From 3a9354212b0ea47f916105cec4bef2692b6d0322 Mon Sep 17 00:00:00 2001 From: glass-ships Date: Mon, 17 Feb 2025 09:47:38 -0500 Subject: [PATCH 6/6] remove import comments, re-sort --- .../populate_reduction_table_from_list_lrdata.py | 4 ---- .../calculations/check_list_run_compatibility_and_display.py | 5 ----- RefRed/calculations/lr_data.py | 4 ---- RefRed/configuration/export_xml_config.py | 3 --- RefRed/configuration/global_settings.py | 1 - RefRed/configuration/loading_configuration.py | 3 --- RefRed/export/export_plot_ascii.py | 4 ---- RefRed/gui_handling/data_norm_spinboxes.py | 3 --- RefRed/gui_handling/fill_stitching_table.py | 3 --- RefRed/gui_handling/gui_utility.py | 3 --- RefRed/gui_handling/observer.py | 4 ---- RefRed/gui_handling/update_plot_widget_status.py | 1 - RefRed/interfaces/__init__.py | 2 -- RefRed/interfaces/mytablewidget.py | 5 ----- RefRed/lconfigdataset.py | 1 - RefRed/plot/background_settings.py | 3 --- RefRed/plot/display_plots.py | 4 ---- RefRed/plot/popup_plot_1d.py | 4 ---- RefRed/plot/popup_plot_2d.py | 3 --- RefRed/reduction/individual_reduction_settings_handler.py | 2 -- RefRed/reduction_table_handling/const_q_checkbox_handler.py | 4 ---- RefRed/reduction_table_handling/reduction_table_check_box.py | 4 ---- RefRed/reduction_table_handling/reduction_table_handler.py | 4 ---- RefRed/reduction_table_handling/update_reduction_table.py | 4 ---- RefRed/sf_calculator/reduction_sf_calculator.py | 3 --- RefRed/tabledata.py | 3 --- scripts/sync_dependencies.py | 1 - test/conftest.py | 3 --- test/ui/test_compute_scaling_factors.py | 4 ---- test/ui/test_plot2d_dialog.py | 3 --- test/ui/test_popup_plot_1d.py | 4 ---- test/ui/test_reduce_and_export_data.py | 4 ---- test/ui/test_scaling_factors_preview.py | 5 ----- test/unit/RefRed/calculations/test_load_nexus.py | 2 -- test/unit/RefRed/configuration/test_export_xml_config.py | 3 --- test/unit/RefRed/configuration/test_loading_configuration.py | 2 -- test/unit/RefRed/export/test_ascii_loader.py | 3 --- test/unit/RefRed/export/test_export_plot_ascii.py | 3 --- test/unit/RefRed/export/test_reduced_ascii_loader.py | 3 --- test/unit/RefRed/interfaces/test_deadtime_settings.py | 3 --- test/unit/RefRed/interfaces/test_mytablewidget.py | 3 --- .../RefRed/low_res_finder_algorithms/test_low_res_finder.py | 3 --- .../peak_finder_algorithms/test_peak_finder_derivation.py | 2 -- .../reduction/test_individual_reduction_settings_handler.py | 2 -- .../RefRed/sf_calculator/test_reduction_sf_calculator.py | 3 --- test/unit/RefRed/sf_calculator/test_sf_calculator.py | 2 -- test/unit/RefRed/test_file_loading_utility.py | 2 -- test/unit/RefRed/test_tabledata.py | 3 --- 48 files changed, 147 deletions(-) diff --git a/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py b/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py index e022abd2..b8d368b8 100644 --- a/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py +++ b/RefRed/autopopulatemaintable/populate_reduction_table_from_list_lrdata.py @@ -1,9 +1,5 @@ -# standard imports - -# third party imports import numpy as np -# application imports from RefRed.interfaces.mytablewidget import ReductionTableColumnIndex from RefRed.reduction_table_handling.reduction_table_handler import ReductionTableHandler from RefRed.tabledata import TableData diff --git a/RefRed/calculations/check_list_run_compatibility_and_display.py b/RefRed/calculations/check_list_run_compatibility_and_display.py index ee123484..7c096f3a 100644 --- a/RefRed/calculations/check_list_run_compatibility_and_display.py +++ b/RefRed/calculations/check_list_run_compatibility_and_display.py @@ -1,11 +1,6 @@ -# standard imports - -# third party imports from qtpy import QtGui import RefRed.colors - -# application imports from RefRed.calculations.add_list_nexus import AddListNexus from RefRed.calculations.lr_data import LRData from RefRed.calculations.update_reduction_table_metadata import UpdateReductionTableMetadata diff --git a/RefRed/calculations/lr_data.py b/RefRed/calculations/lr_data.py index d105a832..0ada0958 100644 --- a/RefRed/calculations/lr_data.py +++ b/RefRed/calculations/lr_data.py @@ -1,15 +1,11 @@ -# standard imports import logging import math from typing import List, Optional, Type import numpy as np - -# third-party imports from mantid.api import mtd from mantid.simpleapi import Rebin -# package imports from RefRed.lconfigdataset import LConfigDataset from RefRed.low_res_finder_algorithms.low_res_finder import LowResFinder from RefRed.peak_finder_algorithms.peak_finder_derivation import PeakFinderDerivation diff --git a/RefRed/configuration/export_xml_config.py b/RefRed/configuration/export_xml_config.py index b1851ef2..051e579d 100644 --- a/RefRed/configuration/export_xml_config.py +++ b/RefRed/configuration/export_xml_config.py @@ -1,14 +1,11 @@ -# standard imports import datetime import logging import os from typing import Optional -# third-party imports import lr_reduction import mantid -# package imports import RefRed from RefRed.calculations.lr_data import LRData from RefRed.reduction.global_reduction_settings_handler import ( diff --git a/RefRed/configuration/global_settings.py b/RefRed/configuration/global_settings.py index 54737d3f..33bcd577 100644 --- a/RefRed/configuration/global_settings.py +++ b/RefRed/configuration/global_settings.py @@ -1,4 +1,3 @@ -# third party imports from pydantic import BaseModel diff --git a/RefRed/configuration/loading_configuration.py b/RefRed/configuration/loading_configuration.py index c38572e7..42ee263f 100644 --- a/RefRed/configuration/loading_configuration.py +++ b/RefRed/configuration/loading_configuration.py @@ -1,14 +1,11 @@ -# standard imports import logging import os from typing import Any from xml.dom import minidom -# third party imports from qtpy import QtWidgets from qtpy.QtWidgets import QFileDialog -# application imports from RefRed.configuration.load_reduction_table_from_lconfigdataset import ( LoadReductionTableFromLConfigDataSet as LoadReductionTable, ) diff --git a/RefRed/export/export_plot_ascii.py b/RefRed/export/export_plot_ascii.py index a221a1e2..7e08085e 100644 --- a/RefRed/export/export_plot_ascii.py +++ b/RefRed/export/export_plot_ascii.py @@ -1,14 +1,10 @@ -# standard imports import os from pathlib import Path from typing import List, Tuple from lr_reduction import output as lr_output - -# third-party imorts from qtpy.QtWidgets import QFileDialog -# RefRed imports import RefRed.utilities from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.reduction.reduced_data_handler import ReducedDataHandler diff --git a/RefRed/gui_handling/data_norm_spinboxes.py b/RefRed/gui_handling/data_norm_spinboxes.py index 1d221ecd..b2e6611a 100644 --- a/RefRed/gui_handling/data_norm_spinboxes.py +++ b/RefRed/gui_handling/data_norm_spinboxes.py @@ -1,10 +1,7 @@ -# standard imports from typing import List -# third party imports from qtpy.QtWidgets import QWidget -# application imports from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.plot.display_plots import DisplayPlots from RefRed.tabledata import TableData diff --git a/RefRed/gui_handling/fill_stitching_table.py b/RefRed/gui_handling/fill_stitching_table.py index 2c565840..75f0673f 100644 --- a/RefRed/gui_handling/fill_stitching_table.py +++ b/RefRed/gui_handling/fill_stitching_table.py @@ -1,11 +1,8 @@ -# standard imports from distutils.util import strtobool from typing import Optional -# third party imports from qtpy import QtCore, QtGui, QtWidgets -# application imports from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.tabledata import TableData diff --git a/RefRed/gui_handling/gui_utility.py b/RefRed/gui_handling/gui_utility.py index 7ccc0ac8..4898eead 100644 --- a/RefRed/gui_handling/gui_utility.py +++ b/RefRed/gui_handling/gui_utility.py @@ -1,11 +1,8 @@ -# standard imports from typing import TYPE_CHECKING, List -# third party imports from qtpy import QtWidgets from qtpy.QtCore import Qt # type: ignore -# application imports from RefRed import WINDOW_TITLE from RefRed.interfaces.mytablewidget import ReductionTableColumnIndex from RefRed.tabledata import TableData diff --git a/RefRed/gui_handling/observer.py b/RefRed/gui_handling/observer.py index e9106b81..bab464f1 100644 --- a/RefRed/gui_handling/observer.py +++ b/RefRed/gui_handling/observer.py @@ -1,11 +1,7 @@ -# standard imports from dataclasses import dataclass -# third-party imports from qtpy.QtWidgets import QSpinBox -# package imports - class SpinBoxObserver: r"""Stores the last value for each of the registered QSpinBox objects. diff --git a/RefRed/gui_handling/update_plot_widget_status.py b/RefRed/gui_handling/update_plot_widget_status.py index db85e354..63ed4d08 100644 --- a/RefRed/gui_handling/update_plot_widget_status.py +++ b/RefRed/gui_handling/update_plot_widget_status.py @@ -1,4 +1,3 @@ -# RefRed imports from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.plot.background_settings import backgrounds_settings diff --git a/RefRed/interfaces/__init__.py b/RefRed/interfaces/__init__.py index 4647b451..4a58a8f7 100644 --- a/RefRed/interfaces/__init__.py +++ b/RefRed/interfaces/__init__.py @@ -1,7 +1,5 @@ -# standard imports import os -# third party imports from qtpy.QtWidgets import QWidget from qtpy.uic import loadUi diff --git a/RefRed/interfaces/mytablewidget.py b/RefRed/interfaces/mytablewidget.py index e0aca26c..ec3c6831 100644 --- a/RefRed/interfaces/mytablewidget.py +++ b/RefRed/interfaces/mytablewidget.py @@ -1,13 +1,8 @@ -# standard imports from enum import IntEnum -# third party imports from qtpy import QtWidgets from qtpy.QtCore import Qt # type: ignore -# application imports -# - class MyTableWidget(QtWidgets.QTableWidget): parent = None diff --git a/RefRed/lconfigdataset.py b/RefRed/lconfigdataset.py index 50b926e3..9660129e 100644 --- a/RefRed/lconfigdataset.py +++ b/RefRed/lconfigdataset.py @@ -1,4 +1,3 @@ -# standard imports from typing import List diff --git a/RefRed/plot/background_settings.py b/RefRed/plot/background_settings.py index 92ebcbb4..37a8a39a 100644 --- a/RefRed/plot/background_settings.py +++ b/RefRed/plot/background_settings.py @@ -1,11 +1,8 @@ -# standard imports from typing import List, Optional, Tuple -# third-party imports from qtpy.QtCore import QObject, Qt, Signal # type: ignore from qtpy.QtWidgets import QCheckBox, QDialog, QWidget -# application imports from RefRed.calculations.lr_data import LRData from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.interfaces import load_ui diff --git a/RefRed/plot/display_plots.py b/RefRed/plot/display_plots.py index 8210fa9f..e1839f5e 100644 --- a/RefRed/plot/display_plots.py +++ b/RefRed/plot/display_plots.py @@ -1,10 +1,6 @@ -# standard imports import bisect import RefRed.colors as colors - -# third party imports -# application imports from RefRed.calculations.lr_data import LRData from RefRed.gui_handling.update_plot_widget_status import UpdatePlotWidgetStatus from RefRed.plot.background_settings import backgrounds_settings diff --git a/RefRed/plot/popup_plot_1d.py b/RefRed/plot/popup_plot_1d.py index 64d17390..65e795cb 100644 --- a/RefRed/plot/popup_plot_1d.py +++ b/RefRed/plot/popup_plot_1d.py @@ -1,16 +1,12 @@ -# standard imports import bisect import os from pathlib import Path from typing import Optional -# third-party imports from qtpy.QtWidgets import QDialog, QFileDialog import RefRed.colors import RefRed.utilities - -# package imports from RefRed.calculations.lr_data import LRData from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.gui_handling.observer import SpinBoxObserver diff --git a/RefRed/plot/popup_plot_2d.py b/RefRed/plot/popup_plot_2d.py index e70765ba..0f9148ed 100644 --- a/RefRed/plot/popup_plot_2d.py +++ b/RefRed/plot/popup_plot_2d.py @@ -1,11 +1,8 @@ -# standard imports import os from pathlib import Path -# third-party imports from qtpy.QtWidgets import QDialog, QFileDialog -# package imports import RefRed.colors import RefRed.utilities from RefRed.gui_handling.auto_tof_range_radio_button_handler import AutoTofRangeRadioButtonHandler diff --git a/RefRed/reduction/individual_reduction_settings_handler.py b/RefRed/reduction/individual_reduction_settings_handler.py index 6153e22d..1146e75e 100644 --- a/RefRed/reduction/individual_reduction_settings_handler.py +++ b/RefRed/reduction/individual_reduction_settings_handler.py @@ -7,10 +7,8 @@ keep this information. """ -# standard imports from typing import Any, List, Optional -# package imports from RefRed.calculations.lr_data import LRData from RefRed.tabledata import TableData diff --git a/RefRed/reduction_table_handling/const_q_checkbox_handler.py b/RefRed/reduction_table_handling/const_q_checkbox_handler.py index 5fd26285..30391203 100644 --- a/RefRed/reduction_table_handling/const_q_checkbox_handler.py +++ b/RefRed/reduction_table_handling/const_q_checkbox_handler.py @@ -1,9 +1,5 @@ -# standard imports - -# third-party imports from qtpy.QtCore import Qt # type: ignore -# package imports from RefRed.tabledata import TableData diff --git a/RefRed/reduction_table_handling/reduction_table_check_box.py b/RefRed/reduction_table_handling/reduction_table_check_box.py index 11603c78..653b225c 100644 --- a/RefRed/reduction_table_handling/reduction_table_check_box.py +++ b/RefRed/reduction_table_handling/reduction_table_check_box.py @@ -1,10 +1,6 @@ -# standard imports - -# third-party imports import numpy as np from qtpy.QtCore import Qt # type: ignore -# package imports from RefRed.gui_handling.auto_tof_range_radio_button_handler import AutoTofRangeRadioButtonHandler from RefRed.gui_handling.update_plot_widget_status import UpdatePlotWidgetStatus from RefRed.plot.background_settings import backgrounds_settings diff --git a/RefRed/reduction_table_handling/reduction_table_handler.py b/RefRed/reduction_table_handling/reduction_table_handler.py index d5a84b9e..21f6b0d0 100644 --- a/RefRed/reduction_table_handling/reduction_table_handler.py +++ b/RefRed/reduction_table_handling/reduction_table_handler.py @@ -1,9 +1,5 @@ -# standard imports - -# third party imports from qtpy import QtCore, QtGui, QtWidgets -# application imports from RefRed import WINDOW_TITLE from RefRed.gui_handling.gui_utility import GuiUtility from RefRed.interfaces.mytablewidget import ReductionTableColumnIndex diff --git a/RefRed/reduction_table_handling/update_reduction_table.py b/RefRed/reduction_table_handling/update_reduction_table.py index c8bf12db..b216b3f7 100644 --- a/RefRed/reduction_table_handling/update_reduction_table.py +++ b/RefRed/reduction_table_handling/update_reduction_table.py @@ -1,10 +1,6 @@ -# standard imports - -# third party imports from qtpy import QtGui from qtpy.QtWidgets import QApplication -# application imports import RefRed.colors from RefRed.calculations.check_list_run_compatibility_thread import CheckListRunCompatibilityThread from RefRed.calculations.locate_list_run import LocateListRun diff --git a/RefRed/sf_calculator/reduction_sf_calculator.py b/RefRed/sf_calculator/reduction_sf_calculator.py index 25600703..141396c5 100644 --- a/RefRed/sf_calculator/reduction_sf_calculator.py +++ b/RefRed/sf_calculator/reduction_sf_calculator.py @@ -1,14 +1,11 @@ -# standard-library imports import logging import sys import time from typing import Optional, Union -# third-party imports import numpy as np from qtpy.QtWidgets import QApplication, QFileDialog, QMessageBox -# RefRed imports from RefRed.utilities import convertTOF diff --git a/RefRed/tabledata.py b/RefRed/tabledata.py index 2e6a7d12..a18faa3f 100644 --- a/RefRed/tabledata.py +++ b/RefRed/tabledata.py @@ -1,11 +1,8 @@ -# standard imports from enum import Enum from typing import Optional, Union -# third party imports import numpy as np -# application imports from RefRed.calculations.lr_data import LRData from RefRed.lconfigdataset import LConfigDataset diff --git a/scripts/sync_dependencies.py b/scripts/sync_dependencies.py index bb3f636e..70122b95 100644 --- a/scripts/sync_dependencies.py +++ b/scripts/sync_dependencies.py @@ -1,4 +1,3 @@ -# standard imports import logging import os import re diff --git a/test/conftest.py b/test/conftest.py index 98b065ec..e253104e 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -1,10 +1,7 @@ -# standard imports import os import sys import pytest - -# 3rd-party imports from mantid.simpleapi import config from qtpy import QtCore, QtWidgets diff --git a/test/ui/test_compute_scaling_factors.py b/test/ui/test_compute_scaling_factors.py index 599d7eb5..2dc56c3e 100644 --- a/test/ui/test_compute_scaling_factors.py +++ b/test/ui/test_compute_scaling_factors.py @@ -1,15 +1,11 @@ -# standard imports import os import random import string from unittest.mock import patch as mock_patch import pytest - -# third party imports from qtpy import QtCore -# RefRed imports from RefRed.main import MainGui SECOND = 1000 # 1000 miliseconds diff --git a/test/ui/test_plot2d_dialog.py b/test/ui/test_plot2d_dialog.py index e1c42e8a..8faf1cbc 100644 --- a/test/ui/test_plot2d_dialog.py +++ b/test/ui/test_plot2d_dialog.py @@ -1,11 +1,8 @@ -# standard imports from unittest.mock import patch as mock_patch -# third-party imports import pytest from qtpy import QtCore, QtWidgets -# RefRed imports from RefRed.main import MainGui from RefRed.plot.popup_plot_2d import PopupPlot2d diff --git a/test/ui/test_popup_plot_1d.py b/test/ui/test_popup_plot_1d.py index 7bf54cf6..f33a0770 100644 --- a/test/ui/test_popup_plot_1d.py +++ b/test/ui/test_popup_plot_1d.py @@ -1,13 +1,9 @@ -# standard imports from unittest.mock import patch as mock_patch -# third-party imports import pytest from qtpy import QtCore from RefRed.main import MainGui - -# RefRed imports from RefRed.plot.popup_plot_1d import PopupPlot1d diff --git a/test/ui/test_reduce_and_export_data.py b/test/ui/test_reduce_and_export_data.py index 20c16ed0..77a17302 100644 --- a/test/ui/test_reduce_and_export_data.py +++ b/test/ui/test_reduce_and_export_data.py @@ -1,16 +1,12 @@ -# standard imports import os from pathlib import Path from unittest import mock -# third-party imports import numpy as np import pytest from qtpy import QtCore from RefRed.configuration.loading_configuration import LoadingConfiguration - -# RefRed imports from RefRed.main import MainGui wait = 200 diff --git a/test/ui/test_scaling_factors_preview.py b/test/ui/test_scaling_factors_preview.py index 71a30427..6d4a9d99 100644 --- a/test/ui/test_scaling_factors_preview.py +++ b/test/ui/test_scaling_factors_preview.py @@ -1,15 +1,10 @@ -# standard imports import os from unittest.mock import patch as mock_patch import pytest - -# third-party imports from qtpy import QtCore from RefRed.main import MainGui - -# RefRed imports from RefRed.sf_preview.sf_preview import SFPreview SECOND = 1000 # 1000 miliseconds diff --git a/test/unit/RefRed/calculations/test_load_nexus.py b/test/unit/RefRed/calculations/test_load_nexus.py index 40ee7325..eb0cbf4b 100644 --- a/test/unit/RefRed/calculations/test_load_nexus.py +++ b/test/unit/RefRed/calculations/test_load_nexus.py @@ -1,5 +1,3 @@ -# package imports -# third party imports import pytest from mantid.simpleapi import mtd diff --git a/test/unit/RefRed/configuration/test_export_xml_config.py b/test/unit/RefRed/configuration/test_export_xml_config.py index 27e8c2c4..55648687 100644 --- a/test/unit/RefRed/configuration/test_export_xml_config.py +++ b/test/unit/RefRed/configuration/test_export_xml_config.py @@ -1,11 +1,8 @@ -# standard imports from datetime import datetime from unittest.mock import MagicMock, patch -# third party imports import pytest -# RefRed imports from RefRed.configuration.export_xml_config import ExportXMLConfig diff --git a/test/unit/RefRed/configuration/test_loading_configuration.py b/test/unit/RefRed/configuration/test_loading_configuration.py index 90135124..2ad06576 100644 --- a/test/unit/RefRed/configuration/test_loading_configuration.py +++ b/test/unit/RefRed/configuration/test_loading_configuration.py @@ -1,9 +1,7 @@ -# third party packages import unittest.mock as mock import pytest -# RefRed imports from RefRed.configuration.loading_configuration import LoadingConfiguration from RefRed.tabledata import TableData diff --git a/test/unit/RefRed/export/test_ascii_loader.py b/test/unit/RefRed/export/test_ascii_loader.py index 90651307..df453a99 100644 --- a/test/unit/RefRed/export/test_ascii_loader.py +++ b/test/unit/RefRed/export/test_ascii_loader.py @@ -1,10 +1,7 @@ -# package imports import tempfile from pathlib import Path import numpy as np - -# 3rd party imports import pytest from RefRed.export import ascii_loader diff --git a/test/unit/RefRed/export/test_export_plot_ascii.py b/test/unit/RefRed/export/test_export_plot_ascii.py index 5ed6ba89..daf32475 100644 --- a/test/unit/RefRed/export/test_export_plot_ascii.py +++ b/test/unit/RefRed/export/test_export_plot_ascii.py @@ -1,11 +1,8 @@ -# package imports import tempfile import unittest.mock as mock from pathlib import Path import numpy as np - -# 3rd party imports import pytest import RefRed diff --git a/test/unit/RefRed/export/test_reduced_ascii_loader.py b/test/unit/RefRed/export/test_reduced_ascii_loader.py index 61361319..e5201d37 100644 --- a/test/unit/RefRed/export/test_reduced_ascii_loader.py +++ b/test/unit/RefRed/export/test_reduced_ascii_loader.py @@ -1,11 +1,8 @@ -# package imports import tempfile import unittest.mock as mock from pathlib import Path import numpy as np - -# 3rd party imports import pytest from RefRed.export.reduced_ascii_loader import ReducedAsciiLoader diff --git a/test/unit/RefRed/interfaces/test_deadtime_settings.py b/test/unit/RefRed/interfaces/test_deadtime_settings.py index 95bedf5f..61358df1 100644 --- a/test/unit/RefRed/interfaces/test_deadtime_settings.py +++ b/test/unit/RefRed/interfaces/test_deadtime_settings.py @@ -1,10 +1,7 @@ -# standard imports from xml.dom.minidom import parseString -# third party imports import pytest -# RefRed imports from RefRed.interfaces.deadtime_settings import DeadTimeSettingsModel diff --git a/test/unit/RefRed/interfaces/test_mytablewidget.py b/test/unit/RefRed/interfaces/test_mytablewidget.py index 6783fe38..bd51d0a4 100644 --- a/test/unit/RefRed/interfaces/test_mytablewidget.py +++ b/test/unit/RefRed/interfaces/test_mytablewidget.py @@ -1,9 +1,6 @@ -# package imports import unittest.mock as mock import pytest - -# third party packages from qtpy.QtCore import Qt # type: ignore from RefRed.interfaces.mytablewidget import MyTableWidget diff --git a/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py b/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py index aed478ba..5914e019 100644 --- a/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py +++ b/test/unit/RefRed/low_res_finder_algorithms/test_low_res_finder.py @@ -1,7 +1,4 @@ -# package imports import numpy as np - -# 3rd party imports import pytest from RefRed.file_loading_utility import loadCsvFile diff --git a/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py b/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py index 9c75f9b1..3e61425d 100644 --- a/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py +++ b/test/unit/RefRed/peak_finder_algorithms/test_peak_finder_derivation.py @@ -1,5 +1,3 @@ -# package imports -# third party packages import pytest from RefRed.file_loading_utility import loadCsvFile diff --git a/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py b/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py index bf904075..22a864cd 100644 --- a/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py +++ b/test/unit/RefRed/reduction/test_individual_reduction_settings_handler.py @@ -1,9 +1,7 @@ -# third party packages. from unittest.mock import Mock import pytest -# RefRed imports from RefRed.reduction.individual_reduction_settings_handler import IndividualReductionSettingsHandler diff --git a/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py b/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py index 43336cdd..67005f3b 100644 --- a/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py +++ b/test/unit/RefRed/sf_calculator/test_reduction_sf_calculator.py @@ -1,7 +1,5 @@ -# standard imports from unittest import mock -# third-party imports import lr_reduction.scaling_factors.LRScalingFactors import numpy as np import pytest @@ -9,7 +7,6 @@ import qtpy.QtWidgets from qtpy.QtWidgets import QTableWidgetItem -# RefRed imports from RefRed.main import MainGui from RefRed.sf_calculator.reduction_sf_calculator import ReductionSfCalculator diff --git a/test/unit/RefRed/sf_calculator/test_sf_calculator.py b/test/unit/RefRed/sf_calculator/test_sf_calculator.py index c5003241..4a9cb5ed 100644 --- a/test/unit/RefRed/sf_calculator/test_sf_calculator.py +++ b/test/unit/RefRed/sf_calculator/test_sf_calculator.py @@ -1,8 +1,6 @@ -# third party imports import pytest from qtpy import QtCore, QtWidgets # type: ignore -# RefRed imports from RefRed.sf_calculator.sf_calculator import SFCalculator diff --git a/test/unit/RefRed/test_file_loading_utility.py b/test/unit/RefRed/test_file_loading_utility.py index 62c1aa97..08cb4980 100644 --- a/test/unit/RefRed/test_file_loading_utility.py +++ b/test/unit/RefRed/test_file_loading_utility.py @@ -1,5 +1,3 @@ -# package imports -# third party packages import pytest from RefRed.file_loading_utility import loadCsvFile diff --git a/test/unit/RefRed/test_tabledata.py b/test/unit/RefRed/test_tabledata.py index 6ba16151..6bb2e9b7 100644 --- a/test/unit/RefRed/test_tabledata.py +++ b/test/unit/RefRed/test_tabledata.py @@ -1,10 +1,7 @@ -# standard imports from unittest.mock import patch -# third party imports import pytest -# application imports from RefRed.calculations.lr_data import LRData from RefRed.lconfigdataset import LConfigDataset from RefRed.tabledata import TableData, TableDataColumIndex