From 7b0b9b93810c5910997a8e07dca156c299f3cdbf Mon Sep 17 00:00:00 2001 From: Sam Tygier Date: Fri, 15 Mar 2024 11:11:59 +0000 Subject: [PATCH 1/6] Fix string formatting (UP030, UP031, UP032) issues --- mantidimaging/core/io/loader/loader.py | 4 ++-- mantidimaging/core/io/saver.py | 8 ++++---- mantidimaging/core/io/test/io_test.py | 7 +------ mantidimaging/core/operations/crop_coords/crop_coords.py | 2 +- mantidimaging/core/reconstruct/astra_recon.py | 2 +- mantidimaging/core/reconstruct/cil_recon.py | 2 +- mantidimaging/core/reconstruct/tomopy_recon.py | 2 +- mantidimaging/core/rotation/data_model.py | 4 ++-- mantidimaging/core/utility/memory_usage.py | 9 ++++----- mantidimaging/core/utility/optional_imports.py | 4 ++-- .../utility/progress_reporting/console_progress_bar.py | 2 +- mantidimaging/gui/dialogs/cor_inspection/presenter.py | 6 +++--- .../gui/dialogs/cor_inspection/test/presenter_test.py | 6 +++--- mantidimaging/gui/utility/qt_helpers.py | 4 ++-- mantidimaging/gui/windows/operations/presenter.py | 2 +- mantidimaging/gui/windows/recon/presenter.py | 8 ++++---- .../gui/windows/spectrum_viewer/spectrum_widget.py | 3 +-- mantidimaging/gui/windows/stack_visualiser/presenter.py | 2 +- mantidimaging/gui/windows/stack_visualiser/view.py | 2 +- setup.py | 2 +- 20 files changed, 37 insertions(+), 44 deletions(-) diff --git a/mantidimaging/core/io/loader/loader.py b/mantidimaging/core/io/loader/loader.py index baeea02fcf0..9e7e71c3c69 100644 --- a/mantidimaging/core/io/loader/loader.py +++ b/mantidimaging/core/io/loader/loader.py @@ -63,7 +63,7 @@ def _fitsread(filename: Path | str) -> np.ndarray: """ image = fits.open(filename) if len(image) < 1: - raise RuntimeError("Could not load at least one FITS image/table file from: {0}".format(filename)) + raise RuntimeError(f"Could not load at least one FITS image/table file from: {filename}") # get the image data return image[0].data @@ -158,7 +158,7 @@ def load(filename_group: FilenameGroup, if metadata_filename: with open(metadata_filename) as f: image_stack.load_metadata(f) - LOG.debug('Loaded metadata from: {}'.format(metadata_filename)) + LOG.debug(f'Loaded metadata from: {metadata_filename}') else: LOG.debug('No metadata file found') diff --git a/mantidimaging/core/io/saver.py b/mantidimaging/core/io/saver.py index fcb0b48c959..e4c1ca6a753 100644 --- a/mantidimaging/core/io/saver.py +++ b/mantidimaging/core/io/saver.py @@ -132,7 +132,7 @@ def image_save(images: ImageStack, # Save metadata metadata_filename = os.path.join(output_dir, name_prefix + '.json') - LOG.debug('Metadata filename: {}'.format(metadata_filename)) + LOG.debug(f'Metadata filename: {metadata_filename}') with open(metadata_filename, 'w+') as f: images.save_metadata(f, rescale_params) @@ -429,8 +429,8 @@ def make_dirs_if_needed(dirname: str | None = None, overwrite_all: bool = False) if not os.path.exists(path): os.makedirs(path) elif os.listdir(path) and not overwrite_all: - raise RuntimeError("The output directory is NOT empty:{0}\nThis can be " - "overridden by specifying 'Overwrite on name conflict'.".format(path)) + raise RuntimeError(f"The output directory is NOT empty:{path}\nThis can be " + "overridden by specifying 'Overwrite on name conflict'.") def create_rits_format(tof: np.ndarray, transmission: np.ndarray, transmission_error: np.ndarray) -> str: @@ -458,4 +458,4 @@ def export_to_dat_rits_format(rits_formatted_data: str, path: Path) -> None: """ with path.open('w') as f: f.write(rits_formatted_data) - LOG.info('RITS formatted data saved to: {}'.format(path)) + LOG.info(f'RITS formatted data saved to: {path}') diff --git a/mantidimaging/core/io/test/io_test.py b/mantidimaging/core/io/test/io_test.py index 00661b05d08..66a2a44c27d 100644 --- a/mantidimaging/core/io/test/io_test.py +++ b/mantidimaging/core/io/test/io_test.py @@ -153,12 +153,7 @@ def do_preproc(self, img_format, loader_indices=None, expected_len=None, saver_i loaded_images = loader.load(group, indices=loader_indices) if loader_indices: - assert len(loaded_images.data) == expected_len, \ - "The length of the loaded data does not " \ - "match the expected length! Expected: {0}, " \ - "Got {1}".format(expected_len, len( - loaded_images.data)) - + self.assertEqual(expected_len, len(loaded_images.data)) expected_images.data = expected_images.data[loader_indices[0]:loader_indices[1]] npt.assert_equal(loaded_images.data, expected_images.data) diff --git a/mantidimaging/core/operations/crop_coords/crop_coords.py b/mantidimaging/core/operations/crop_coords/crop_coords.py index 3c50d3af607..c570260fa33 100644 --- a/mantidimaging/core/operations/crop_coords/crop_coords.py +++ b/mantidimaging/core/operations/crop_coords/crop_coords.py @@ -110,7 +110,7 @@ def execute_single(data, roi, progress=None, out=None): region in roi), \ "The region of interest coordinates are not integers!" - progress.update(msg="Cropping with coordinates: {0}".format(roi)) + progress.update(msg=f"Cropping with coordinates: {roi}") output = out[:] if out is not None else data[:] output[:] = data[:, roi.top:roi.bottom, roi.left:roi.right] diff --git a/mantidimaging/core/reconstruct/astra_recon.py b/mantidimaging/core/reconstruct/astra_recon.py index 0ca983c7663..f25be91106f 100644 --- a/mantidimaging/core/reconstruct/astra_recon.py +++ b/mantidimaging/core/reconstruct/astra_recon.py @@ -49,7 +49,7 @@ def _managed_recon(sino: np.ndarray, cfg, proj_geom, vol_geom) -> Generator[tupl alg_id = None try: proj_type = 'cuda' if CudaChecker().cuda_is_present() else 'line' - LOG.debug("Using projection type {}".format(proj_type)) + LOG.debug(f"Using projection type {proj_type}") proj_id = astra.create_projector(proj_type, proj_geom, vol_geom) sino_id = astra.data2d.create('-sino', proj_geom, sino) diff --git a/mantidimaging/core/reconstruct/cil_recon.py b/mantidimaging/core/reconstruct/cil_recon.py index 1826a5fb350..1ebf8c9886e 100644 --- a/mantidimaging/core/reconstruct/cil_recon.py +++ b/mantidimaging/core/reconstruct/cil_recon.py @@ -326,7 +326,7 @@ def full(images: ImageStack, algo.next() volume = algo.solution.as_array() - LOG.info('Reconstructed 3D volume with shape: {0}'.format(volume.shape)) + LOG.info(f'Reconstructed 3D volume with shape: {volume.shape}') t1 = time.perf_counter() LOG.info(f"full reconstruction time: {t1-t0}s for shape {images.data.shape}") return ImageStack(volume) diff --git a/mantidimaging/core/reconstruct/tomopy_recon.py b/mantidimaging/core/reconstruct/tomopy_recon.py index ed2e7f5b787..cfef8ff80dd 100644 --- a/mantidimaging/core/reconstruct/tomopy_recon.py +++ b/mantidimaging/core/reconstruct/tomopy_recon.py @@ -79,7 +79,7 @@ def full(images: ImageStack, with progress: volume = tomopy.recon(**kwargs) - LOG.info('Reconstructed 3D volume with shape: {0}'.format(volume.shape)) + LOG.info(f'Reconstructed 3D volume with shape: {volume.shape}') return ImageStack(volume) diff --git a/mantidimaging/core/rotation/data_model.py b/mantidimaging/core/rotation/data_model.py index 56ec0a1152f..e5745c3d095 100644 --- a/mantidimaging/core/rotation/data_model.py +++ b/mantidimaging/core/rotation/data_model.py @@ -33,10 +33,10 @@ def populate_slice_indices(self, begin, end, count, cor=0.0): self.clear_results() self._points = [Point(int(idx), cor) for idx in np.linspace(begin, end, count, dtype=int)] - LOG.debug('Populated slice indices: {}'.format(self.slices)) + LOG.debug(f'Populated slice indices: {self.slices}') def linear_regression(self): - LOG.debug('Running linear regression with {} points'.format(self.num_points)) + LOG.debug(f'Running linear regression with {self.num_points} points') self._cached_gradient, self._cached_cor, *_ = sp.stats.linregress(self.slices, self.cors) def add_point(self, idx=None, slice_idx=0, cor=0.0): diff --git a/mantidimaging/core/utility/memory_usage.py b/mantidimaging/core/utility/memory_usage.py index 8925f5b7ef0..adaba75c9e8 100644 --- a/mantidimaging/core/utility/memory_usage.py +++ b/mantidimaging/core/utility/memory_usage.py @@ -51,7 +51,7 @@ def get_memory_usage_linux(kb=False, mb=False): def get_memory_usage_linux_str(): memory_in_kbs, memory_in_mbs = get_memory_usage_linux(kb=True, mb=True) # handle caching - memory_string = "{0} KB, {1} MB".format(memory_in_kbs, memory_in_mbs) + memory_string = f"{memory_in_kbs} KB, {memory_in_mbs} MB" # use an attribute to this function only, instead a global variable visible # outside @@ -66,7 +66,7 @@ def get_memory_usage_linux_str(): # remove cached memory, del removes the reference so that hasattr will # work correctly del get_memory_usage_linux_str.last_memory_cache - memory_string += ". Memory change: {0} MB".format(delta_memory) + memory_string += f". Memory change: {delta_memory} MB" return memory_string @@ -77,9 +77,8 @@ def debug_log_memory_usage_linux(message=""): # silently fail import resource as res log = getLogger(__name__) - log.info("Memory usage {} KB, {} MB".format( - res.getrusage(res.RUSAGE_SELF).ru_maxrss, - int(res.getrusage(res.RUSAGE_SELF).ru_maxrss) / 1024)) + max_rss = res.getrusage(res.RUSAGE_SELF).ru_maxrss + log.info(f"Memory usage {max_rss} KB, {int(max_rss) / 1024} MB") log.info(message) except ImportError: log.warning('Resource monitoring is not available on Windows') diff --git a/mantidimaging/core/utility/optional_imports.py b/mantidimaging/core/utility/optional_imports.py index 06c25cc8f14..13b2a78e64c 100644 --- a/mantidimaging/core/utility/optional_imports.py +++ b/mantidimaging/core/utility/optional_imports.py @@ -24,11 +24,11 @@ def safe_import(name): module = importlib.import_module(name) except ImportError: - warnings.warn('Failed to import optional module "{}"'.format(name), stacklevel=1) + warnings.warn(f'Failed to import optional module "{name}"', stacklevel=1) o = StringIO() traceback.print_stack(file=o) - getLogger(__name__).debug('Module import stack trace: {}'.format(o.getvalue())) + getLogger(__name__).debug(f'Module import stack trace: {o.getvalue()}') module = None diff --git a/mantidimaging/core/utility/progress_reporting/console_progress_bar.py b/mantidimaging/core/utility/progress_reporting/console_progress_bar.py index bed18f28df7..0b14e854d64 100644 --- a/mantidimaging/core/utility/progress_reporting/console_progress_bar.py +++ b/mantidimaging/core/utility/progress_reporting/console_progress_bar.py @@ -27,7 +27,7 @@ def __init__(self, width=70): self.width = width def progress_update(self): - suffix = '{}/{}'.format(self.progress.current_step, self.progress.end_step) + suffix = f'{self.progress.current_step}/{self.progress.end_step}' _print_ascii_progress_bar(self.progress.completion(), self.width, self.progress.task_name, suffix) diff --git a/mantidimaging/gui/dialogs/cor_inspection/presenter.py b/mantidimaging/gui/dialogs/cor_inspection/presenter.py index 7f9f59646e1..47e83b68c19 100644 --- a/mantidimaging/gui/dialogs/cor_inspection/presenter.py +++ b/mantidimaging/gui/dialogs/cor_inspection/presenter.py @@ -70,7 +70,7 @@ def on_load(self): self.notify(Notification.FULL_UPDATE) def on_select_image(self, img): - LOG.debug('Image selected: {}'.format(img)) + LOG.debug(f'Image selected: {img}') # Adjust COR/iterations step self.model.adjust(img) @@ -82,10 +82,10 @@ def on_select_image(self, img): self.do_refresh([ImageType.LESS, ImageType.MORE]) def _make_cor_title(self, image) -> str: - return 'COR: {}'.format(self.model.cor(image)) + return f'COR: {self.model.cor(image)}' def _make_iters_title(self, image) -> str: - return 'Iterations: {}'.format(self.model.iterations(image)) + return f'Iterations: {self.model.iterations(image)}' def do_refresh(self, images=None): if images is None: diff --git a/mantidimaging/gui/dialogs/cor_inspection/test/presenter_test.py b/mantidimaging/gui/dialogs/cor_inspection/test/presenter_test.py index 9a86ea04684..e64ae0608f6 100644 --- a/mantidimaging/gui/dialogs/cor_inspection/test/presenter_test.py +++ b/mantidimaging/gui/dialogs/cor_inspection/test/presenter_test.py @@ -37,7 +37,7 @@ def test_click_less(self): with self.assertLogs(self.presenter.__module__, level='DEBUG') as presenter_log: self.presenter.notify(Notification.IMAGE_CLICKED_LESS) self.model.adjust.assert_called_once_with(ImageType.LESS) - self.assertIn("Image selected: {}".format(ImageType.LESS), presenter_log.output[0]) + self.assertIn(f"Image selected: {ImageType.LESS}", presenter_log.output[0]) assert self.view.step_size == self.model.step calls = [ @@ -49,7 +49,7 @@ def test_click_current(self): with self.assertLogs(self.presenter.__module__, level='DEBUG') as presenter_log: self.presenter.notify(Notification.IMAGE_CLICKED_CURRENT) self.model.adjust.assert_called_once_with(ImageType.CURRENT) - self.assertIn("Image selected: {}".format(ImageType.CURRENT), presenter_log.output[0]) + self.assertIn(f"Image selected: {ImageType.CURRENT}", presenter_log.output[0]) assert self.view.step_size == self.model.step calls = [ @@ -62,7 +62,7 @@ def test_click_more(self): with self.assertLogs(self.presenter.__module__, level='DEBUG') as presenter_log: self.presenter.notify(Notification.IMAGE_CLICKED_MORE) self.model.adjust.assert_called_once_with(ImageType.MORE) - self.assertIn("Image selected: {}".format(ImageType.MORE), presenter_log.output[0]) + self.assertIn(f"Image selected: {ImageType.MORE}", presenter_log.output[0]) assert self.view.step_size == self.model.step calls = [ diff --git a/mantidimaging/gui/utility/qt_helpers.py b/mantidimaging/gui/utility/qt_helpers.py index cfac49ed17e..00382650912 100644 --- a/mantidimaging/gui/utility/qt_helpers.py +++ b/mantidimaging/gui/utility/qt_helpers.py @@ -52,8 +52,8 @@ def compile_ui(ui_file, qt_obj=None): def select_directory(field, caption): - assert isinstance(field, QLineEdit), ("The passed object is of type {0}. This function only works with " - "QLineEdit".format(type(field))) + assert isinstance(field, QLineEdit), (f"The passed object is of type {type(field)}. This function only works with " + "QLineEdit") # open file dialog and set the text if file is selected field.setText(QFileDialog.getExistingDirectory(caption=caption)) diff --git a/mantidimaging/gui/windows/operations/presenter.py b/mantidimaging/gui/windows/operations/presenter.py index 84995a287bc..21293e4f538 100644 --- a/mantidimaging/gui/windows/operations/presenter.py +++ b/mantidimaging/gui/windows/operations/presenter.py @@ -86,7 +86,7 @@ def _group_consecutive_values(slices: list[int]) -> list[str]: if len(rng) == 1: s = str(rng[0][1]) else: - s = "{}-{}".format(rng[0][1], rng[-1][1]) + s = f"{rng[0][1]}-{rng[-1][1]}" ranges.append(s) return ranges diff --git a/mantidimaging/gui/windows/recon/presenter.py b/mantidimaging/gui/windows/recon/presenter.py index f4defe70e9a..37aa854a274 100644 --- a/mantidimaging/gui/windows/recon/presenter.py +++ b/mantidimaging/gui/windows/recon/presenter.py @@ -311,10 +311,10 @@ def _do_refine_selected_cor(self): res = dialog.exec() dialog.deleteLater() - LOG.debug('COR refine dialog result: {}'.format(res)) + LOG.debug(f'COR refine dialog result: {res}') if res == CORInspectionDialogView.Accepted: new_cor = dialog.optimal_rotation_centre - LOG.debug('New optimal rotation centre: {}'.format(new_cor)) + LOG.debug(f'New optimal rotation centre: {new_cor}') self.model.data_model.set_cor_at_slice(slice_idx, new_cor.value) self.model.last_cor = new_cor # Update reconstruction preview with new COR @@ -327,10 +327,10 @@ def _do_refine_iterations(self) -> None: self.view.recon_params(), True) res = dialog.exec() - LOG.debug('COR refine iteration result: {}'.format(res)) + LOG.debug(f'COR refine iteration result: {res}') if res == CORInspectionDialogView.Accepted: new_iters = dialog.optimal_iterations - LOG.debug('New optimal iterations: {}'.format(new_iters)) + LOG.debug(f'New optimal iterations: {new_iters}') self.view.num_iter = new_iters def do_cor_fit(self) -> None: diff --git a/mantidimaging/gui/windows/spectrum_viewer/spectrum_widget.py b/mantidimaging/gui/windows/spectrum_viewer/spectrum_widget.py index 85d17262d3e..c3b84e7c792 100644 --- a/mantidimaging/gui/windows/spectrum_viewer/spectrum_widget.py +++ b/mantidimaging/gui/windows/spectrum_viewer/spectrum_widget.py @@ -234,8 +234,7 @@ def get_roi(self, roi_name: str) -> SensibleROI: size = CloseEnoughPoint(self.max_roi_size) return SensibleROI.from_points(pos, size) else: - raise KeyError("ROI with name {roi_name} does not exist in self.roi_dict or and is not 'all'".format( - roi_name=roi_name)) + raise KeyError(f"ROI with name {roi_name} does not exist in self.roi_dict or and is not 'all'") def remove_roi(self, roi_name: str) -> None: """ diff --git a/mantidimaging/gui/windows/stack_visualiser/presenter.py b/mantidimaging/gui/windows/stack_visualiser/presenter.py index e2b70fe5a6d..5c59cd46d1a 100644 --- a/mantidimaging/gui/windows/stack_visualiser/presenter.py +++ b/mantidimaging/gui/windows/stack_visualiser/presenter.py @@ -87,7 +87,7 @@ def get_parameter_value(self, parameter: SVParameters): return self.view.current_roi else: raise ValueError("Invalid parameter name has been requested from the Stack " - "Visualiser, parameter: {0}".format(parameter)) + f"Visualiser, parameter: {parameter}") def toggle_image_mode(self): if self.image_mode is SVImageMode.NORMAL: diff --git a/mantidimaging/gui/windows/stack_visualiser/view.py b/mantidimaging/gui/windows/stack_visualiser/view.py index a12a686c8c5..6f8374ebaa5 100644 --- a/mantidimaging/gui/windows/stack_visualiser/view.py +++ b/mantidimaging/gui/windows/stack_visualiser/view.py @@ -34,7 +34,7 @@ class StackVisualiserView(QDockWidget): def __init__(self, parent: MainWindowView, images: ImageStack): # enforce not showing a single image assert images.data.ndim == 3, \ - "Data does NOT have 3 dimensions! Dimensions found: {0}".format(images.data.ndim) + f"Data does NOT have 3 dimensions! Dimensions found: {images.data.ndim}" # We set the main window as the parent, the effect is the same as # having no parent, the window will be inside the QDockWidget. If the diff --git a/setup.py b/setup.py index ea5cbc95741..55a3f27bd81 100644 --- a/setup.py +++ b/setup.py @@ -55,7 +55,7 @@ def run(self): g.init() g.checkout(b="main") g.add(".") - g.commit("-m {}".format(self.commit_msg)) + g.commit(f"-m {self.commit_msg}") g.push("--force", self.repo, "main:gh-pages") From 179d6286f9d9a8f1e348033d0a17ea5f49ade001 Mon Sep 17 00:00:00 2001 From: Sam Tygier Date: Fri, 15 Mar 2024 11:13:32 +0000 Subject: [PATCH 2/6] Fix useless-object-inheritance (UP004) issues --- mantidimaging/core/io/loader/img_loader.py | 2 +- mantidimaging/core/utility/progress_reporting/progress.py | 4 ++-- mantidimaging/gui/dialogs/cor_inspection/model.py | 2 +- mantidimaging/gui/mvp_base/presenter.py | 2 +- mantidimaging/gui/mvp_base/test/presenter_test.py | 2 +- mantidimaging/gui/utility/qt_helpers.py | 2 +- mantidimaging/gui/windows/main/model.py | 2 +- mantidimaging/gui/windows/operations/model.py | 2 +- mantidimaging/gui/windows/recon/model.py | 2 +- mantidimaging/test_helpers/unit_test_helper.py | 2 +- 10 files changed, 11 insertions(+), 11 deletions(-) diff --git a/mantidimaging/core/io/loader/img_loader.py b/mantidimaging/core/io/loader/img_loader.py index af42e311db3..cde440c3ddd 100644 --- a/mantidimaging/core/io/loader/img_loader.py +++ b/mantidimaging/core/io/loader/img_loader.py @@ -55,7 +55,7 @@ def execute(load_func: Callable[[str], np.ndarray], return ImageStack(sample_data, chosen_input_filenames, indices) -class ImageLoader(object): +class ImageLoader: def __init__(self, load_func: Callable[[str], np.ndarray], diff --git a/mantidimaging/core/utility/progress_reporting/progress.py b/mantidimaging/core/utility/progress_reporting/progress.py index 7953404f8e8..b45009b2247 100644 --- a/mantidimaging/core/utility/progress_reporting/progress.py +++ b/mantidimaging/core/utility/progress_reporting/progress.py @@ -12,7 +12,7 @@ ProgressHistory = NamedTuple('ProgressHistory', [('time', float), ('step', int), ('msg', str)]) -class ProgressHandler(object): +class ProgressHandler: def __init__(self): self.progress = None @@ -24,7 +24,7 @@ def progress_update(self): STEPS_TO_AVERAGE = 30 -class Progress(object): +class Progress: """ Class used to perform basic progress monitoring and reporting. """ diff --git a/mantidimaging/gui/dialogs/cor_inspection/model.py b/mantidimaging/gui/dialogs/cor_inspection/model.py index 4b97b8eb284..21d0fe60346 100644 --- a/mantidimaging/gui/dialogs/cor_inspection/model.py +++ b/mantidimaging/gui/dialogs/cor_inspection/model.py @@ -15,7 +15,7 @@ INIT_ITERS_STEP = 50 -class CORInspectionDialogModel(object): +class CORInspectionDialogModel: step: int | float def __init__(self, images: ImageStack, slice_idx: int, initial_cor: ScalarCoR, diff --git a/mantidimaging/gui/mvp_base/presenter.py b/mantidimaging/gui/mvp_base/presenter.py index 84fb40cc2b4..1c22774dae9 100644 --- a/mantidimaging/gui/mvp_base/presenter.py +++ b/mantidimaging/gui/mvp_base/presenter.py @@ -9,7 +9,7 @@ from mantidimaging.gui.mvp_base import BaseMainWindowView, BaseDialogView # pragma: no cover -class BasePresenter(object): +class BasePresenter: view: BaseMainWindowView | BaseDialogView def __init__(self, view: BaseMainWindowView): diff --git a/mantidimaging/gui/mvp_base/test/presenter_test.py b/mantidimaging/gui/mvp_base/test/presenter_test.py index 5eb3ba77876..d96e907b5a9 100644 --- a/mantidimaging/gui/mvp_base/test/presenter_test.py +++ b/mantidimaging/gui/mvp_base/test/presenter_test.py @@ -35,7 +35,7 @@ def test_show_error_message_forwarded_to_dialog_view(self): def test_bad_view_causes_errors_to_be_logged(self): - class V(object): + class V: pass view = V() diff --git a/mantidimaging/gui/utility/qt_helpers.py b/mantidimaging/gui/utility/qt_helpers.py index 00382650912..83a95634ecf 100644 --- a/mantidimaging/gui/utility/qt_helpers.py +++ b/mantidimaging/gui/utility/qt_helpers.py @@ -22,7 +22,7 @@ INPUT_DIALOG_FLAGS = Qt.WindowSystemMenuHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint -class BlockQtSignals(object): +class BlockQtSignals: """ Used to block Qt signals from a selection of QWidgets within a context. """ diff --git a/mantidimaging/gui/windows/main/model.py b/mantidimaging/gui/windows/main/model.py index 7ac603f13d2..e0aea41cc8d 100644 --- a/mantidimaging/gui/windows/main/model.py +++ b/mantidimaging/gui/windows/main/model.py @@ -23,7 +23,7 @@ def _matching_dataset_attribute(dataset_attribute: ImageStack | None, images_id: return isinstance(dataset_attribute, ImageStack) and dataset_attribute.id == images_id -class MainWindowModel(object): +class MainWindowModel: def __init__(self) -> None: super().__init__() diff --git a/mantidimaging/gui/windows/operations/model.py b/mantidimaging/gui/windows/operations/model.py index 55592c6fad6..1b426a3be77 100644 --- a/mantidimaging/gui/windows/operations/model.py +++ b/mantidimaging/gui/windows/operations/model.py @@ -18,7 +18,7 @@ from mantidimaging.core.operations.loader import BaseFilterClass -class FiltersWindowModel(object): +class FiltersWindowModel: filters: list[BaseFilterClass] selected_filter: BaseFilterClass filter_widget_kwargs: dict[str, Any] diff --git a/mantidimaging/gui/windows/recon/model.py b/mantidimaging/gui/windows/recon/model.py index d3d926b5017..7fb7cdcf7fb 100644 --- a/mantidimaging/gui/windows/recon/model.py +++ b/mantidimaging/gui/windows/recon/model.py @@ -25,7 +25,7 @@ LOG = getLogger(__name__) -class ReconstructWindowModel(object): +class ReconstructWindowModel: def __init__(self, data_model: CorTiltPointQtModel): self._images: ImageStack | None = None diff --git a/mantidimaging/test_helpers/unit_test_helper.py b/mantidimaging/test_helpers/unit_test_helper.py index bddb37a3811..433b4cfd803 100644 --- a/mantidimaging/test_helpers/unit_test_helper.py +++ b/mantidimaging/test_helpers/unit_test_helper.py @@ -117,7 +117,7 @@ def assert_files_exist(cls, base_name, file_extension, file_extension_separator= cls.assertTrue(os.path.isfile(filename)) -class IgnoreOutputStreams(object): +class IgnoreOutputStreams: def __init__(self): self.stdout = None From d95aed36359016756c7d623f887f19eff7725057 Mon Sep 17 00:00:00 2001 From: Sam Tygier Date: Fri, 15 Mar 2024 11:16:50 +0000 Subject: [PATCH 3/6] Fix redundant-open-modes (UP015) issues --- mantidimaging/core/gpu/utility.py | 2 +- mantidimaging/core/io/loader/loader.py | 2 +- mantidimaging/core/utility/projection_angle_parser.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/mantidimaging/core/gpu/utility.py b/mantidimaging/core/gpu/utility.py index 8536a96120e..bc0e74af5bb 100644 --- a/mantidimaging/core/gpu/utility.py +++ b/mantidimaging/core/gpu/utility.py @@ -79,7 +79,7 @@ def _load_cuda_kernel(dtype): :return: The CUDA kernel in string format. """ cuda_kernel = "" - with open(os.path.join(os.path.dirname(__file__), KERNEL_FILENAME), "r") as f: + with open(os.path.join(os.path.dirname(__file__), KERNEL_FILENAME)) as f: cuda_kernel += f.read() if "float64" in str(dtype): return cuda_kernel.replace("float", "double") diff --git a/mantidimaging/core/io/loader/loader.py b/mantidimaging/core/io/loader/loader.py index 9e7e71c3c69..3926a1412fe 100644 --- a/mantidimaging/core/io/loader/loader.py +++ b/mantidimaging/core/io/loader/loader.py @@ -94,7 +94,7 @@ def read_image_dimensions(file_path: Path) -> tuple[int, int]: def load_log(log_file: Path) -> InstrumentLog: - with open(log_file, 'r') as f: + with open(log_file) as f: return InstrumentLog(f.readlines(), log_file) diff --git a/mantidimaging/core/utility/projection_angle_parser.py b/mantidimaging/core/utility/projection_angle_parser.py index 6fa818e22e3..b3a68b74e60 100644 --- a/mantidimaging/core/utility/projection_angle_parser.py +++ b/mantidimaging/core/utility/projection_angle_parser.py @@ -11,7 +11,7 @@ class ProjectionAngleFileParser: separated values on a single line, or a single angle value per line" def __init__(self, file: str) -> None: - with open(file, 'r') as f: + with open(file) as f: self.contents = f.readlines() def get_projection_angles(self) -> ProjectionAngles: From 258b22eb132c433c7bae1948e908dcfba2779fef Mon Sep 17 00:00:00 2001 From: Sam Tygier Date: Fri, 15 Mar 2024 11:19:57 +0000 Subject: [PATCH 4/6] Fix unnecessary-encode-utf8 (UP012) issues --- .../gui/windows/nexus_load_dialog/test/presenter_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mantidimaging/gui/windows/nexus_load_dialog/test/presenter_test.py b/mantidimaging/gui/windows/nexus_load_dialog/test/presenter_test.py index e6816a720a0..b8bdd23e2cc 100644 --- a/mantidimaging/gui/windows/nexus_load_dialog/test/presenter_test.py +++ b/mantidimaging/gui/windows/nexus_load_dialog/test/presenter_test.py @@ -263,7 +263,7 @@ def test_image_names(self): def test_empty_name_field(self): del self.tomo_entry["title"] - self.tomo_entry["title"] = "".encode("UTF-8") + self.tomo_entry["title"] = b"" self.nexus_loader.tomo_entry = self.tomo_entry with self.assertLogs(nexus_logger, level="INFO") as log_mock: assert self.nexus_loader._find_data_title() == "NeXus Data" From 6854887c36e1241370329dc6f0225377e9853560 Mon Sep 17 00:00:00 2001 From: Sam Tygier Date: Fri, 15 Mar 2024 11:24:32 +0000 Subject: [PATCH 5/6] Fix os-error-alias (UP024) issues --- mantidimaging/core/io/loader/img_loader.py | 2 +- mantidimaging/eyes_tests/eyes_manager.py | 2 +- mantidimaging/gui/windows/live_viewer/presenter.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/mantidimaging/core/io/loader/img_loader.py b/mantidimaging/core/io/loader/img_loader.py index cde440c3ddd..0c8efcc999f 100644 --- a/mantidimaging/core/io/loader/img_loader.py +++ b/mantidimaging/core/io/loader/img_loader.py @@ -92,7 +92,7 @@ def _do_files_load_seq(self, data: pu.SharedArray, files: list[str]) -> pu.Share "dimensions! All images must have the same " f"dimensions. Expected dimensions: {self.img_shape} Error " f"message: {exc}") from exc - except IOError as exc: + except OSError as exc: raise RuntimeError(f"Could not load file {in_file}. Error details: {exc}") from exc return data diff --git a/mantidimaging/eyes_tests/eyes_manager.py b/mantidimaging/eyes_tests/eyes_manager.py index a9f3cac4cd6..d958f0c3c1b 100644 --- a/mantidimaging/eyes_tests/eyes_manager.py +++ b/mantidimaging/eyes_tests/eyes_manager.py @@ -111,7 +111,7 @@ def _take_screenshot(self, widget: QWidget = None, image_name=None): if window_image.save(file_path, "PNG"): return file_path else: - raise IOError("Failed to save", file_path) + raise OSError("Failed to save", file_path) def close_eyes(self): if self.eyes.is_open: diff --git a/mantidimaging/gui/windows/live_viewer/presenter.py b/mantidimaging/gui/windows/live_viewer/presenter.py index 8215eeaa653..2c1294ab2db 100644 --- a/mantidimaging/gui/windows/live_viewer/presenter.py +++ b/mantidimaging/gui/windows/live_viewer/presenter.py @@ -88,7 +88,7 @@ def display_image(self, image_path: Path): """ try: image_data = self.load_image(image_path) - except (IOError, KeyError, ValueError, TiffFileError, DeflateError) as error: + except (OSError, KeyError, ValueError, TiffFileError, DeflateError) as error: message = f"{type(error).__name__} reading image: {image_path}: {error}" logger.error(message) self.view.remove_image() From 0dba7c2e52e20ff5755634471a0e29cd9e923729 Mon Sep 17 00:00:00 2001 From: Sam Tygier Date: Fri, 15 Mar 2024 11:36:05 +0000 Subject: [PATCH 6/6] Fix extraneous-parentheses (UP034) issues --- mantidimaging/core/operations/crop_coords/crop_coords.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mantidimaging/core/operations/crop_coords/crop_coords.py b/mantidimaging/core/operations/crop_coords/crop_coords.py index c570260fa33..7758c3f888c 100644 --- a/mantidimaging/core/operations/crop_coords/crop_coords.py +++ b/mantidimaging/core/operations/crop_coords/crop_coords.py @@ -64,7 +64,7 @@ def filter_func(images: ImageStack, sample = images.data shape = (sample.shape[0], region_of_interest.height, region_of_interest.width) - if any((s < 0 for s in shape)): + if any(s < 0 for s in shape): raise ValueError("It seems the Region of Interest is outside of the current image dimensions.\n" "This can happen on the image preview right after a previous Crop Coordinates.")