Skip to content

Commit

Permalink
Fixes for remaining ruff UP rules (#2142)
Browse files Browse the repository at this point in the history
  • Loading branch information
JackEAllen committed Mar 18, 2024
2 parents 3fd5227 + 0dba7c2 commit ef070b6
Show file tree
Hide file tree
Showing 34 changed files with 56 additions and 63 deletions.
2 changes: 1 addition & 1 deletion mantidimaging/core/gpu/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/io/loader/img_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions mantidimaging/core/io/loader/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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')

Expand Down
8 changes: 4 additions & 4 deletions mantidimaging/core/io/saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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}')
7 changes: 1 addition & 6 deletions mantidimaging/core/io/test/io_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/operations/crop_coords/crop_coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")

Expand Down Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/reconstruct/astra_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/reconstruct/cil_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/reconstruct/tomopy_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/rotation/data_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 4 additions & 5 deletions mantidimaging/core/utility/memory_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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')
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/optional_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/progress_reporting/progress.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
ProgressHistory = NamedTuple('ProgressHistory', [('time', float), ('step', int), ('msg', str)])


class ProgressHandler(object):
class ProgressHandler:

def __init__(self):
self.progress = None
Expand All @@ -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.
"""
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/utility/projection_angle_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/eyes_tests/eyes_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/dialogs/cor_inspection/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions mantidimaging/gui/dialogs/cor_inspection/presenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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 = [
Expand All @@ -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 = [
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/mvp_base/presenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/mvp_base/test/presenter_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions mantidimaging/gui/utility/qt_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/windows/live_viewer/presenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/windows/main/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/windows/operations/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/windows/operations/presenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/gui/windows/recon/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
LOG = getLogger(__name__)


class ReconstructWindowModel(object):
class ReconstructWindowModel:

def __init__(self, data_model: CorTiltPointQtModel):
self._images: ImageStack | None = None
Expand Down

0 comments on commit ef070b6

Please sign in to comment.