diff --git a/app.py b/app.py index 6ce84a0ff..c18f08270 100644 --- a/app.py +++ b/app.py @@ -18,8 +18,6 @@ # detalhes. # ------------------------------------------------------------------------- -from __future__ import print_function - import argparse import multiprocessing import os @@ -53,11 +51,7 @@ os.environ["GDK_BACKEND"] = "x11" import wx - -try: - from wx.adv import SplashScreen -except ImportError: - from wx import SplashScreen +from wx.adv import SPLASH_CENTRE_ON_SCREEN, SPLASH_TIMEOUT, SplashScreen # import wx.lib.agw.advancedsplash as agw # if sys.platform.startswith('linux'): @@ -66,6 +60,7 @@ # if sys.platform != 'darwin': # _SplashScreen = wx.SplashScreen import invesalius.gui.language_dialog as lang_dlg +import invesalius.gui.log as log import invesalius.i18n as i18n import invesalius.session as ses import invesalius.utils as utils @@ -78,13 +73,8 @@ # ------------------------------------------------------------------ if sys.platform in ("linux2", "linux", "win32"): - try: - tmp_var = wx.GetXDisplay - except AttributeError: - # A workaround to make InVesalius run with wxPython4 from Ubuntu 18.04 - wx.GetXDisplay = lambda: None - else: - del tmp_var + if not hasattr(wx, "GetXDisplay"): + setattr(wx, "GetXDisplay", lambda: None) session = ses.Session() @@ -96,8 +86,6 @@ except FileNotFoundError: pass -import invesalius.gui.log as log - class InVesalius(wx.App): """ @@ -203,7 +191,7 @@ def __init__(self): icon_file = "splash_" + lang + ".png" if hasattr(sys, "frozen") and ( - sys.frozen == "windows_exe" or sys.frozen == "console_exe" + getattr(sys, "frozen") == "windows_exe" or getattr(sys, "frozen") == "console_exe" ): abs_file_path = os.path.abspath(".." + os.sep) path = abs_file_path @@ -215,10 +203,7 @@ def __init__(self): bmp = wx.Image(path).ConvertToBitmap() - try: - style = wx.adv.SPLASH_TIMEOUT | wx.adv.SPLASH_CENTRE_ON_SCREEN - except AttributeError: - style = wx.SPLASH_TIMEOUT | wx.SPLASH_CENTRE_ON_SCREEN + style = SPLASH_TIMEOUT | SPLASH_CENTRE_ON_SCREEN SplashScreen.__init__( self, bitmap=bmp, splashStyle=style, milliseconds=1500, id=-1, parent=None @@ -232,7 +217,6 @@ def Startup(self): # while splash is being shown from invesalius.control import Controller from invesalius.gui.frame import Frame - from invesalius.project import Project self.main = Frame(None) self.control = Controller(self.main) @@ -289,14 +273,13 @@ def non_gui_startup(args): _ = i18n.InstallLanguage(lang) from invesalius.control import Controller - from invesalius.project import Project session = ses.Session() if not session.ReadConfig(): session.CreateConfig() session.SetConfig("language", lang) - control = Controller(None) + _ = Controller(None) use_cmd_optargs(args) @@ -441,9 +424,9 @@ def check_for_export(args, suffix="", remove_surfaces=False): if suffix: if args.export.endswith(".stl"): - path_ = "{}-{}.stl".format(args.export[:-4], suffix) + path_ = f"{args.export[:-4]}-{suffix}.stl" else: - path_ = "{}-{}.stl".format(args.export, suffix) + path_ = f"{args.export}-{suffix}.stl" else: path_ = args.export @@ -455,9 +438,9 @@ def check_for_export(args, suffix="", remove_surfaces=False): for threshold_name, threshold_range in Project().presets.thresh_ct.items(): if isinstance(threshold_range[0], int): - path_ = "{}-{}-{}.stl".format(args.export_to_all, suffix, threshold_name) + path_ = f"{args.export_to_all}-{suffix}-{threshold_name}.stl" export(path_, threshold_range, remove_surface=True) - except: + except Exception: traceback.print_exc() finally: exit(0) @@ -469,14 +452,15 @@ def check_for_export(args, suffix="", remove_surfaces=False): export_filename = args.export_project if suffix: export_filename, ext = os.path.splitext(export_filename) - export_filename = "{}-{}{}".format(export_filename, suffix, ext) + export_filename = f"{export_filename}-{suffix}{ext}" prj.export_project(export_filename, save_masks=args.save_masks) - print("Saved {}".format(export_filename)) + print(f"Saved {export_filename}") def export(path_, threshold_range, remove_surface=False): import invesalius.constants as const + from invesalius.i18n import tr as _ Publisher.sendMessage("Set threshold values", threshold_range=threshold_range) @@ -504,7 +488,7 @@ def print_events(topic=Publisher.AUTO_TOPIC, **msg_data): """ Print pubsub messages """ - utils.debug("%s\n\tParameters: %s" % (topic, msg_data)) + utils.debug(f"{topic}\n\tParameters: {msg_data}") def init(): @@ -517,7 +501,7 @@ def init(): multiprocessing.freeze_support() # Needed in win 32 exe - if hasattr(sys, "frozen") and sys.platform.startswith("win"): + if hasattr(sys, "frozen") and sys.platform == "win32": # Click in the .inv3 file support root = winreg.HKEY_CLASSES_ROOT key = "InVesalius 3.1\InstallationDir" @@ -532,9 +516,9 @@ def init(): if inv_paths.OLD_USER_INV_DIR.exists(): inv_paths.copy_old_files() - if hasattr(sys, "frozen") and sys.frozen == "windows_exe": + if hasattr(sys, "frozen") and getattr(sys, "frozen") == "windows_exe": # Set system standard error output to file - path = inv_paths.USER_LOG_DIR.join("stderr.log") + path = inv_paths.USER_LOG_DIR.joinpath("stderr.log") sys.stderr = open(path, "w") @@ -586,7 +570,7 @@ def main(connection=None, remote_host=None): if args.no_gui: non_gui_startup(args) else: - application = InVesalius(0) + application = InVesalius(False) application.MainLoop() diff --git a/invesalius/control.py b/invesalius/control.py index e81fe446a..519b6aec7 100644 --- a/invesalius/control.py +++ b/invesalius/control.py @@ -384,8 +384,6 @@ def SaveProject(self, path: Optional["str | Path"] = None, compress: bool = Fals if isinstance(filename, str): filename = utils.decode(filename, const.FS_ENCODE) - proj = prj.Project() - # Update progress dialog Publisher.sendMessage( "Update Progress bar", value=30, msg="Preparing to save project..." @@ -702,13 +700,13 @@ def CreateBitmapProject(self, bmp_data, rec_data, matrix, matrix_filename): name = rec_data[0] orientation = rec_data[1] - sp_x = float(rec_data[2]) - sp_y = float(rec_data[3]) - sp_z = float(rec_data[4]) - interval = int(rec_data[5]) + # sp_x = float(rec_data[2]) + # sp_y = float(rec_data[3]) + # sp_z = float(rec_data[4]) + # interval = int(rec_data[5]) - bits = bmp_data.GetFirstPixelSize() - sx, sy = size = bmp_data.GetFirstBitmapSize() + # bits = bmp_data.GetFirstPixelSize() + # sx, sy = size = bmp_data.GetFirstBitmapSize() proj = prj.Project() proj.name = name @@ -988,20 +986,20 @@ def OpenDicomGroup( size = dicom.image.size bits = dicom.image.bits_allocad - sop_class_uid = dicom.acquisition.sop_class_uid + # sop_class_uid = dicom.acquisition.sop_class_uid xyspacing = dicom.image.spacing orientation = dicom.image.orientation_label - samples_per_pixel = dicom.image.samples_per_pixel + # samples_per_pixel = dicom.image.samples_per_pixel wl = float(dicom.image.level) ww = float(dicom.image.window) - if sop_class_uid == "1.2.840.10008.5.1.4.1.1.7": # Secondary Capture Image Storage - use_dcmspacing = 1 - else: - use_dcmspacing = 0 + # if sop_class_uid == "1.2.840.10008.5.1.4.1.1.7": # Secondary Capture Image Storage + # use_dcmspacing = 1 + # else: + # use_dcmspacing = 0 - imagedata = None + # imagedata = None if dicom.image.number_of_frames == 1: sx, sy = size diff --git a/invesalius/data/actor_factory.py b/invesalius/data/actor_factory.py index 53d0a6ac1..c326f0d12 100644 --- a/invesalius/data/actor_factory.py +++ b/invesalius/data/actor_factory.py @@ -10,7 +10,7 @@ from invesalius import inv_paths -class ActorFactory(object): +class ActorFactory: def __init__(self): pass diff --git a/invesalius/data/brainmesh_handler.py b/invesalius/data/brainmesh_handler.py index 310e06311..901100b61 100644 --- a/invesalius/data/brainmesh_handler.py +++ b/invesalius/data/brainmesh_handler.py @@ -3,7 +3,7 @@ # import os import pyvista -from vtkmodules.vtkCommonColor import vtkColorSeries, vtkNamedColors +from vtkmodules.vtkCommonColor import vtkColorSeries # import Trekker from vtkmodules.vtkCommonCore import ( diff --git a/invesalius/data/coordinates.py b/invesalius/data/coordinates.py index 68aa56fee..fbdfdba3e 100644 --- a/invesalius/data/coordinates.py +++ b/invesalius/data/coordinates.py @@ -21,7 +21,7 @@ from math import cos, sin from random import uniform from time import sleep -from typing import TYPE_CHECKING, Any, List, Optional, Sequence, Tuple, Union +from typing import TYPE_CHECKING, List, Optional, Sequence, Tuple, Union import numpy as np import wx diff --git a/invesalius/data/cursor_actors.py b/invesalius/data/cursor_actors.py index d3a797dff..b7f6b84a0 100644 --- a/invesalius/data/cursor_actors.py +++ b/invesalius/data/cursor_actors.py @@ -77,7 +77,7 @@ def to_vtk(n_array, spacing, slice_number, orientation): return image_copy -class CursorBase(object): +class CursorBase: def __init__(self): self.colour = (0.0, 0.0, 1.0) self.opacity = 1 @@ -216,7 +216,7 @@ def _calculate_area_pixels(self): pass def _set_colour(self, imagedata, colour): - scalar_range = int(imagedata.GetScalarRange()[1]) + # scalar_range = int(imagedata.GetScalarRange()[1]) r, g, b = colour[:3] # map scalar values into colors @@ -247,7 +247,7 @@ class CursorCircle(CursorBase): # CursorCircleActor(vtkActor) def __init__(self): self.radius = 15.0 - super(CursorCircle, self).__init__() + super().__init__() def _build_actor(self): """ @@ -307,7 +307,7 @@ def _calculate_area_pixels(self): if self.unit == "µm": r /= 1000.0 if self.unit == "px": - sx, sy, sz = 1.0, 1.0, 1.0 + sx, sy = 1.0, 1.0 else: if self.orientation == "AXIAL": sx = self.spacing[0] @@ -333,7 +333,7 @@ def _calculate_area_pixels(self): class CursorRectangle(CursorBase): def __init__(self): self.radius = 15.0 - super(CursorRectangle, self).__init__() + super().__init__() def _build_actor(self): """ diff --git a/invesalius/data/e_field.py b/invesalius/data/e_field.py index 4fb3a4c07..974e54941 100644 --- a/invesalius/data/e_field.py +++ b/invesalius/data/e_field.py @@ -92,7 +92,7 @@ def run(self): ) try: self.e_field_norms_queue.put_nowait( - ([T_rot, cp, coord, enorm, id_list]) + [T_rot, cp, coord, enorm, id_list] ) except queue.Full: diff --git a/invesalius/data/editor.py b/invesalius/data/editor.py index 6abbd9e43..e824fb033 100644 --- a/invesalius/data/editor.py +++ b/invesalius/data/editor.py @@ -49,12 +49,12 @@ def __init__(self): self.lut = vtkLookupTable() self.lut_original = vtkLookupTable() self.image_color = vtkImageMapToColors() - self.blend = blend = vtkImageBlend() - self.map = map = vtkImageMapper() + self.blend = vtkImageBlend() + self.map = vtkImageMapper() - self.actor = actor = vtkImageActor() - self.actor2 = actor2 = vtkImageActor() - self.actor3 = actor3 = vtkImageActor() + self.actor = vtkImageActor() + self.actor2 = vtkImageActor() + self.actor3 = vtkImageActor() self.image_color_o = vtkImageMapToColors() @@ -84,7 +84,7 @@ def SetInteractor(self, interactor): istyle.AddObserver("LeftButtonReleaseEvent", self.Release) istyle.AddObserver("MouseMoveEvent", self.Moved) - pick = self.pick = vtkCellPicker() + self.pick = vtkCellPicker() def SetActor(self, actor): self.actor = actor @@ -220,7 +220,7 @@ def DoOperation(self, xc, yc, zc): Extracted equation. http://www.mathopenref.com/chord.html """ - extent = self.image.GetWholeExtent() + # extent = self.image.GetWholeExtent() cursor = self.cursor b = [0, 0, 0, 0, 0, 0] self.actor.GetDisplayBounds(b) @@ -244,7 +244,7 @@ def DoOperation(self, xc, yc, zc): operation = self.PixelThresholdLevel try: [operation(*o(k, yi)) for k, yi in cursor.GetPoints()] - except: + except Exception: pass # if extent[0] <= k+xc <= extent[1] \ # and extent[2] <= yi+yc <=extent[3]] diff --git a/invesalius/data/geometry.py b/invesalius/data/geometry.py index 41bd880ba..31f3c430c 100644 --- a/invesalius/data/geometry.py +++ b/invesalius/data/geometry.py @@ -295,12 +295,12 @@ def __init__(self): def MouseMove(self, x, y): self.MouseInLine(x, y) - x_pos_sl_, y_pos_sl_ = self.viewer.get_slice_pixel_coord_by_screen_pos(x, y) + # x_pos_sl_, y_pos_sl_ = self.viewer.get_slice_pixel_coord_by_screen_pos(x, y) slice_spacing = self.viewer.slice_.spacing xs, ys, zs = slice_spacing - x_pos_sl = x_pos_sl_ * xs - y_pos_sl = y_pos_sl_ * ys + # x_pos_sl = x_pos_sl_ * xs + # y_pos_sl = y_pos_sl_ * ys x, y, z = self.viewer.get_voxel_coord_by_screen_pos(x, y) @@ -385,7 +385,7 @@ def MouseInLine(self, x, y): if ( self.point_into_box(p0, p1, (x_pos_sl, y_pos_sl), "AXIAL") - and self.status_move == None + and self.status_move is None ): self.crop_pan = const.CROP_PAN # break @@ -415,7 +415,7 @@ def MouseInLine(self, x, y): if ( self.point_into_box(p0, p1, (x_pos_sl, y_pos_sl), "CORONAL") - and self.status_move == None + and self.status_move is None ): self.crop_pan = const.CROP_PAN # break @@ -446,7 +446,7 @@ def MouseInLine(self, x, y): if ( self.point_into_box(p0, p1, (x_pos_sl, y_pos_sl), "SAGITAL") - and self.status_move == None + and self.status_move is None ): self.crop_pan = const.CROP_PAN # break diff --git a/invesalius/data/imagedata_utils.py b/invesalius/data/imagedata_utils.py index 071706358..cb79c6657 100644 --- a/invesalius/data/imagedata_utils.py +++ b/invesalius/data/imagedata_utils.py @@ -19,7 +19,6 @@ import math import os -import sys import tempfile import gdcm @@ -43,16 +42,6 @@ from invesalius.data import vtk_utils as vtk_utils from invesalius.i18n import tr as _ -if sys.platform == "win32": - try: - import win32api - - _has_win32api = True - except ImportError: - _has_win32api = False -else: - _has_win32api = False - # TODO: Test cases which are originally in sagittal/coronal orientation # and have gantry @@ -65,7 +54,7 @@ def ResampleImage3D(imagedata, value): extent = imagedata.GetExtent() size = imagedata.GetDimensions() - width = float(size[0]) + # width = float(size[0]) height = float(size[1] / value) resolution = (height / (extent[1] - extent[0]) + 1) * spacing[1] @@ -84,8 +73,8 @@ def ResampleImage2D(imagedata, px=None, py=None, resolution_percentage=None, upd """ extent = imagedata.GetExtent() - spacing = imagedata.GetSpacing() - dimensions = imagedata.GetDimensions() + # spacing = imagedata.GetSpacing() + # dimensions = imagedata.GetDimensions() if resolution_percentage: factor_x = resolution_percentage @@ -356,7 +345,6 @@ def bitmap2memmap(files, slice_size, orientation, spacing, resolution_percentage max_scalar = None min_scalar = None - xy_shape = None first_resample_entry = False for n, f in enumerate(files): diff --git a/invesalius/data/markers/marker.py b/invesalius/data/markers/marker.py index 4bacaa791..aafc444b7 100644 --- a/invesalius/data/markers/marker.py +++ b/invesalius/data/markers/marker.py @@ -163,7 +163,7 @@ def to_csv_header(cls): if (field.name != "version" and field.name != "marker_uuid") ] res.extend(["x_world", "y_world", "z_world", "alpha_world", "beta_world", "gamma_world"]) - return "\t".join(map(lambda x: '"%s"' % x, res)) + return "\t".join(map(lambda x: f'"{x}"', res)) def to_csv_row(self): """Serialize to excel-friendly tab-separated string""" @@ -178,11 +178,11 @@ def to_csv_row(self): continue if field.type is str: - res += '"%s"\t' % getattr(self, field.name) + res += f'"{getattr(self, field.name)}"\t' elif field.type is MarkerType: - res += "%s\t" % getattr(self, field.name).value + res += f"{getattr(self, field.name).value}\t" else: - res += "%s\t" % str(getattr(self, field.name)) + res += f"{str(getattr(self, field.name))}\t" if self.alpha is not None and self.beta is not None and self.gamma is not None: # Add world coordinates (in addition to the internal ones). diff --git a/invesalius/data/markers/marker_transformator.py b/invesalius/data/markers/marker_transformator.py index 612f96143..47cbfe916 100644 --- a/invesalius/data/markers/marker_transformator.py +++ b/invesalius/data/markers/marker_transformator.py @@ -1,7 +1,4 @@ -import math - import numpy as np -import vtk import invesalius.constants as const import invesalius.data.coordinates as dco diff --git a/invesalius/data/markers/surface_geometry.py b/invesalius/data/markers/surface_geometry.py index c48ca2022..296be5c03 100644 --- a/invesalius/data/markers/surface_geometry.py +++ b/invesalius/data/markers/surface_geometry.py @@ -1,8 +1,5 @@ -import numpy as np import vtk -import wx -import invesalius.data.coordinates as dco from invesalius.gui import dialogs from invesalius.pubsub import pub as Publisher from invesalius.utils import Singleton diff --git a/invesalius/data/mask.py b/invesalius/data/mask.py index f6f37dfcc..bb444b938 100644 --- a/invesalius/data/mask.py +++ b/invesalius/data/mask.py @@ -27,7 +27,6 @@ import numpy as np from scipy import ndimage -from vtkmodules.util import numpy_support import invesalius.constants as const import invesalius.data.converters as converters @@ -37,7 +36,7 @@ from invesalius_cy import floodfill -class EditionHistoryNode(object): +class EditionHistoryNode: def __init__(self, index, orientation, array, clean=False): self.index = index self.orientation = orientation @@ -75,7 +74,7 @@ def __del__(self): os.remove(self.filename) -class EditionHistory(object): +class EditionHistory: def __init__(self, size=50): self.history = [] self.index = -1 @@ -295,8 +294,8 @@ def _update_imagedata(self, update_volume_viewer=True): def SavePlist(self, dir_temp, filelist): mask = {} filename = "mask_%d" % self.index - mask_filename = "%s.dat" % filename - mask_filepath = os.path.join(dir_temp, mask_filename) + mask_filename = f"{filename}.dat" + # mask_filepath = os.path.join(dir_temp, mask_filename) filelist[self.temp_file] = mask_filename # self._save_mask(mask_filepath) diff --git a/invesalius/data/measures.py b/invesalius/data/measures.py index 4eb2fc662..e2c570012 100644 --- a/invesalius/data/measures.py +++ b/invesalius/data/measures.py @@ -133,7 +133,7 @@ def __len__(self): return len(self._list_measures) -class MeasurementManager(object): +class MeasurementManager: """ A class to manage the use (Addition, remotion and visibility) from measures. @@ -279,9 +279,9 @@ def _add_point(self, position, type, location, slice_number=0, radius=const.PROP type_ = TYPE[type] location = LOCATION[location] if type == const.LINEAR: - value = "%.3f mm" % m.value + value = f"{m.value:.3f} mm" else: - value = "%.3f°" % m.value + value = f"{m.value:.3f}°" msg = ("Update measurement info in GUI",) Publisher.sendMessage( @@ -317,9 +317,9 @@ def _change_measure_point_pos(self, index, npoint, pos): location = LOCATION[m.location] if m.type == const.LINEAR: - value = "%.3f mm" % m.value + value = f"{m.value:.3f} mm" else: - value = "%.3f°" % m.value + value = f"{m.value:.3f}°" Publisher.sendMessage( "Update measurement info in GUI", @@ -370,7 +370,7 @@ def _rm_incomplete_measurements(self): self.measures.remove((m, mr)) Publisher.sendMessage("Remove GUI measurement", measure_index=idx) actors = mr.GetActors() - slice_number = self.current[0].slice_number + # slice_number = self.current[0].slice_number if m.location == const.SURFACE: Publisher.sendMessage( ("Remove actors " + str(self.current[0].location)), actors=actors @@ -412,7 +412,7 @@ def _add_density_measure(self, density_measure): self.measures.append((m, density_measure)) - index = prj.Project().AddMeasurement(m) + # index = prj.Project().AddMeasurement(m) msg = ("Update measurement info in GUI",) Publisher.sendMessage( @@ -422,7 +422,7 @@ def _add_density_measure(self, density_measure): colour=m.colour, location=density_measure.orientation, type_="Density", - value="%.3f" % m.value, + value=f"{m.value:.3f}", ) def OnCloseProject(self): @@ -530,7 +530,7 @@ def get_as_dict(self): return d -class CirclePointRepresentation(object): +class CirclePointRepresentation: """ This class represents a circle that indicate a point in the surface """ @@ -565,7 +565,7 @@ def GetRepresentation(self, x, y, z): return a -class CrossPointRepresentation(object): +class CrossPointRepresentation: """ This class represents a cross that indicate a point in the surface """ @@ -633,7 +633,7 @@ def GetRepresentation(self, x, y, z): return a -class LinearMeasure(object): +class LinearMeasure: def __init__(self, colour=(1, 0, 0), representation=None): self.colour = colour self.points = [] @@ -651,7 +651,7 @@ def IsComplete(self): """ Is this measure complete? """ - return not self.point_actor2 is None + return self.point_actor2 is not None def AddPoint(self, x, y, z): if not self.point_actor1: @@ -711,8 +711,8 @@ def _draw_line(self): def _draw_text(self): p1, p2 = self.points - text = " %.3f mm " % math.sqrt(vtkMath.Distance2BetweenPoints(p1, p2)) - x, y, z = [(i + j) / 2 for i, j in zip(p1, p2)] + text = f" {math.sqrt(vtkMath.Distance2BetweenPoints(p1, p2)):.3f} mm " + x, y, z = ((i + j) / 2 for i, j in zip(p1, p2)) textsource = vtkTextSource() textsource.SetText(text) textsource.SetBackgroundColor((250 / 255.0, 247 / 255.0, 218 / 255.0)) @@ -751,7 +751,7 @@ def draw_to_canvas(self, gc, canvas): r, g, b = self.colour canvas.draw_line(p0, p1, colour=(r * 255, g * 255, b * 255, 255)) - txt = "%.3f mm" % self.GetValue() + txt = f"{self.GetValue():.3f} mm" canvas.draw_text_box( txt, ( @@ -820,7 +820,7 @@ def __del__(self): self.Remove() -class AngularMeasure(object): +class AngularMeasure: def __init__(self, colour=(1, 0, 0), representation=None): self.colour = colour self.points = [] @@ -836,7 +836,7 @@ def __init__(self, colour=(1, 0, 0), representation=None): self.representation = representation def IsComplete(self): - return not self.point_actor3 is None + return self.point_actor3 is not None def AddPoint(self, x, y, z): if not self.point_actor1: @@ -943,11 +943,11 @@ def DrawArc(self): if d1 < d2: d = d1 p1 = self.points[0] - a, b, c = [j - i for i, j in zip(self.points[1], self.points[2])] + a, b, c = (j - i for i, j in zip(self.points[1], self.points[2])) else: d = d2 p1 = self.points[2] - a, b, c = [j - i for i, j in zip(self.points[1], self.points[0])] + a, b, c = (j - i for i, j in zip(self.points[1], self.points[0])) t = d / math.sqrt(a**2 + b**2 + c**2) x = self.points[1][0] + a * t @@ -963,7 +963,7 @@ def DrawArc(self): return arc def _draw_text(self): - text = " %.3f " % self.CalculateAngle() + text = f" {self.CalculateAngle():.3f} " x, y, z = self.points[1] textsource = vtkTextSource() textsource.SetText(text) @@ -1003,7 +1003,7 @@ def draw_to_canvas(self, gc, canvas): canvas.draw_line(p0, p1, colour=(r * 255, g * 255, b * 255, 255)) if len(points) == 3: - txt = "%.3f° / %.3f°" % (self.GetValue(), 360.0 - self.GetValue()) + txt = f"{self.GetValue():.3f}° / {360.0 - self.GetValue():.3f}°" r, g, b = self.colour canvas.draw_arc( points[1], @@ -1102,7 +1102,7 @@ def __del__(self): class CircleDensityMeasure(CanvasHandlerBase): def __init__(self, orientation, slice_number, colour=(255, 0, 0, 255), interactive=True): - super(CircleDensityMeasure, self).__init__(None) + super().__init__(None) self.parent = None self.children = [] self.layer = 0 @@ -1217,7 +1217,7 @@ def _update_gui_info(self): colour=m.colour, location=self.orientation, type_=_("Density Ellipse"), - value="%.3f" % m.value, + value=f"{m.value:.3f}", ) def set_measurement(self, dm): @@ -1422,7 +1422,7 @@ def on_deselect(self, evt): class PolygonDensityMeasure(CanvasHandlerBase): def __init__(self, orientation, slice_number, colour=(255, 0, 0, 255), interactive=True): - super(PolygonDensityMeasure, self).__init__(None) + super().__init__(None) self.parent = None self.children = [] self.layer = 0 @@ -1723,5 +1723,5 @@ def _update_gui_info(self): colour=m.colour, location=self.orientation, type_=_("Density Polygon"), - value="%.3f" % m.value, + value=f"{m.value:.3f}", ) diff --git a/invesalius/data/orientation.py b/invesalius/data/orientation.py index d38904f02..4a86c27d1 100644 --- a/invesalius/data/orientation.py +++ b/invesalius/data/orientation.py @@ -21,7 +21,7 @@ SAGITAL = 0 -class Orientation(object): +class Orientation: def __init__(self, interactor, actor): self.interactor = interactor self.actor = actor @@ -41,7 +41,7 @@ def SetOrientation(self, orientation): cam.SetViewUp(0, 1, 0) xs = extent[1] - extent[0] + 1 - ys = extent[3] - extent[2] + 1 + # ys = extent[3] - extent[2] + 1 elif orientation == CORONAL: cam.SetFocalPoint(0, 0, 0) @@ -50,7 +50,7 @@ def SetOrientation(self, orientation): cam.SetViewUp(0, 0, 1) xs = extent[1] - extent[0] + 1 - ys = extent[5] - extent[4] + 1 + # ys = extent[5] - extent[4] + 1 elif orientation == SAGITAL: cam.SetFocalPoint(0, 0, 0) @@ -59,7 +59,7 @@ def SetOrientation(self, orientation): cam.SetViewUp(0, 0, 1) xs = extent[3] - extent[2] + 1 - ys = extent[5] - extent[4] + 1 + # ys = extent[5] - extent[4] + 1 if xs < 150: scale = 75 @@ -80,8 +80,8 @@ def SetOrientation(self, orientation): def UpdateDisplayExtent(self): extent = self.image.GetWholeExtent() if self.orientation == AXIAL: - xs = extent[1] - extent[0] + 1 - ys = extent[3] - extent[2] + 1 + # xs = extent[1] - extent[0] + 1 + # ys = extent[3] - extent[2] + 1 actor = self.actor actor.SetInput(self.image) @@ -90,8 +90,8 @@ def UpdateDisplayExtent(self): ) elif self.orientation == CORONAL: - xs = extent[1] - extent[0] + 1 - ys = extent[5] - extent[4] + 1 + # xs = extent[1] - extent[0] + 1 + # ys = extent[5] - extent[4] + 1 actor = self.actor actor.SetInput(self.image) @@ -100,8 +100,8 @@ def UpdateDisplayExtent(self): ) elif self.orientation == SAGITAL: - xs = extent[3] - extent[2] + 1 - ys = extent[5] - extent[4] + 1 + # xs = extent[3] - extent[2] + 1 + # ys = extent[5] - extent[4] + 1 actor = self.actor actor.SetInput(self.image) diff --git a/invesalius/data/ruler_volume.py b/invesalius/data/ruler_volume.py index ccd6fab63..ae66065a7 100644 --- a/invesalius/data/ruler_volume.py +++ b/invesalius/data/ruler_volume.py @@ -145,8 +145,8 @@ def GetVolumeSize(self): Returns: tuple: (image width in mm, image height in mm) """ - initial_orientation = (0, 0, 1) # up direction is z-axis - initial_rotational_axis = (0, 1, 0) # y-axis + # initial_orientation = (0, 0, 1) # up direction is z-axis + # initial_rotational_axis = (0, 1, 0) # y-axis bounds = self.viewer_volume.surface.GetBounds() bounds_matrix = np.abs( np.array([bounds[0] - bounds[1], bounds[2] - bounds[3], bounds[4] - bounds[5]]) diff --git a/invesalius/data/serial_port_connection.py b/invesalius/data/serial_port_connection.py index 3a54af285..47e2e457f 100644 --- a/invesalius/data/serial_port_connection.py +++ b/invesalius/data/serial_port_connection.py @@ -49,16 +49,16 @@ def Connect(self): import serial self.connection = serial.Serial(self.com_port, baudrate=self.baud_rate, timeout=0) - print("Connection to port {} opened.".format(self.com_port)) + print(f"Connection to port {self.com_port} opened.") Publisher.sendMessage("Serial port connection", state=True) - except: - print("Serial port init error: Connecting to port {} failed.".format(self.com_port)) + except Exception: + print(f"Serial port init error: Connecting to port {self.com_port} failed.") def Disconnect(self): if self.connection: self.connection.close() - print("Connection to port {} closed.".format(self.com_port)) + print(f"Connection to port {self.com_port} closed.") Publisher.sendMessage("Serial port connection", state=False) @@ -66,7 +66,7 @@ def SendPulse(self): try: self.connection.send_break(constants.PULSE_DURATION_IN_MILLISECONDS / 1000) Publisher.sendMessage("Serial port pulse triggered") - except: + except Exception: print("Error: Serial port could not be written into.") def run(self): @@ -76,7 +76,7 @@ def run(self): lines = self.connection.readlines() if lines: trigger_on = True - except: + except Exception: print("Error: Serial port could not be read.") if self.stylusplh: diff --git a/invesalius/data/slice_.py b/invesalius/data/slice_.py index aef2ef76a..bcf9fa4ea 100644 --- a/invesalius/data/slice_.py +++ b/invesalius/data/slice_.py @@ -42,6 +42,7 @@ import invesalius.utils as utils from invesalius.data import transformations from invesalius.data.mask import Mask +from invesalius.i18n import tr as _ from invesalius.project import Project from invesalius.pubsub import pub as Publisher from invesalius_cy import mips, transforms @@ -557,8 +558,8 @@ def edit_mask_pixel(self, operation, index, position, radius, orientation): py = position / mask.shape[1] px = position % mask.shape[1] elif orientation == "SAGITAL": - sx = self.spacing[2] - sy = self.spacing[1] + sx = self.spacing[2] # noqa: F841 + sy = self.spacing[1] # noqa: F841 py = position / mask.shape[1] px = position % mask.shape[1] @@ -1295,7 +1296,7 @@ def UpdateColourTableBackgroundWidget(self, nodes): def UpdateSlice3D(self, widget, orientation): img = self.buffer_slices[orientation].vtk_image - original_orientation = Project().original_orientation + # original_orientation = Project().original_orientation cast = vtkImageCast() cast.SetInputData(img) cast.SetOutputScalarTypeToDouble() @@ -1513,7 +1514,7 @@ def do_colour_image(self, imagedata): return img_colours_bg.GetOutput() def do_colour_mask(self, imagedata, opacity): - scalar_range = int(imagedata.GetScalarRange()[1]) + # scalar_range = int(imagedata.GetScalarRange()[1]) r, g, b = self.current_mask.colour[:3] # map scalar values into colors diff --git a/invesalius/data/slice_data.py b/invesalius/data/slice_data.py index 54332fbba..5cd99e9d8 100644 --- a/invesalius/data/slice_data.py +++ b/invesalius/data/slice_data.py @@ -29,7 +29,7 @@ BORDER_NONE = 0 -class SliceData(object): +class SliceData: def __init__(self): self.actor = None self.cursor = None diff --git a/invesalius/data/styles.py b/invesalius/data/styles.py index d3332cf39..bea2b77f6 100644 --- a/invesalius/data/styles.py +++ b/invesalius/data/styles.py @@ -294,7 +294,7 @@ def OnBIBrushClick(self, obj, evt): viewer = self.viewer iren = viewer.interactor - operation = self.config.operation + # operation = self.config.operation viewer._set_editor_cursor_visibility(1) @@ -341,7 +341,7 @@ def OnBIBrushMove(self, obj, evt): mouse_x, mouse_y = self.GetMousePosition() render = iren.FindPokedRenderer(mouse_x, mouse_y) slice_data = viewer.get_slice_data(render) - operation = self.config.operation + # operation = self.config.operation wx, wy, wz = viewer.get_coordinate_cursor(mouse_x, mouse_y, self.picker) slice_data.cursor.SetPosition((wx, wy, wz)) @@ -411,8 +411,8 @@ def edit_mask_pixel(self, fill_value, n, index, position, radius, orientation): py = position / matrix.shape[1] px = position % matrix.shape[1] elif orientation == "SAGITAL": - sx = spacing[2] - sy = spacing[1] + sx = spacing[2] # noqa: F841 + sy = spacing[1] # noqa: F841 py = position / matrix.shape[1] px = position % matrix.shape[1] @@ -679,7 +679,7 @@ def CleanUp(self): def OnWindowLevelMove(self, obj, evt): if self.left_pressed: - iren = obj.GetInteractor() + # iren = obj.GetInteractor() mouse_x, mouse_y = self.GetMousePosition() self.acum_achange_window += mouse_x - self.last_x self.acum_achange_level += mouse_y - self.last_y @@ -802,7 +802,7 @@ def OnInsertMeasurePoint(self, obj, evt): self.viewer.scroll_enabled = False else: if self.picker.GetViewProp(): - renderer = self.viewer.slice_data.renderer + # renderer = self.viewer.slice_data.renderer Publisher.sendMessage( "Add measurement point", position=(x, y, z), @@ -988,7 +988,7 @@ def _2d_to_3d(self, pos): return (x, y, z) def _pick_position(self): - iren = self.viewer.interactor + # iren = self.viewer.interactor mx, my = self.GetMousePosition() return (mx, my) @@ -1238,7 +1238,7 @@ def OnChangeSliceMove(self, evt, obj): max = self.viewer.slice_.GetMaxSliceNumber(self.viewer.orientation) position = self.viewer.interactor.GetLastEventPosition() - scroll_position = self.viewer.scroll.GetThumbPosition() + # scroll_position = self.viewer.scroll.GetThumbPosition() if (position[1] > self.last_position) and (self.acum_achange_slice > min): self.acum_achange_slice -= 1 @@ -1470,7 +1470,7 @@ def OnBrushRelease(self, evt, obj): def EOnScrollForward(self, evt, obj): iren = self.viewer.interactor - viewer = self.viewer + # viewer = self.viewer if iren.GetControlKey(): mouse_x, mouse_y = self.GetMousePosition() render = iren.FindPokedRenderer(mouse_x, mouse_y) @@ -1488,7 +1488,7 @@ def EOnScrollForward(self, evt, obj): def EOnScrollBackward(self, evt, obj): iren = self.viewer.interactor - viewer = self.viewer + # viewer = self.viewer if iren.GetControlKey(): mouse_x, mouse_y = self.GetMousePosition() render = iren.FindPokedRenderer(mouse_x, mouse_y) @@ -1505,7 +1505,7 @@ def EOnScrollBackward(self, evt, obj): self.OnScrollBackward(obj, evt) -class WatershedProgressWindow(object): +class WatershedProgressWindow: def __init__(self, process): self.process = process self.title = "InVesalius 3" @@ -1608,7 +1608,7 @@ def __init__(self, viewer): self.viewer.slice_data.cursor.Show(0) def SetUp(self): - mask = self.viewer.slice_.current_mask.matrix + # mask = self.viewer.slice_.current_mask.matrix self._create_mask() self.viewer.slice_.to_show_aux = "watershed" self.viewer.OnScrollBar() @@ -1694,7 +1694,7 @@ def OnLeaveInteractor(self, obj, evt): def WOnScrollBackward(self, obj, evt): iren = self.viewer.interactor - viewer = self.viewer + # viewer = self.viewer if iren.GetControlKey(): mouse_x, mouse_y = self.GetMousePosition() render = iren.FindPokedRenderer(mouse_x, mouse_y) @@ -1712,7 +1712,7 @@ def WOnScrollBackward(self, obj, evt): def WOnScrollForward(self, obj, evt): iren = self.viewer.interactor - viewer = self.viewer + # viewer = self.viewer if iren.GetControlKey(): mouse_x, mouse_y = self.GetMousePosition() render = iren.FindPokedRenderer(mouse_x, mouse_y) @@ -1765,12 +1765,12 @@ def OnBrushClick(self, obj, evt): n = self.viewer.slice_data.number self.edit_mask_pixel(operation, n, cursor.GetPixels(), position, radius, self.orientation) - if self.orientation == "AXIAL": - mask = self.matrix[n, :, :] - elif self.orientation == "CORONAL": - mask = self.matrix[:, n, :] - elif self.orientation == "SAGITAL": - mask = self.matrix[:, :, n] + # if self.orientation == "AXIAL": + # mask = self.matrix[n, :, :] + # elif self.orientation == "CORONAL": + # mask = self.matrix[:, n, :] + # elif self.orientation == "SAGITAL": + # mask = self.matrix[:, :, n] # TODO: To create a new function to reload images to viewer. viewer.OnScrollBar() @@ -1815,12 +1815,12 @@ def OnBrushMove(self, obj, evt): self.edit_mask_pixel( operation, n, cursor.GetPixels(), position, radius, self.orientation ) - if self.orientation == "AXIAL": - mask = self.matrix[n, :, :] - elif self.orientation == "CORONAL": - mask = self.matrix[:, n, :] - elif self.orientation == "SAGITAL": - mask = self.matrix[:, :, n] + # if self.orientation == "AXIAL": + # mask = self.matrix[n, :, :] + # elif self.orientation == "CORONAL": + # mask = self.matrix[:, n, :] + # elif self.orientation == "SAGITAL": + # mask = self.matrix[:, :, n] # TODO: To create a new function to reload images to viewer. viewer.OnScrollBar(update3D=False) @@ -1934,8 +1934,8 @@ def edit_mask_pixel(self, operation, n, index, position, radius, orientation): py = position / mask.shape[1] px = position % mask.shape[1] elif orientation == "SAGITAL": - sx = spacing[2] - sy = spacing[1] + sx = spacing[2] # noqa: F841 + sy = spacing[1] # noqa: F841 py = position / mask.shape[1] px = position % mask.shape[1] @@ -2149,7 +2149,7 @@ def OnMouseMove(self, obj, evt): self._rotate() else: # Getting mouse position - iren = self.viewer.interactor + # iren = self.viewer.interactor mx, my = self.GetMousePosition() # Getting center value @@ -2195,7 +2195,7 @@ def OnDblClick(self, evt): Publisher.sendMessage("Reload actual slice") def _move_center_rot(self): - iren = self.viewer.interactor + # iren = self.viewer.interactor mx, my = self.GetMousePosition() icx, icy, icz = self.viewer.slice_.center @@ -2216,7 +2216,7 @@ def _move_center_rot(self): def _rotate(self): # Getting mouse position - iren = self.viewer.interactor + # iren = self.viewer.interactor mx, my = self.GetMousePosition() cx, cy, cz = self.viewer.slice_.center @@ -2250,7 +2250,7 @@ def _rotate(self): self._discard_buffers() if self.viewer.slice_.current_mask: self.viewer.slice_.current_mask.clear_history() - Publisher.sendMessage("Reload actual slice %s" % self.viewer.orientation) + Publisher.sendMessage(f"Reload actual slice {self.viewer.orientation}") self.p0 = self.get_image_point_coord(x, y, z) def get_image_point_coord(self, x, y, z): @@ -2380,8 +2380,8 @@ def OnFFClick(self, obj, evt): if self.viewer.slice_.buffer_slices[self.orientation].mask is None: return - viewer = self.viewer - iren = viewer.interactor + # viewer = self.viewer + # iren = viewer.interactor mouse_x, mouse_y = self.GetMousePosition() x, y, z = self.viewer.get_voxel_coord_by_screen_pos(mouse_x, mouse_y, self.picker) @@ -2796,8 +2796,8 @@ def OnFFClick(self, obj, evt): Publisher.sendMessage("Reload actual slice") def do_2d_seg(self): - viewer = self.viewer - iren = viewer.interactor + # viewer = self.viewer + # iren = viewer.interactor mouse_x, mouse_y = self.GetMousePosition() x, y = self.viewer.get_slice_pixel_coord_by_screen_pos(mouse_x, mouse_y, self.picker) @@ -2865,8 +2865,8 @@ def do_2d_seg(self): self.viewer.slice_.current_mask.save_history(index, self.orientation, mask, b_mask) def do_3d_seg(self): - viewer = self.viewer - iren = viewer.interactor + # viewer = self.viewer + # iren = viewer.interactor mouse_x, mouse_y = self.GetMousePosition() x, y, z = self.viewer.get_voxel_coord_by_screen_pos(mouse_x, mouse_y, self.picker) diff --git a/invesalius/data/styles_3d.py b/invesalius/data/styles_3d.py index 3205bc884..5117430df 100644 --- a/invesalius/data/styles_3d.py +++ b/invesalius/data/styles_3d.py @@ -17,7 +17,6 @@ # detalhes. # -------------------------------------------------------------------------- -import time import wx from vtkmodules.vtkInteractionStyle import ( diff --git a/invesalius/data/surface.py b/invesalius/data/surface.py index 0ec5e4bb7..a3670ff52 100644 --- a/invesalius/data/surface.py +++ b/invesalius/data/surface.py @@ -27,15 +27,8 @@ import tempfile import time import traceback -import weakref import numpy as np - -try: - import queue -except ImportError: - import Queue as queue - import wx import wx.lib.agw.genericmessagedialog as GMD from vtkmodules.vtkCommonCore import ( @@ -80,7 +73,6 @@ from invesalius.data.converters import convert_custom_bin_to_vtk from invesalius.gui import dialogs from invesalius.i18n import tr as _ -from invesalius_cy import cy_mesh # TODO: Verificar ReleaseDataFlagOn and SetSource @@ -424,7 +416,7 @@ def OnImportJsonConfig(self, filename, convert_to_inv): create_meshes_flag = False self.convert_to_inv = convert_to_inv scalp_index = None - with open(filename, "r") as config_file: + with open(filename) as config_file: config_dict = json.load(config_file) cortex = config_dict["path_meshes"] + config_dict["cortex"] bmeshes = config_dict["bmeshes"] @@ -983,7 +975,7 @@ def AddNewActor(self, slice_, mask, surface_parameters): try: surface_filename, surface_measures = f.get() - except Exception as e: + except Exception: print(_("InVesalius was not able to create the surface")) print(traceback.print_exc()) return @@ -1084,12 +1076,12 @@ def AddNewActor(self, slice_, mask, surface_parameters): try: msg = msg_queue.get_nowait() sp.Update(msg) - except: + except Exception: sp.Update(None) wx.Yield() t_end = time.time() - print("Elapsed time - {}".format(t_end - t_init)) + print(f"Elapsed time - {t_end - t_init}") sp.Close() if sp.error: dlg = GMD.GenericMessageDialog(None, sp.error, "Exception!", wx.OK | wx.ICON_ERROR) @@ -1201,18 +1193,14 @@ def OnExportSurface(self, filename, filetype, convert_to_world=False): if wx.GetApp() is None: print( _( - "It was not possible to export the surface because you don't have permission to write to {} folder: {}".format( - dirpath, err - ) + f"It was not possible to export the surface because you don't have permission to write to {dirpath} folder: {err}" ) ) else: dlg = dialogs.ErrorMessageBox( None, _("Export surface error"), - "It was not possible to export the surface because you don't have permission to write to {}:\n{}".format( - dirpath, err - ), + f"It was not possible to export the surface because you don't have permission to write to {dirpath}:\n{err}", ) dlg.ShowModal() dlg.Destroy() diff --git a/invesalius/data/surface_process.py b/invesalius/data/surface_process.py index 14f61331d..d18bed0e5 100644 --- a/invesalius/data/surface_process.py +++ b/invesalius/data/surface_process.py @@ -1,6 +1,5 @@ import os import tempfile -import weakref try: import queue @@ -24,7 +23,6 @@ from vtkmodules.vtkIOXML import vtkXMLPolyDataReader, vtkXMLPolyDataWriter import invesalius.data.converters as converters -from invesalius.i18n import tr as _ from invesalius_cy import cy_mesh @@ -37,7 +35,7 @@ def ResampleImage3D(imagedata, value): extent = imagedata.GetExtent() size = imagedata.GetDimensions() - width = float(size[0]) + # width = float(size[0]) height = float(size[1] / value) resolution = (height / (extent[1] - extent[0]) + 1) * spacing[1] @@ -53,12 +51,12 @@ def ResampleImage3D(imagedata, value): def pad_image(image, pad_value, pad_bottom, pad_top): dz, dy, dx = image.shape z_iadd = 0 - z_eadd = 0 + # z_eadd = 0 if pad_bottom: z_iadd = 1 dz += 1 if pad_top: - z_eadd = 1 + # z_eadd = 1 dz += 1 new_shape = dz, dy + 2, dx + 2 @@ -247,7 +245,7 @@ def send_message(msg): clean = vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() - clean_ref = weakref.ref(clean) + # clean_ref = weakref.ref(clean) # clean_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) @@ -262,7 +260,7 @@ def send_message(msg): if algorithm == "ca_smoothing": send_message("Calculating normals ...") normals = vtkPolyDataNormals() - normals_ref = weakref.ref(normals) + # normals_ref = weakref.ref(normals) # normals_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) @@ -280,7 +278,7 @@ def send_message(msg): clean = vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() - clean_ref = weakref.ref(clean) + # clean_ref = weakref.ref(clean) # clean_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) @@ -343,7 +341,7 @@ def send_message(msg): # decimation.ReleaseDataFlagOn() decimation.SetInputData(polydata) decimation.SetTargetReduction(decimate_reduction) - decimation_ref = weakref.ref(decimation) + # decimation_ref = weakref.ref(decimation) # decimation_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(decimation_ref(), _("Creating 3D surface..."))) # decimation.PreserveTopologyOn() @@ -365,7 +363,7 @@ def send_message(msg): conn = vtkPolyDataConnectivityFilter() conn.SetInputData(polydata) conn.SetExtractionModeToLargestRegion() - conn_ref = weakref.ref(conn) + # conn_ref = weakref.ref(conn) # conn_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(conn_ref(), _("Creating 3D surface..."))) conn.Update() @@ -385,7 +383,7 @@ def send_message(msg): # filled_polydata.ReleaseDataFlagOn() filled_polydata.SetInputData(polydata) filled_polydata.SetHoleSize(300) - filled_polydata_ref = weakref.ref(filled_polydata) + # filled_polydata_ref = weakref.ref(filled_polydata) # filled_polydata_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(filled_polydata_ref(), _("Creating 3D surface..."))) filled_polydata.Update() diff --git a/invesalius/data/tracker_connection.py b/invesalius/data/tracker_connection.py index 107de8210..f1270ca67 100644 --- a/invesalius/data/tracker_connection.py +++ b/invesalius/data/tracker_connection.py @@ -23,7 +23,6 @@ import invesalius.constants as const import invesalius.gui.dialogs as dlg from invesalius import inv_paths -from invesalius.pubsub import pub as Publisher # TODO: Disconnect tracker when a new one is connected # TODO: Test if there are too many prints when connection fails @@ -48,7 +47,7 @@ def Disconnect(self): self.connection = False self.lib_mode = "wrapper" print("Tracker disconnected.") - except: + except Exception: self.connection = True self.lib_mode = "error" print("The tracker could not be disconnected.") @@ -173,7 +172,7 @@ def __init__(self, model=None): "fastrak", "isotrak", "patriot", - ], "Unsupported model for Polhemus tracker: {}".format(model) + ], f"Unsupported model for Polhemus tracker: {model}" super().__init__(model) @@ -223,7 +222,7 @@ def Connect(self, reconfigure): self.ConfigureCOMPort() connection = self.PolhemusSerialConnection() lib_mode = "serial" - except: + except Exception: lib_mode = "error" print("Could not connect to Polhemus by any method.") @@ -255,7 +254,7 @@ def PolhemusWrapperConnection(self): print( "Could not connect to Polhemus via wrapper without error: Initialize is False." ) - except: + except Exception: connection = None print("Could not connect to Polhemus via wrapper without error: Import failed.") @@ -292,7 +291,7 @@ def PolhemusSerialConnection(self): connection = None print("Could not connect to Polhemus serial without error.") - except: + except Exception: connection = None print("Could not connect to Polhemus tracker.") @@ -333,7 +332,7 @@ def PolhemusUSBConnection(self): connection = None print("Could not connect to Polhemus USB without error.") - except: + except Exception: print("Could not connect to Polhemus USB with error.") return connection @@ -349,7 +348,7 @@ def Disconnect(self): self.connection = False print("Tracker disconnected.") - except: + except Exception: self.connection = True self.lib_mode = "error" print("The tracker could not be disconnected.") @@ -373,7 +372,7 @@ def Connect(self): lib_mode = "wrapper" self.connection = connection - except: + except Exception: print("Could not connect to camera tracker.") lib_mode = "error" @@ -436,7 +435,7 @@ def Connect(self): print("Connected to polaris tracking device.") self.connection = connection - except: + except Exception: lib_mode = "error" connection = None print("Could not connect to polaris tracker.") @@ -495,7 +494,7 @@ def Connect(self): else: print("Connect to Polaris P4 tracking device.") - except: + except Exception: lib_mode = "error" connection = None print("Could not connect to Polaris P4 tracker.") diff --git a/invesalius/data/tractography.py b/invesalius/data/tractography.py index de97bea72..b8fe4e5b8 100644 --- a/invesalius/data/tractography.py +++ b/invesalius/data/tractography.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer @@ -61,7 +59,7 @@ def compute_directions(trk_n, alpha=255): trk_d[-1, :] *= -1 # check that linalg norm makes second norm # https://stackoverflow.com/questions/21030391/how-to-normalize-an-array-in-numpy - direction = 255 * np.absolute((trk_d / np.linalg.norm(trk_d, axis=1)[:, None])) + direction = 255 * np.absolute(trk_d / np.linalg.norm(trk_d, axis=1)[:, None]) direction = np.hstack([direction, alpha * np.ones([direction.shape[0], 1])]) return direction.astype(int) diff --git a/invesalius/data/transformations.py b/invesalius/data/transformations.py index b50ecb1ea..24d5aecea 100644 --- a/invesalius/data/transformations.py +++ b/invesalius/data/transformations.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # transformations.py # Copyright (c) 2006-2015, Christoph Gohlke @@ -193,10 +192,8 @@ """ -from __future__ import division, print_function - import math -from typing import Any, Sequence, Union +from typing import Sequence, Union import numpy import numpy.typing @@ -703,7 +700,7 @@ def shear_from_matrix(matrix): w, V = numpy.linalg.eig(M33) i = numpy.where(abs(numpy.real(w) - 1.0) < 1e-4)[0] if len(i) < 2: - raise ValueError("no two linear independent eigenvectors found %s" % w) + raise ValueError(f"no two linear independent eigenvectors found {w}") V = numpy.real(V[:, i]).squeeze().T lenorm = -1.0 for i0, i1 in ((0, 1), (0, 2), (1, 2)): @@ -1530,7 +1527,7 @@ def random_rotation_matrix(rand=None): return quaternion_matrix(random_quaternion(rand)) -class Arcball(object): +class Arcball: """Virtual Trackball Control. >>> ball = Arcball() @@ -1940,7 +1937,7 @@ def _import_module(name, package=None, warn=True, prefix="_py_", ignore="_"): module = import_module("." + name, package=package) except ImportError: if warn: - warnings.warn("failed to import module %s" % name) + warnings.warn(f"failed to import module {name}") else: for attr in dir(module): if ignore and attr.startswith(ignore): @@ -1958,7 +1955,7 @@ def _import_module(name, package=None, warn=True, prefix="_py_", ignore="_"): if __name__ == "__main__": import doctest - import random # used in doctests + import random # used in doctests # noqa: F401 numpy.set_printoptions(suppress=True, precision=5) doctest.testmod() diff --git a/invesalius/data/viewer_slice.py b/invesalius/data/viewer_slice.py index 990f23cc8..214171784 100644 --- a/invesalius/data/viewer_slice.py +++ b/invesalius/data/viewer_slice.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer @@ -19,12 +18,9 @@ # -------------------------------------------------------------------------- import collections -import itertools import os import sys -import tempfile -import numpy as np import wx from vtkmodules.vtkFiltersGeneral import vtkCursor3D from vtkmodules.vtkFiltersHybrid import vtkRenderLargeImage @@ -50,7 +46,6 @@ from vtkmodules.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor import invesalius.constants as const -import invesalius.data.converters as converters import invesalius.data.cursor_actors as ca import invesalius.data.measures as measures import invesalius.data.slice_ as sl @@ -171,15 +166,15 @@ def __init__(self, prnt, orientation): def OnSetMIPSize(self, number_slices): val = self.mip_size_spin.GetValue() - Publisher.sendMessage("Set MIP size %s" % self.orientation, number_slices=val) + Publisher.sendMessage(f"Set MIP size {self.orientation}", number_slices=val) def OnSetMIPBorder(self, evt): val = self.border_spin.GetValue() - Publisher.sendMessage("Set MIP border %s" % self.orientation, border_size=val) + Publisher.sendMessage(f"Set MIP border {self.orientation}", border_size=val) def OnCheckInverted(self, evt): val = self.inverted.GetValue() - Publisher.sendMessage("Set MIP Invert %s" % self.orientation, invert=val) + Publisher.sendMessage(f"Set MIP Invert {self.orientation}", invert=val) def _set_projection_type(self, projection_id): if projection_id in (const.PROJECTION_MIDA, const.PROJECTION_CONTOUR_MIDA): @@ -583,7 +578,7 @@ def Reposition(self, slice_data): vtk 5.4.3 """ ren = slice_data.renderer - size = ren.GetSize() + # size = ren.GetSize() ren.ResetCamera() ren.GetActiveCamera().Zoom(1.0) @@ -871,7 +866,7 @@ def get_coord_inside_volume(self, mx, my, picker=None): picker = self.pick slice_data = self.slice_data - renderer = slice_data.renderer + # renderer = slice_data.renderer coord = self.get_coordinate_cursor(picker) position = slice_data.actor.GetInput().FindPoint(coord) @@ -885,9 +880,9 @@ def __bind_events(self): Publisher.subscribe(self.LoadImagedata, "Load slice to viewer") Publisher.subscribe(self.SetBrushColour, "Change mask colour") Publisher.subscribe(self.UpdateRender, "Update slice viewer") - Publisher.subscribe(self.UpdateRender, "Update slice viewer %s" % self.orientation) + Publisher.subscribe(self.UpdateRender, f"Update slice viewer {self.orientation}") Publisher.subscribe(self.UpdateCanvas, "Redraw canvas") - Publisher.subscribe(self.UpdateCanvas, "Redraw canvas %s" % self.orientation) + Publisher.subscribe(self.UpdateCanvas, f"Redraw canvas {self.orientation}") Publisher.subscribe(self.ChangeSliceNumber, ("Set scroll position", self.orientation)) # Publisher.subscribe(self.__update_cross_position, # 'Update cross position') @@ -927,13 +922,13 @@ def __bind_events(self): Publisher.subscribe(self.OnSwapVolumeAxes, "Swap volume axes") Publisher.subscribe(self.ReloadActualSlice, "Reload actual slice") - Publisher.subscribe(self.ReloadActualSlice, "Reload actual slice %s" % self.orientation) + Publisher.subscribe(self.ReloadActualSlice, f"Reload actual slice {self.orientation}") Publisher.subscribe(self.OnUpdateScroll, "Update scroll") # MIP - Publisher.subscribe(self.OnSetMIPSize, "Set MIP size %s" % self.orientation) - Publisher.subscribe(self.OnSetMIPBorder, "Set MIP border %s" % self.orientation) - Publisher.subscribe(self.OnSetMIPInvert, "Set MIP Invert %s" % self.orientation) + Publisher.subscribe(self.OnSetMIPSize, f"Set MIP size {self.orientation}") + Publisher.subscribe(self.OnSetMIPBorder, f"Set MIP border {self.orientation}") + Publisher.subscribe(self.OnSetMIPInvert, f"Set MIP Invert {self.orientation}") Publisher.subscribe(self.OnShowMIPInterface, "Show MIP interface") Publisher.subscribe(self.OnSetOverwriteMask, "Set overwrite mask") @@ -1016,7 +1011,7 @@ def _export_picture(self, id, filename, filetype): writer = vtkPostScriptWriter() elif filetype == const.FILETYPE_TIF: writer = vtkTIFFWriter() - filename = "%s.tif" % filename.strip(".tif") + filename = "{}.tif".format(filename.strip(".tif")) writer.SetInputData(image) writer.SetFileName(filename.encode(const.FS_ENCODE)) @@ -1274,7 +1269,7 @@ def create_slice_window(self): return slice_data def UpdateInterpolatedSlice(self): - if self.slice_actor != None: + if self.slice_actor is not None: session = ses.Session() if session.GetConfig("slice_interpolation"): self.slice_actor.InterpolateOff() @@ -1285,8 +1280,8 @@ def UpdateInterpolatedSlice(self): def SetInterpolatedSlices(self, flag): self.interpolation_slice_status = flag - if self.slice_actor != None: - if self.interpolation_slice_status == True: + if self.slice_actor is not None: + if self.interpolation_slice_status is True: self.slice_actor.InterpolateOn() else: self.slice_actor.InterpolateOff() @@ -1294,7 +1289,7 @@ def SetInterpolatedSlices(self, flag): self.UpdateRender() def __update_camera(self): - orientation = self.orientation + # orientation = self.orientation proj = project.Project() orig_orien = proj.original_orientation @@ -1369,7 +1364,7 @@ def set_scroll_position(self, position): self.OnScrollBar() def UpdateSlice3D(self, pos): - original_orientation = project.Project().original_orientation + # original_orientation = project.Project().original_orientation pos = self.scroll.GetThumbPosition() Publisher.sendMessage( "Change slice from slice plane", orientation=self.orientation, index=pos @@ -1398,7 +1393,7 @@ def OnScrollBar(self, evt=None, update3D=True): evt.Skip() def OnScrollBarRelease(self, evt): - pos = self.scroll.GetThumbPosition() + # pos = self.scroll.GetThumbPosition() evt.Skip() def OnKeyDown(self, evt=None, obj=None): diff --git a/invesalius/data/viewer_volume.py b/invesalius/data/viewer_volume.py index 4643683cf..60a204388 100644 --- a/invesalius/data/viewer_volume.py +++ b/invesalius/data/viewer_volume.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -import math - # -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer @@ -22,7 +19,6 @@ # from math import cos, sin import os import queue -import random import sys import numpy as np @@ -33,31 +29,24 @@ from vtkmodules.vtkCommonColor import vtkColorSeries, vtkNamedColors # TODO: Check that these imports are not used -- vtkLookupTable, vtkMinimalStandardRandomSequence, vtkPoints, vtkUnsignedCharArray -from vtkmodules.vtkCommonComputationalGeometry import vtkParametricTorus from vtkmodules.vtkCommonCore import ( mutable, vtkDoubleArray, vtkIdList, vtkLookupTable, - vtkMath, vtkPoints, vtkUnsignedCharArray, ) from vtkmodules.vtkCommonDataModel import ( - vtkCellLocator, vtkPolyData, ) from vtkmodules.vtkCommonMath import vtkMatrix4x4 from vtkmodules.vtkCommonTransforms import vtkTransform from vtkmodules.vtkFiltersCore import vtkCenterOfMass, vtkGlyph3D, vtkPolyDataNormals -from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter from vtkmodules.vtkFiltersHybrid import vtkRenderLargeImage from vtkmodules.vtkFiltersModeling import vtkBandedPolyDataContourFilter from vtkmodules.vtkFiltersSources import ( vtkArrowSource, - vtkDiskSource, - vtkLineSource, - vtkParametricFunctionSource, vtkSphereSource, ) from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera @@ -81,7 +70,7 @@ vtkPostScriptWriter, vtkTIFFWriter, ) -from vtkmodules.vtkRenderingAnnotation import vtkAnnotatedCubeActor, vtkAxesActor, vtkScalarBarActor +from vtkmodules.vtkRenderingAnnotation import vtkAnnotatedCubeActor, vtkAxesActor from vtkmodules.vtkRenderingCore import ( vtkActor, vtkPointPicker, @@ -97,7 +86,6 @@ import invesalius.constants as const import invesalius.data.coordinates as dco import invesalius.data.coregistration as dcr -import invesalius.data.slice_ as sl import invesalius.data.styles_3d as styles import invesalius.data.transformations as tr import invesalius.data.vtk_utils as vtku @@ -107,7 +95,6 @@ import invesalius.utils as utils from invesalius import inv_paths from invesalius.data.actor_factory import ActorFactory -from invesalius.data.markers.marker import Marker, MarkerType from invesalius.data.markers.surface_geometry import SurfaceGeometry from invesalius.data.ruler_volume import GenericLeftRulerVolume from invesalius.data.visualization.coil_visualizer import CoilVisualizer @@ -768,7 +755,7 @@ def _export_picture(self, id, filename, filetype): writer = vtkPostScriptWriter() elif filetype == const.FILETYPE_TIF: writer = vtkTIFFWriter() - filename = "%s.tif" % filename.strip(".tif") + filename = "{}.tif".format(filename.strip(".tif")) writer.SetInputData(image) writer.SetFileName(filename.encode(const.FS_ENCODE)) @@ -1049,13 +1036,13 @@ def SetTargetMode(self, enabled=False): self.DisableTargetMode() def OnUpdateCoilPose(self, m_img, coord): - vtk_colors = vtkNamedColors() + # vtk_colors = vtkNamedColors() if self.target_coord and self.target_mode: distance_to_target = distance.euclidean( coord[0:3], (self.target_coord[0], -self.target_coord[1], self.target_coord[2]) ) - formatted_distance = "Distance: {: >5.1f} mm".format(distance_to_target) + formatted_distance = f"Distance: {distance_to_target: >5.1f} mm" if self.distance_text is not None: self.distance_text.SetValue(formatted_distance) @@ -1235,7 +1222,7 @@ def OnSetTarget(self, marker): self.coil_visualizer.AddTargetCoil(self.m_target) - print("Target updated to coordinates {}".format(coord)) + print(f"Target updated to coordinates {coord}") def CreateVTKObjectMatrix(self, direction, orientation): m_img = dco.coordinates_to_transformation_matrix( @@ -1297,7 +1284,7 @@ def Plane(self, x0, pTarget): v2 = v2 / np.linalg.norm(v2) # unit vector v1 = np.cross(v3, v2) v1 = v1 / np.linalg.norm(v1) # unit vector - x2 = x0 + v1 + # x2 = x0 + v1 # calculates the matrix for the change of coordinate systems (from canonical to the plane's). # remember that, in np.dot(M,p), even though p is a line vector (e.g.,np.array([1,2,3])), it is treated as a column for the dot multiplication. M_plane_inv = np.array( @@ -1504,12 +1491,8 @@ def AddCortexMarkerActor(self, position_orientation, marker_id): proj = prj.Project() timestamp = time.localtime(time.time()) - stamp_date = "{:0>4d}{:0>2d}{:0>2d}".format( - timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday - ) - stamp_time = "{:0>2d}{:0>2d}{:0>2d}".format( - timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec - ) + stamp_date = f"{timestamp.tm_year:0>4d}{timestamp.tm_mon:0>2d}{timestamp.tm_mday:0>2d}" + stamp_time = f"{timestamp.tm_hour:0>2d}{timestamp.tm_min:0>2d}{timestamp.tm_sec:0>2d}" sep = "-" if self.path_meshes is None: @@ -1567,7 +1550,7 @@ def CreateEfieldSpreadLegend(self): def CalculateDistanceMaxEfieldCoGE(self): self.distance_efield = distance.euclidean(self.center_gravity_position, self.position_max) self.SpreadEfieldFactorTextActor.SetValue( - "Spread distance: " + str("{:04.2f}".format(self.distance_efield)) + "Spread distance: " + str(f"{self.distance_efield:04.2f}") ) def EfieldVectors(self): @@ -1710,7 +1693,7 @@ def find_and_extract_data(self, csv_filename, target_numbers): matching_rows = [] - with open(csv_filename, "r") as csvfile: + with open(csv_filename) as csvfile: csv_reader = csv.reader(csvfile) for row in csv_reader: # Extract the first three numbers from the current row @@ -1984,16 +1967,14 @@ def SetEfieldTargetAtCortex(self, position, orientation): def ShowEfieldAtCortexTarget(self): if self.target_at_cortex is not None: - import vtk - index = self.efield_mesh.FindPoint(self.target_at_cortex) if index in self.Id_list: cell_number = self.Id_list.index(index) self.EfieldAtTargetLegend.SetValue( - "Efield at Target: " + str("{:04.2f}".format(self.e_field_norms[cell_number])) + "Efield at Target: " + str(f"{self.e_field_norms[cell_number]:04.2f}") ) else: - self.EfieldAtTargetLegend.SetValue("Efield at Target: " + str("{:04.2f}".format(0))) + self.EfieldAtTargetLegend.SetValue("Efield at Target: " + str(f"{0:04.2f}")) def CreateEfieldAtTargetLegend(self): if self.EfieldAtTargetLegend is not None: @@ -2082,9 +2063,9 @@ def ShowEfieldintheintersection(self, intersectingCellIds, p1, coil_norm, coil_d distance = np.linalg.norm(point - p1) if distance < closestDist: closestDist = distance - closestPoint = point - pointnormal = np.array(self.e_field_mesh_normals.GetTuple(cellId)) - angle = np.rad2deg(np.arccos(np.dot(pointnormal, coil_norm))) + # closestPoint = point + # pointnormal = np.array(self.e_field_mesh_normals.GetTuple(cellId)) + # angle = np.rad2deg(np.arccos(np.dot(pointnormal, coil_norm))) self.FindPointsAroundRadiusEfield(cellId) self.radius_list.Sort() else: @@ -2143,7 +2124,7 @@ def UpdateEfieldPointLocation(self, m_img, coord, queue_IDs): self.e_field_IDs_queue = queue_IDs if self.radius_list.GetNumberOfIds() != 0: if np.all(self.old_coord != coord): - self.e_field_IDs_queue.put_nowait((self.radius_list)) + self.e_field_IDs_queue.put_nowait(self.radius_list) self.old_coord = np.array([coord]) except queue.Full: pass @@ -2215,11 +2196,11 @@ def GetEnorm(self, enorm_data, plot_vector): proj = prj.Project() timestamp = time.localtime(time.time()) - stamp_date = "{:0>4d}{:0>2d}{:0>2d}".format( - timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday + stamp_date = ( + f"{timestamp.tm_year:0>4d}{timestamp.tm_mon:0>2d}{timestamp.tm_mday:0>2d}" ) - stamp_time = "{:0>2d}{:0>2d}{:0>2d}".format( - timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec + stamp_time = ( + f"{timestamp.tm_hour:0>2d}{timestamp.tm_min:0>2d}{timestamp.tm_sec:0>2d}" ) sep = "-" @@ -2331,8 +2312,6 @@ def SaveEfieldData(self, filename, plot_efield_vectors, marker_id): def SavedAllEfieldData(self, filename): import csv - import invesalius.data.imagedata_utils as imagedata_utils - header = [ "Marker ID", "Enorm cell indexes", @@ -2355,14 +2334,14 @@ def SavedAllEfieldData(self, filename): writer.writerows(all_data) def GetCellIntersection(self, p1, p2, locator): - vtk_colors = vtkNamedColors() + # vtk_colors = vtkNamedColors() # This find store the triangles that intersect the coil's normal intersectingCellIds = vtkIdList() locator.FindCellsAlongLine(p1, p2, 0.001, intersectingCellIds) return intersectingCellIds def ShowCoilProjection(self, intersectingCellIds, p1, coil_norm, coil_dir): - vtk_colors = vtkNamedColors() + # vtk_colors = vtkNamedColors() closestDist = 50 # If intersection is was found, calculate angle and add actors. @@ -2817,8 +2796,8 @@ def SetViewAngle(self, view): cam = self.ren.GetActiveCamera() cam.SetFocalPoint(0, 0, 0) - proj = prj.Project() - orig_orien = proj.original_orientation + # proj = prj.Project() + # orig_orien = proj.original_orientation xv, yv, zv = const.VOLUME_POSITION[const.AXIAL][0][view] xp, yp, zp = const.VOLUME_POSITION[const.AXIAL][1][view] diff --git a/invesalius/data/visualization/coil_visualizer.py b/invesalius/data/visualization/coil_visualizer.py index 3a9504ea0..f1dd39aad 100644 --- a/invesalius/data/visualization/coil_visualizer.py +++ b/invesalius/data/visualization/coil_visualizer.py @@ -3,7 +3,6 @@ import vtk import invesalius.constants as const -import invesalius.data.coordinates as dco import invesalius.data.polydata_utils as pu import invesalius.data.vtk_utils as vtku import invesalius.session as ses diff --git a/invesalius/data/visualization/marker_visualizer.py b/invesalius/data/visualization/marker_visualizer.py index 05fe01207..0d56755a1 100644 --- a/invesalius/data/visualization/marker_visualizer.py +++ b/invesalius/data/visualization/marker_visualizer.py @@ -1,8 +1,7 @@ import vtk -import invesalius.constants as const import invesalius.data.coordinates as dco -from invesalius.data.markers.marker import Marker, MarkerType +from invesalius.data.markers.marker import MarkerType from invesalius.pubsub import pub as Publisher @@ -352,7 +351,7 @@ def SetCoilAtTarget(self, state): actor = marker.visualization["actor"] highlighted = marker.visualization["highlighted"] - vtk_colors = vtk.vtkNamedColors() + # vtk_colors = vtk.vtkNamedColors() if state: # Change the color of the marker. actor.GetProperty().SetColor(self.COIL_AT_TARGET_COLOR) diff --git a/invesalius/data/visualization/vector_field_visualizer.py b/invesalius/data/visualization/vector_field_visualizer.py index 5c8596a14..34f22a682 100644 --- a/invesalius/data/visualization/vector_field_visualizer.py +++ b/invesalius/data/visualization/vector_field_visualizer.py @@ -1,10 +1,5 @@ import vtk -import invesalius.constants as const -import invesalius.data.coordinates as dco -import invesalius.data.polydata_utils as pu -import invesalius.data.vtk_utils as vtku -import invesalius.session as ses from invesalius.pubsub import pub as Publisher diff --git a/invesalius/data/volume.py b/invesalius/data/volume.py index df7b28262..39e89da56 100644 --- a/invesalius/data/volume.py +++ b/invesalius/data/volume.py @@ -20,8 +20,6 @@ import plistlib import weakref -import numpy -import wx from packaging.version import Version from vtkmodules.util import numpy_support from vtkmodules.vtkCommonCore import vtkVersion @@ -359,8 +357,8 @@ def Create16bColorTable(self, scale): curve_table = self.config["16bitClutCurves"] color_table = self.config["16bitClutColors"] colors = [] - for i, l in enumerate(curve_table): - for j, lopacity in enumerate(l): + for i, element in enumerate(curve_table): + for j, lopacity in enumerate(element): gray_level = lopacity["x"] r = color_table[i][j]["red"] g = color_table[i][j]["green"] @@ -415,16 +413,16 @@ def CreateOpacityTable(self, scale): self.ww = ww self.wl = wl - l1 = wl - ww / 2.0 - l2 = wl + ww / 2.0 + # l1 = wl - ww / 2.0 + # l2 = wl + ww / 2.0 - k1 = 0.0 - k2 = 1.0 + # k1 = 0.0 + # k2 = 1.0 opacity_transfer_func.AddSegment(0, 0, 2**16 - 1, 0) - for i, l in enumerate(curve_table): - for j, lopacity in enumerate(l): + for i, element in enumerate(curve_table): + for j, lopacity in enumerate(element): gray_level = lopacity["x"] # if gray_level <= l1: # opacity = k1 @@ -442,7 +440,6 @@ def Create8bOpacityTable(self, scale): else: opacity_transfer_func = vtkPiecewiseFunction() opacity_transfer_func.RemoveAllPoints() - opacities = [] ww = self.config["ww"] wl = self.TranslateScale(scale, self.config["wl"]) @@ -456,8 +453,8 @@ def Create8bOpacityTable(self, scale): opacity_transfer_func.RemoveAllPoints() opacity_transfer_func.AddSegment(0, 0, 2**16 - 1, 0) - k1 = 0.0 - k2 = 1.0 + # k1 = 0.0 + # k2 = 1.0 opacity_transfer_func.AddPoint(l1, 0) opacity_transfer_func.AddPoint(l2, 1) @@ -479,32 +476,6 @@ def ChangeBackgroundColour(self, colour): self.config["backgroundColorGreenComponent"] = colour[1] * 255 self.config["backgroundColorBlueComponent"] = colour[2] * 255 - def BuildTable(): - curve_table = p["16bitClutCurves"] - color_background = ( - p["backgroundColorRedComponent"], - p["backgroundColorGreenComponent"], - p["backgroundColorBlueComponent"], - ) - color_background = [i for i in color_background] - opacities = [] - colors = [] - - for i, l in enumerate(curve_table): - for j, lopacity in enumerate(l): - gray_level = lopacity["x"] - opacity = lopacity["y"] - - opacities.append((gray_level, opacity)) - - r = color_table[i][j]["red"] - g = color_table[i][j]["green"] - b = color_table[i][j]["blue"] - - colors.append((gray_level, r, g, b)) - - return colors, opacities, color_background, p["useShading"] - def SetShading(self): if self.config["useShading"]: self.volume_properties.ShadeOn() @@ -527,9 +498,9 @@ def SetTypeRaycasting(self): self.volume_mapper.SetBlendModeToComposite() else: if self.config.get("MIP", False): - raycasting_function = vtkVolumeRayCastMIPFunction() + raycasting_function = vtkVolumeRayCastMIPFunction() # noqa: F821 else: - raycasting_function = vtkVolumeRayCastCompositeFunction() + raycasting_function = vtkVolumeRayCastCompositeFunction() # noqa: F821 raycasting_function.SetCompositeMethodToInterpolateFirst() session = ses.Session() @@ -571,7 +542,6 @@ def LoadImage(self): self.image = image def LoadVolume(self): - proj = prj.Project() # image = imagedata_utils.to_vtk(n_array, spacing, slice_number, orientation) if not self.loaded_image: @@ -582,10 +552,10 @@ def LoadVolume(self): number_filters = len(self.config["convolutionFilters"]) - if prj.Project().original_orientation == const.AXIAL: - flip_image = True - else: - flip_image = False + # if prj.Project().original_orientation == const.AXIAL: + # flip_image = True + # else: + # flip_image = False # if (flip_image): update_progress = vtk_utils.ShowProgress(2 + number_filters) @@ -632,25 +602,16 @@ def LoadVolume(self): # Changed the vtkVolumeRayCast to vtkFixedPointVolumeRayCastMapper # because it's faster and the image is better # TODO: To test if it's true. - if const.TYPE_RAYCASTING_MAPPER: - volume_mapper = vtkVolumeRayCastMapper() + session = ses.Session() + if not session.GetConfig("rendering"): + volume_mapper = vtkFixedPointVolumeRayCastMapper() # volume_mapper.AutoAdjustSampleDistancesOff() - # volume_mapper.SetInput(image2) - # volume_mapper.SetVolumeRayCastFunction(composite_function) - # volume_mapper.SetGradientEstimator(gradientEstimator) - volume_mapper.IntermixIntersectingGeometryOn() self.volume_mapper = volume_mapper + volume_mapper.IntermixIntersectingGeometryOn() else: - session = ses.Session() - if not session.GetConfig("rendering"): - volume_mapper = vtkFixedPointVolumeRayCastMapper() - # volume_mapper.AutoAdjustSampleDistancesOff() - self.volume_mapper = volume_mapper - volume_mapper.IntermixIntersectingGeometryOn() - else: - volume_mapper = vtkOpenGLGPUVolumeRayCastMapper() - volume_mapper.UseJitteringOn() - self.volume_mapper = volume_mapper + volume_mapper = vtkOpenGLGPUVolumeRayCastMapper() + volume_mapper.UseJitteringOn() + self.volume_mapper = volume_mapper self.SetTypeRaycasting() volume_mapper.SetInputData(image2) @@ -911,7 +872,7 @@ def Disable(self): def Reset(self): plane_source = self.plane_source - plane_widget = self.plane_widget + # plane_widget = self.plane_widget plane_source.SetOrigin(self.origin) plane_source.SetPoint1(self.p1) plane_source.SetPoint2(self.p2) diff --git a/invesalius/gui/bitmap_preview_panel.py b/invesalius/gui/bitmap_preview_panel.py index c76531e36..e79f7d5b8 100644 --- a/invesalius/gui/bitmap_preview_panel.py +++ b/invesalius/gui/bitmap_preview_panel.py @@ -54,7 +54,7 @@ class SelectionEvent(wx.PyCommandEvent): class PreviewEvent(wx.PyCommandEvent): def __init__(self, evtType, id): - super(PreviewEvent, self).__init__(evtType, id) + super().__init__(evtType, id) def GetSelectID(self): return self.SelectedID @@ -77,10 +77,10 @@ def SetShiftStatus(self, status): class SerieEvent(PreviewEvent): def __init__(self, evtType, id): - super(SerieEvent, self).__init__(evtType, id) + super().__init__(evtType, id) -class BitmapInfo(object): +class BitmapInfo: """ Keep the informations and the image used by preview. """ @@ -108,7 +108,7 @@ def release_thumbnail(self): class DicomPaintPanel(wx.Panel): def __init__(self, parent): - super(DicomPaintPanel, self).__init__(parent) + super().__init__(parent) self._bind_events() self.image = None self.last_size = (10, 10) @@ -157,7 +157,7 @@ class Preview(wx.Panel): """ def __init__(self, parent): - super(Preview, self).__init__(parent) + super().__init__(parent) # Will it be white? self.select_on = False self.bitmap_info = None @@ -280,7 +280,7 @@ class BitmapPreviewSeries(wx.Panel): """A dicom series preview panel""" def __init__(self, parent): - super(BitmapPreviewSeries, self).__init__(parent) + super().__init__(parent) # TODO: 3 pixels between the previews is a good idea? # I have to test. self.displayed_position = 0 @@ -367,7 +367,7 @@ def SetBitmapFiles(self, data): def RemovePanel(self, data): for p, f in zip(self.previews, self.files): - if p.bitmap_info != None: + if p.bitmap_info is not None: if data in p.bitmap_info.data[0]: self.files.remove(f) p.Hide() @@ -380,7 +380,7 @@ def RemovePanel(self, data): self.Layout() for n, p in enumerate(self.previews): - if p.bitmap_info != None: + if p.bitmap_info is not None: if p.IsShown(): p.bitmap_info.pos = n @@ -548,7 +548,7 @@ def __bind_pubsub(self): Publisher.subscribe(self.ShowBlackSlice, "Show black slice in single preview image") def ShowBitmapByPosition(self, pos): - if pos != None: + if pos is not None: self.ShowSlice(int(pos)) def OnSlider(self, evt): @@ -629,7 +629,7 @@ def ShowSlice(self, index=0): value1 = "" value2 = "" - value = "%s\n%s" % (value1, value2) + value = f"{value1}\n{value2}" self.text_image_location.SetValue(value) # self.text_patient.SetValue(value) diff --git a/invesalius/gui/data_notebook.py b/invesalius/gui/data_notebook.py index 491938b9a..2591aaeb0 100644 --- a/invesalius/gui/data_notebook.py +++ b/invesalius/gui/data_notebook.py @@ -18,7 +18,6 @@ # detalhes. # -------------------------------------------------------------------------- import os -import platform import sys try: @@ -26,13 +25,10 @@ except ImportError: from PIL import Image -import numpy as np import wx import wx.grid -import wx.lib.colourselect as csel # import invesalius.gui.widgets.listctrl as listmix -import wx.lib.mixins.listctrl as listmix import wx.lib.platebtn as pbtn import invesalius.constants as const @@ -42,7 +38,7 @@ from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher -BTN_NEW, BTN_REMOVE, BTN_DUPLICATE, BTN_OPEN = [wx.NewIdRef() for i in range(4)] +BTN_NEW, BTN_REMOVE, BTN_DUPLICATE, BTN_OPEN = (wx.NewIdRef() for i in range(4)) TYPE = { const.LINEAR: _("Linear"), @@ -184,8 +180,8 @@ def __init_gui(self): self.Fit() menu = wx.Menu() - item = menu.Append(const.MEASURE_LINEAR, _("Measure distance")) - item = menu.Append(const.MEASURE_ANGULAR, _("Measure angle")) + menu.Append(const.MEASURE_LINEAR, _("Measure distance")) + menu.Append(const.MEASURE_ANGULAR, _("Measure angle")) menu.Bind(wx.EVT_MENU, self.OnMenu) self.menu = menu @@ -577,13 +573,13 @@ def __init_image_list(self): bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_null = self.imagelist.Add(bitmap) + self.imagelist.Add(bitmap) image = wx.Image(os.path.join(inv_paths.ICON_DIR, "object_visible.png")) bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_check = self.imagelist.Add(bitmap) + self.imagelist.Add(bitmap) self.SetImageList(self.imagelist, wx.IMAGE_LIST_SMALL) @@ -990,13 +986,13 @@ def __init_image_list(self): bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_null = self.imagelist.Add(bitmap) + self.imagelist.Add(bitmap) image = wx.Image(os.path.join(inv_paths.ICON_DIR, "object_visible.png")) bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_check = self.imagelist.Add(bitmap) + self.imagelist.Add(bitmap) self.SetImageList(self.imagelist, wx.IMAGE_LIST_SMALL) @@ -1039,8 +1035,8 @@ def AddSurface(self, surface): index = surface.index name = surface.name colour = surface.colour - volume = "%.3f" % surface.volume - area = "%.3f" % surface.area + volume = f"{surface.volume:.3f}" + area = f"{surface.area:.3f}" transparency = "%d%%" % (int(100 * surface.transparency)) if index not in self.surface_list_index: @@ -1053,14 +1049,14 @@ def AddSurface(self, surface): if (index in index_list) and index_list: try: self.UpdateItemInfo(index, name, volume, area, transparency, colour) - except wx._core.wxAssertionError: + except wx.wxAssertionError: self.InsertNewItem(index, name, volume, area, transparency, colour) else: self.InsertNewItem(index, name, volume, area, transparency, colour) else: try: self.UpdateItemInfo(index, name, volume, area, transparency, colour) - except wx._core.wxAssertionError: + except wx.wxAssertionError: self.InsertNewItem(index, name, volume, area, transparency, colour) def InsertNewItem( @@ -1202,7 +1198,7 @@ def OnItemSelected_(self, evt): # Otherwise the parent's method will be overwritten and other # things will stop working, e.g.: OnCheckItem - last_index = evt.Index + # last_index = evt.Index # Publisher.sendMessage('Change measurement selected', # last_index) evt.Skip() @@ -1241,13 +1237,13 @@ def __init_image_list(self): bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_null = self.imagelist.Add(bitmap) + self.imagelist.Add(bitmap) image = wx.Image(os.path.join(inv_paths.ICON_DIR, "object_visible.png")) bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_check = self.imagelist.Add(bitmap) + self.imagelist.Add(bitmap) self.SetImageList(self.imagelist, wx.IMAGE_LIST_SMALL) @@ -1294,18 +1290,18 @@ def OnLoadData(self, measurement_dict, spacing=(1.0, 1.0, 1.0)): image = self.CreateColourBitmap(m.colour) image_index = self.imagelist.Add(image) - index_list = self._list_index.keys() + # index_list = self._list_index.keys() self._list_index[m.index] = image_index colour = [255 * c for c in m.colour] type = TYPE[m.type] location = LOCATION[m.location] if m.type == const.LINEAR: - value = ("%.2f mm") % m.value + value = f"{m.value:.2f} mm" elif m.type == const.ANGULAR: - value = ("%.2f°") % m.value + value = f"{m.value:.2f}°" else: - value = ("%.3f") % m.value + value = f"{m.value:.3f}" self.InsertNewItem(m.index, m.name, colour, location, type, value) if not m.visible: @@ -1322,14 +1318,14 @@ def AddItem_(self, index, name, colour, location, type_, value): if (index in index_list) and index_list: try: self.UpdateItemInfo(index, name, colour, location, type_, value) - except wx._core.wxAssertionError: + except wx.wxAssertionError: self.InsertNewItem(index, name, colour, location, type_, value) else: self.InsertNewItem(index, name, colour, location, type_, value) else: try: self.UpdateItemInfo(index, name, colour, location, type_, value) - except wx._core.wxAssertionError: + except wx.wxAssertionError: self.InsertNewItem(index, name, colour, location, type_, value) def InsertNewItem( @@ -1417,13 +1413,13 @@ def __init_image_list(self): bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) bitmap.SetHeight(16) - img_check = self.imagelist.Add(bitmap) + img_check = self.imagelist.Add(bitmap) # noqa: F841 image = wx.Image(os.path.join(inv_paths.ICON_DIR, "object_invisible.png")) bitmap = wx.Bitmap(image.Scale(16, 16)) bitmap.SetWidth(16) - bitmap.SetHeight(16) - img_null = self.imagelist.Add(bitmap) + bitmap.SetHeicght(16) + img_null = self.imagelist.Add(bitmap) # noqa: F841 image = wx.Image(os.path.join(inv_paths.ICON_DIR, "object_colour.png")) bitmap = wx.Bitmap(image.Scale(16, 16)) diff --git a/invesalius/gui/deep_learning_seg_dialog.py b/invesalius/gui/deep_learning_seg_dialog.py index c7f676cc0..91d1bc812 100644 --- a/invesalius/gui/deep_learning_seg_dialog.py +++ b/invesalius/gui/deep_learning_seg_dialog.py @@ -3,11 +3,6 @@ import importlib import multiprocessing -import os -import pathlib -import subprocess -import sys -import tempfile import time import numpy as np @@ -144,7 +139,7 @@ def _init_gui(self): self.btn_stop.Disable() self.btn_close = wx.Button(self, wx.ID_CLOSE) - self.txt_threshold.SetValue("{:3d}%".format(self.sld_threshold.GetValue())) + self.txt_threshold.SetValue(f"{self.sld_threshold.GetValue():3d}%") def _do_layout(self): main_sizer = wx.BoxSizer(wx.VERTICAL) @@ -244,8 +239,8 @@ def OnSetBackend(self, evt=None): self.main_sizer.SetSizeHints(self) def OnScrollThreshold(self, evt): - value = self.sld_threshold.GetValue() - self.txt_threshold.SetValue("{:3d}%".format(self.sld_threshold.GetValue())) + # value = self.sld_threshold.GetValue() + self.txt_threshold.SetValue(f"{self.sld_threshold.GetValue():3d}%") if self.segmented: self.apply_segment_threshold() @@ -257,7 +252,7 @@ def OnKillFocus(self, evt): except ValueError: value = self.sld_threshold.GetValue() self.sld_threshold.SetValue(value) - self.txt_threshold.SetValue("{:3d}%".format(value)) + self.txt_threshold.SetValue(f"{value:3d}%") if self.segmented: self.apply_segment_threshold() @@ -281,7 +276,7 @@ def OnSegment(self, evt): apply_wwwl = self.chk_apply_wwwl.GetValue() create_new_mask = self.chk_new_mask.GetValue() use_gpu = self.chk_use_gpu.GetValue() - prob_threshold = self.sld_threshold.GetValue() / 100.0 + # prob_threshold = self.sld_threshold.GetValue() / 100.0 self.btn_close.Disable() self.btn_stop.Enable() self.btn_segment.Disable() @@ -488,7 +483,7 @@ def OnSegment(self, evt): apply_wwwl = self.chk_apply_wwwl.GetValue() create_new_mask = self.chk_new_mask.GetValue() use_gpu = self.chk_use_gpu.GetValue() - prob_threshold = self.sld_threshold.GetValue() / 100.0 + # prob_threshold = self.sld_threshold.GetValue() / 100.0 resize_by_spacing = self.chk_apply_resize_by_spacing.GetValue() self.btn_close.Disable() diff --git a/invesalius/gui/default_tasks.py b/invesalius/gui/default_tasks.py index 1d28ee52f..958d15ad9 100644 --- a/invesalius/gui/default_tasks.py +++ b/invesalius/gui/default_tasks.py @@ -18,11 +18,8 @@ # -------------------------------------------------------------------------- import wx +import wx.lib.agw.foldpanelbar as fpb -try: - import wx.lib.agw.foldpanelbar as fpb -except ModuleNotFoundError: - import wx.lib.foldpanelbar as fpb import invesalius.constants as const import invesalius.gui.data_notebook as nb import invesalius.gui.task_exporter as exporter @@ -31,7 +28,6 @@ import invesalius.gui.task_navigator as navigator import invesalius.gui.task_slice as slice_ import invesalius.gui.task_surface as surface -import invesalius.gui.task_tools as tools import invesalius.session as ses from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher @@ -185,8 +181,8 @@ def __init__(self, parent): # Fold 1 - Data item = fold_panel.AddFoldPanel(_("Data"), collapsed=False, foldIcons=image_list) - style = fold_panel.GetCaptionStyle(item) - col = style.GetFirstColour() + # style = fold_panel.GetCaptionStyle(item) + # col = style.GetFirstColour() self.enable_items.append(item) # npanel = wx.Panel(self, -1) @@ -308,9 +304,9 @@ def __init__(self, parent): "%d. %s" % (i + 1, name), collapsed=True, foldIcons=image_list ) else: - item = fold_panel.AddFoldPanel("%s" % name, collapsed=True, foldIcons=image_list) - style = fold_panel.GetCaptionStyle(item) - col = style.GetFirstColour() + item = fold_panel.AddFoldPanel(f"{name}", collapsed=True, foldIcons=image_list) + # style = fold_panel.GetCaptionStyle(item) + # col = style.GetFirstColour() # Add panel to FoldPanel fold_panel.AddFoldPanelWindow( @@ -388,7 +384,7 @@ def SetStateProjectOpen(self): def OnFoldPressCaption(self, evt): id = evt.GetTag().GetId() - closed = evt.GetFoldStatus() + # closed = evt.GetFoldStatus() if id == self.__id_slice: Publisher.sendMessage("Retrieve task slice style") diff --git a/invesalius/gui/default_viewers.py b/invesalius/gui/default_viewers.py index 66eada1ce..e5d9d4368 100644 --- a/invesalius/gui/default_viewers.py +++ b/invesalius/gui/default_viewers.py @@ -21,6 +21,8 @@ import wx import wx.lib.agw.fourwaysplitter as fws +import wx.lib.colourselect as csel +import wx.lib.platebtn as pbtn import invesalius.constants as const import invesalius.data.viewer_slice as slice_viewer @@ -241,14 +243,13 @@ def __init_mix(self): splitter.AppendWindow(p1) splitter.AppendWindow(p2) splitter.AppendWindow(p3) - splitter.AppendWindow(p4) aui_manager.Update() class VolumeInteraction(wx.Panel): def __init__(self, parent, id): - super(VolumeInteraction, self).__init__(parent, id) + super().__init__(parent, id) self.can_show_raycasting_widget = 0 self.__init_aui_manager() # sizer = wx.BoxSizer(wx.HORIZONTAL) @@ -351,12 +352,6 @@ def _Exit(self): self.aui_manager.UnInit() -import wx.lib.buttons as btn -import wx.lib.colourselect as csel -import wx.lib.platebtn as pbtn - -from invesalius.pubsub import pub as Publisher - RAYCASTING_TOOLS = wx.NewIdRef() ID_TO_NAME = {} @@ -398,7 +393,7 @@ def __init__(self, parent): BMP_3D_STEREO = wx.Bitmap( str(inv_paths.ICON_DIR.joinpath("3D_glasses.png")), wx.BITMAP_TYPE_PNG ) - BMP_TARGET = wx.Bitmap(str(inv_paths.ICON_DIR.joinpath("target.png")), wx.BITMAP_TYPE_PNG) + # BMP_TARGET = wx.Bitmap(str(inv_paths.ICON_DIR.joinpath("target.png")), wx.BITMAP_TYPE_PNG) self.button_raycasting = pbtn.PlateButton( self, -1, "", BMP_RAYCASTING, style=pbtn.PB_STYLE_SQUARE, size=ICON_SIZE @@ -657,5 +652,5 @@ def OnMenuView(self, evt): self.Refresh() def OnSelectColour(self, evt): - colour = c = [i / 255.0 for i in evt.GetValue()] + colour = [i / 255.0 for i in evt.GetValue()] Publisher.sendMessage("Change volume viewer background colour", colour=colour) diff --git a/invesalius/gui/dialogs.py b/invesalius/gui/dialogs.py index a4e44207f..d78c554cc 100644 --- a/invesalius/gui/dialogs.py +++ b/invesalius/gui/dialogs.py @@ -870,7 +870,11 @@ def __init__( class ErrorMessageBox(wx.Dialog): def __init__( - self, parent: wx.Window, title: str, message: str, caption: str = "InVesalius3 Error" + self, + parent: Optional[wx.Window], + title: str, + message: str, + caption: str = "InVesalius3 Error", ): wx.Dialog.__init__( self, parent, title=caption, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER @@ -4590,7 +4594,7 @@ def DistanceBetweenPointAndSurface(self, surface, points: np.ndarray) -> np.floa return np.sqrt(float(d)) def OnComboName(self, evt: wx.CommandEvent) -> None: - surface_name = evt.GetString() + # surface_name = evt.GetString() surface_index = evt.GetSelection() self.surface = self.proj.surface_dict[surface_index].polydata if self.obj_actor: @@ -4659,7 +4663,7 @@ def OnICP(self, evt: wx.CommandEvent) -> None: sourcePoints_vtk = vtkPoints() for i in range(len(sourcePoints)): - id0 = sourcePoints_vtk.InsertNextPoint(sourcePoints[i]) + sourcePoints_vtk.InsertNextPoint(sourcePoints[i]) source = vtkPolyData() source.SetPoints(sourcePoints_vtk) @@ -5506,7 +5510,7 @@ def ICP( sourcePoints = np.array(coord[:3]) sourcePoints_vtk = vtkPoints() for i in range(len(sourcePoints)): - id0 = sourcePoints_vtk.InsertNextPoint(sourcePoints) + sourcePoints_vtk.InsertNextPoint(sourcePoints) source = vtkPolyData() source.SetPoints(sourcePoints_vtk) diff --git a/invesalius/gui/dicom_preview_panel.py b/invesalius/gui/dicom_preview_panel.py index 83f3dea86..7a579347a 100644 --- a/invesalius/gui/dicom_preview_panel.py +++ b/invesalius/gui/dicom_preview_panel.py @@ -21,7 +21,6 @@ # TODO: To create a beautiful API import sys -import tempfile import time import wx @@ -38,6 +37,7 @@ import invesalius.utils as utils from invesalius.data import converters, imagedata_utils from invesalius.gui.widgets.canvas_renderer import CanvasRendererCTX +from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher if sys.platform == "win32": @@ -88,7 +88,7 @@ class SelectionEvent(wx.PyCommandEvent): class PreviewEvent(wx.PyCommandEvent): def __init__(self, evtType, id): - super(PreviewEvent, self).__init__(evtType, id) + super().__init__(evtType, id) def GetSelectID(self): return self.SelectedID @@ -111,10 +111,10 @@ def SetShiftStatus(self, status): class SerieEvent(PreviewEvent): def __init__(self, evtType, id): - super(SerieEvent, self).__init__(evtType, id) + super().__init__(evtType, id) -class DicomInfo(object): +class DicomInfo: """ Keep the informations and the image used by preview. """ @@ -145,7 +145,7 @@ def release_thumbnail(self): class DicomPaintPanel(wx.Panel): def __init__(self, parent): - super(DicomPaintPanel, self).__init__(parent) + super().__init__(parent) self._bind_events() self.image = None self.last_size = (10, 10) @@ -194,7 +194,7 @@ class Preview(wx.Panel): """ def __init__(self, parent): - super(Preview, self).__init__(parent) + super().__init__(parent) # Will it be white? self.select_on = False self.dicom_info = None @@ -275,10 +275,8 @@ def SetSubtitle(self, subtitle): def OnEnter(self, evt): if not self.select_on: # c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DHILIGHT) - try: - c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE) - except AttributeError: - c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNFACE) + c = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE) + self.SetBackgroundColour(c) def OnLeave(self, evt): @@ -291,7 +289,7 @@ def OnSelect(self, evt): if evt.shiftDown: shift_pressed = True - dicom_id = self.dicom_info.id + # dicom_id = self.dicom_info.id self.select_on = True self.dicom_info.selected = True ##c = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNHIGHLIGHT) @@ -345,7 +343,7 @@ class DicomPreviewSeries(wx.Panel): """A dicom series preview panel""" def __init__(self, parent): - super(DicomPreviewSeries, self).__init__(parent) + super().__init__(parent) # TODO: 3 pixels between the previews is a good idea? # I have to test. # self.sizer = wx.BoxSizer(wx.HORIZONTAL) @@ -484,7 +482,7 @@ class DicomPreviewSlice(wx.Panel): """A dicom preview panel""" def __init__(self, parent): - super(DicomPreviewSlice, self).__init__(parent) + super().__init__(parent) # TODO: 3 pixels between the previews is a good idea? # I have to test. self.displayed_position = 0 @@ -535,7 +533,7 @@ def _bind_events(self): self.Bind(wx.EVT_MOUSEWHEEL, self.OnWheel) def SetDicomDirectory(self, directory): - utils.debug("Setting Dicom Directory %s" % directory) + utils.debug(f"Setting Dicom Directory {directory}") self.directory = directory self.series = dicom_reader.GetSeries(directory)[0] @@ -557,7 +555,7 @@ def SetDicomSerie(self, pos): for thumbnail in dicom.image.thumbnail_path: print(thumbnail) info = DicomInfo( - n, dicom, _("Image %d") % (n), "%.2f" % (dicom.image.position[2]), _slice + n, dicom, _("Image %d") % (n), f"{dicom.image.position[2]:.2f}", _slice ) self.files.append(info) n += 1 @@ -567,7 +565,7 @@ def SetDicomSerie(self, pos): n, dicom, _("Image %d") % (dicom.image.number), - "%.2f" % (dicom.image.position[2]), + f"{dicom.image.position[2]:.2f}", ) self.files.append(info) n += 1 @@ -592,7 +590,7 @@ def SetDicomGroup(self, group): for thumbnail in dicom.image.thumbnail_path: print(thumbnail) info = DicomInfo( - n, dicom, _("Image %d") % int(n), "%.2f" % (dicom.image.position[2]), _slice + n, dicom, _("Image %d") % int(n), f"{dicom.image.position[2]:.2f}", _slice ) self.files.append(info) n += 1 @@ -602,7 +600,7 @@ def SetDicomGroup(self, group): n, dicom, _("Image %d") % int(dicom.image.number), - "%.2f" % (dicom.image.position[2]), + f"{dicom.image.position[2]:.2f}", ) self.files.append(info) n += 1 @@ -881,7 +879,7 @@ def ShowSlice(self, index=0): else: value2 = "" - value = "%s\n%s" % (value1, value2) + value = f"{value1}\n{value2}" self.text_image_location.SetValue(value) ## Text related to patient/ acquisiiton data diff --git a/invesalius/gui/frame.py b/invesalius/gui/frame.py index 19ec56a82..fa65b8e7f 100644 --- a/invesalius/gui/frame.py +++ b/invesalius/gui/frame.py @@ -18,7 +18,6 @@ # -------------------------------------------------------------------- import errno -import math import os.path import platform import subprocess @@ -27,7 +26,6 @@ import wx import wx.aui -import wx.lib.popupctl as pc from wx.lib.agw.aui.auibar import AUI_TB_PLAIN_BACKGROUND, AuiToolBar import invesalius.constants as const @@ -427,7 +425,7 @@ def _SetProjectName(self, proj_name=""): if not (proj_name): self.SetTitle("InVesalius 3") else: - self.SetTitle("%s - InVesalius 3" % (proj_name)) + self.SetTitle(f"{proj_name} - InVesalius 3") def _ShowContentPanel(self): """ @@ -710,9 +708,6 @@ def OnDbsMode(self): Publisher.sendMessage("Hide dbs folder") self.actived_navigation_mode.Check(const.ID_MODE_NAVIGATION, 0) - def OnInterpolatedSlices(self, status): - Publisher.sendMessage("Set interpolated slices", flag=status) - def OnNavigationMode(self, status): if status and self._show_navigator_message and sys.platform != "win32": wx.MessageBox( @@ -738,7 +733,7 @@ def OnIdle(self, evt): self.Reposition() def Reposition(self): - Publisher.sendMessage(("ProgressBar Reposition")) + Publisher.sendMessage("ProgressBar Reposition") self.sizeChanged = False def OnMove(self, evt): @@ -864,14 +859,12 @@ def ExportProject(self): filename += ext try: p.export_project(filename) - except (OSError, IOError) as err: + except OSError as err: if err.errno == errno.EACCES: - message = "It was not possible to save because you don't have permission to write at {}".format( - dirpath - ) + message = f"It was not possible to save because you don't have permission to write at {dirpath}" else: message = "It was not possible to save because" - d = dlg.ErrorMessageBox(None, "Save project error", "{}:\n{}".format(message, err)) + d = dlg.ErrorMessageBox(None, "Save project error", f"{message}:\n{err}") d.ShowModal() d.Destroy() else: @@ -1726,11 +1719,11 @@ def __init_items(self): path = d.joinpath("preferences.png") BMP_PREFERENCES = wx.Bitmap(str(path), wx.BITMAP_TYPE_PNG) - path = d.joinpath("print_original.png") - BMP_PRINT = wx.Bitmap(str(path), wx.BITMAP_TYPE_PNG) + # path = d.joinpath("print_original.png") + # BMP_PRINT = wx.Bitmap(str(path), wx.BITMAP_TYPE_PNG) - path = d.joinpath("tool_photo_original.png") - BMP_PHOTO = wx.Bitmap(str(path), wx.BITMAP_TYPE_PNG) + # path = d.joinpath("tool_photo_original.png") + # BMP_PHOTO = wx.Bitmap(str(path), wx.BITMAP_TYPE_PNG) # Create tool items based on bitmaps self.AddTool( diff --git a/invesalius/gui/import_bitmap_panel.py b/invesalius/gui/import_bitmap_panel.py index dc3c4166f..81fb9c6f7 100644 --- a/invesalius/gui/import_bitmap_panel.py +++ b/invesalius/gui/import_bitmap_panel.py @@ -24,7 +24,6 @@ import invesalius.gui.bitmap_preview_panel as bpp import invesalius.gui.dialogs as dlg import invesalius.reader.bitmap_reader as bpr -from invesalius.gui.dialogs import ImportBitmapParameters as dialogs from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher @@ -43,7 +42,7 @@ class SelectEvent(wx.PyCommandEvent): def __init__(self, evtType, id): - super(SelectEvent, self).__init__(evtType, id) + super().__init__(evtType, id) def GetSelectID(self): return self.SelectedID @@ -372,7 +371,7 @@ def SetBitmapFiles(self, data): self.Update() def OnSelectSerie(self, evt): - data = evt.GetItemData() + # data = evt.GetItemData() my_evt = SelectEvent(myEVT_SELECT_SERIE, self.GetId()) my_evt.SetSelectedID(evt.GetSelectID()) my_evt.SetItemData(evt.GetItemData()) diff --git a/invesalius/gui/import_network_panel.py b/invesalius/gui/import_network_panel.py index c1b179f09..44edbd160 100644 --- a/invesalius/gui/import_network_panel.py +++ b/invesalius/gui/import_network_panel.py @@ -50,7 +50,7 @@ class SelectEvent(wx.PyCommandEvent): def __init__(self, evtType, id): - super(SelectEvent, self).__init__(evtType, id) + super().__init__(evtType, id) def GetSelectID(self): return self.SelectedID @@ -194,7 +194,7 @@ def LoadDicom(self, group): group = max(group.GetGroups(), key=lambda g: g.nslices) slice_amont = group.nslices - if (self.first_image_selection != None) and ( + if (self.first_image_selection is not None) and ( self.first_image_selection != self.last_image_selection ): slice_amont = (self.last_image_selection) - self.first_image_selection @@ -282,7 +282,7 @@ def Populate(self, pubsub_evt): # print ">>>>>>>>>>>>",dir(self.tree) patients = pubsub_evt.data - first = 0 + # first = 0 self.idserie_treeitem = {} for patient in patients.keys(): @@ -315,17 +315,17 @@ def Populate(self, pubsub_evt): n_amount_images = n_amount_images + patients[patient][se]["n_images"] tree.SetItemPyData(parent, patient) - tree.SetItemText(parent, "%s" % p_id, 1) - tree.SetItemText(parent, "%s" % age, 2) - tree.SetItemText(parent, "%s" % gender, 3) - tree.SetItemText(parent, "%s" % study_description, 4) - tree.SetItemText(parent, "%s" % "", 5) - tree.SetItemText(parent, "%s" % date + " " + time, 6) - tree.SetItemText(parent, "%s" % str(n_amount_images), 7) - tree.SetItemText(parent, "%s" % institution, 8) - tree.SetItemText(parent, "%s" % birthdate, 9) - tree.SetItemText(parent, "%s" % acession_number, 10) - tree.SetItemText(parent, "%s" % physician, 11) + tree.SetItemText(parent, f"{p_id}", 1) + tree.SetItemText(parent, f"{age}", 2) + tree.SetItemText(parent, f"{gender}", 3) + tree.SetItemText(parent, f"{study_description}", 4) + tree.SetItemText(parent, "{}".format(""), 5) + tree.SetItemText(parent, f"{date}" + " " + time, 6) + tree.SetItemText(parent, f"{str(n_amount_images)}", 7) + tree.SetItemText(parent, f"{institution}", 8) + tree.SetItemText(parent, f"{birthdate}", 9) + tree.SetItemText(parent, f"{acession_number}", 10) + tree.SetItemText(parent, f"{physician}", 11) for series in patients[patient].keys(): serie_description = patients[patient][series]["serie_description"] @@ -337,11 +337,11 @@ def Populate(self, pubsub_evt): child = tree.AppendItem(parent, series) tree.SetItemPyData(child, series) - tree.SetItemText(child, "%s" % serie_description, 0) + tree.SetItemText(child, f"{serie_description}", 0) # tree.SetItemText(child, "%s" % dicom.acquisition.protocol_name, 4) - tree.SetItemText(child, "%s" % modality, 5) - tree.SetItemText(child, "%s" % date + " " + time, 6) - tree.SetItemText(child, "%s" % n_images, 7) + tree.SetItemText(child, f"{modality}", 5) + tree.SetItemText(child, f"{date}" + " " + time, 6) + tree.SetItemText(child, f"{n_images}", 7) self.idserie_treeitem[(patient, series)] = child @@ -722,7 +722,7 @@ def OnLeftDown(self, evt): evt.Skip() def OnButtonRemove(self, evt): - if self.selected_item != None and self.selected_item != 0: + if self.selected_item is not None and self.selected_item != 0: self.tree_node.DeleteItem(self.selected_item) self.hosts.pop(self.selected_item) self.selected_item = None @@ -751,7 +751,7 @@ def OnButtonCheck(self, evt): self.tree_node.SetItem(key, 4, _("error")) def RightButton(self, evt): - event.Skip() + evt.Skip() def OnItemSelected(self, evt): self.selected_item = evt.m_itemIndex diff --git a/invesalius/gui/import_panel.py b/invesalius/gui/import_panel.py index 6438ab818..950203cd6 100644 --- a/invesalius/gui/import_panel.py +++ b/invesalius/gui/import_panel.py @@ -21,7 +21,6 @@ import wx.lib.splitter as spl import invesalius.constants as const -import invesalius.gui.dialogs as dlg import invesalius.gui.dicom_preview_panel as dpp import invesalius.reader.dicom_grouper as dcm from invesalius.i18n import tr as _ @@ -42,7 +41,7 @@ class SelectEvent(wx.PyCommandEvent): def __init__(self, evtType, id): - super(SelectEvent, self).__init__(evtType, id) + super().__init__(evtType, id) def GetSelectID(self): return self.SelectedID @@ -183,7 +182,7 @@ def LoadDicom(self, group): group = max(group.GetGroups(), key=lambda g: g.nslices) slice_amont = group.nslices - if (self.first_image_selection != None) and ( + if (self.first_image_selection is not None) and ( self.first_image_selection != self.last_image_selection ): slice_amont = (self.last_image_selection) - self.first_image_selection @@ -191,7 +190,7 @@ def LoadDicom(self, group): if slice_amont == 0: slice_amont = group.nslices - nslices_result = slice_amont / (interval + 1) + # nslices_result = slice_amont / (interval + 1) Publisher.sendMessage( "Open DICOM group", group=group, @@ -273,7 +272,7 @@ def Populate(self, patient_list): ngroups = patient.ngroups dicom = patient.GetDicomSample() title = dicom.patient.name + " (%d series)" % (ngroups) - date_time = "%s %s" % (dicom.acquisition.date, dicom.acquisition.time) + date_time = f"{dicom.acquisition.date} {dicom.acquisition.time}" parent = tree.AppendItem(self.root, title) @@ -282,17 +281,17 @@ def Populate(self, patient_list): first += 1 tree.SetItemPyData(parent, patient) - tree.SetItemText(parent, "%s" % dicom.patient.id, 1) - tree.SetItemText(parent, "%s" % dicom.patient.age, 2) - tree.SetItemText(parent, "%s" % dicom.patient.gender, 3) - tree.SetItemText(parent, "%s" % dicom.acquisition.study_description, 4) - tree.SetItemText(parent, "%s" % dicom.acquisition.modality, 5) - tree.SetItemText(parent, "%s" % date_time, 6) - tree.SetItemText(parent, "%s" % patient.nslices, 7) - tree.SetItemText(parent, "%s" % dicom.acquisition.institution, 8) - tree.SetItemText(parent, "%s" % dicom.patient.birthdate, 9) - tree.SetItemText(parent, "%s" % dicom.acquisition.accession_number, 10) - tree.SetItemText(parent, "%s" % dicom.patient.physician, 11) + tree.SetItemText(parent, f"{dicom.patient.id}", 1) + tree.SetItemText(parent, f"{dicom.patient.age}", 2) + tree.SetItemText(parent, f"{dicom.patient.gender}", 3) + tree.SetItemText(parent, f"{dicom.acquisition.study_description}", 4) + tree.SetItemText(parent, f"{dicom.acquisition.modality}", 5) + tree.SetItemText(parent, f"{date_time}", 6) + tree.SetItemText(parent, f"{patient.nslices}", 7) + tree.SetItemText(parent, f"{dicom.acquisition.institution}", 8) + tree.SetItemText(parent, f"{dicom.patient.birthdate}", 9) + tree.SetItemText(parent, f"{dicom.acquisition.accession_number}", 10) + tree.SetItemText(parent, f"{dicom.patient.physician}", 11) group_list = patient.GetGroups() for n, group in enumerate(group_list): @@ -301,11 +300,11 @@ def Populate(self, patient_list): child = tree.AppendItem(parent, group.title) tree.SetItemPyData(child, group) - tree.SetItemText(child, "%s" % group.title, 0) - tree.SetItemText(child, "%s" % dicom.acquisition.protocol_name, 4) - tree.SetItemText(child, "%s" % dicom.acquisition.modality, 5) - tree.SetItemText(child, "%s" % date_time, 6) - tree.SetItemText(child, "%s" % group.nslices, 7) + tree.SetItemText(child, f"{group.title}", 0) + tree.SetItemText(child, f"{dicom.acquisition.protocol_name}", 4) + tree.SetItemText(child, f"{dicom.acquisition.modality}", 5) + tree.SetItemText(child, f"{date_time}", 6) + tree.SetItemText(child, f"{group.nslices}", 7) self.idserie_treeitem[(dicom.patient.id, dicom.acquisition.serie_number)] = child @@ -454,8 +453,8 @@ def SetPatientSeries(self, patient): self.Update() def OnSelectSerie(self, evt): - serie = evt.GetItemData() - data = evt.GetItemData() + # serie = evt.GetItemData() + # data = evt.GetItemData() my_evt = SelectEvent(myEVT_SELECT_SERIE, self.GetId()) my_evt.SetSelectedID(evt.GetSelectID()) diff --git a/invesalius/gui/language_dialog.py b/invesalius/gui/language_dialog.py index d13f614e1..b50eb866e 100644 --- a/invesalius/gui/language_dialog.py +++ b/invesalius/gui/language_dialog.py @@ -73,7 +73,7 @@ def __init__(self, parent): self.bitmapCmb = bitmapCmb = BitmapComboBox(parent, style=wx.CB_READONLY) for key in self.locales_key: # Based on composed flag filename, get bitmap - filepath = os.path.join(ICON_DIR, "%s.png" % (key)) + filepath = os.path.join(ICON_DIR, f"{key}.png") bmp = wx.Bitmap(filepath, wx.BITMAP_TYPE_PNG) # Add bitmap and info to Combo bitmapCmb.Append(dict_locales[key], bmp, key) @@ -95,7 +95,7 @@ class LanguageDialog(wx.Dialog): selected is writing in the config.ini""" def __init__(self, parent=None, startApp=None): - super(LanguageDialog, self).__init__(parent, title="") + super().__init__(parent, title="") self.__TranslateMessage__() self.SetTitle(_("Language selection")) self.__init_gui() diff --git a/invesalius/gui/log.py b/invesalius/gui/log.py index 433618ac0..3f07fb268 100644 --- a/invesalius/gui/log.py +++ b/invesalius/gui/log.py @@ -24,13 +24,14 @@ import os import sys from datetime import datetime +from functools import wraps from typing import Callable, Dict, List import wx import invesalius.constants as const from invesalius import inv_paths -from invesalius.utils import Singleton, deep_merge_dict +from invesalius.utils import deep_merge_dict LOG_CONFIG_PATH = os.path.join(inv_paths.USER_INV_DIR, "log_config.json") DEFAULT_LOGFILE = os.path.join( @@ -52,13 +53,13 @@ def __init__(self, textctrl): def emit(self, record): msg = self.format(record) - stream = self.stream + # stream = self.stream if invLogger._config["console_logging"] == 1: self.textctrl.WriteText(msg + "\n") self.flush() -class ConsoleRedirectText(object): +class ConsoleRedirectText: def __init__(self, textctrl): self.out = textctrl @@ -161,7 +162,7 @@ def _write_to_json(self, config_dict, config_filename): def _read_config_from_json(self, json_filename): try: - config_file = open(json_filename, "r") + config_file = open(json_filename) config_dict = json.load(config_file) self._config = deep_merge_dict(self._config.copy(), config_dict) except Exception as e1: @@ -192,11 +193,11 @@ def configureLogging(self): logging_file = os.path.abspath(logging_file) print("logging_file:", logging_file) console_logging = self._config["console_logging"] - console_logging_level = self._config["console_logging_level"] + # console_logging_level = self._config["console_logging_level"] self._logger.setLevel(self._config["base_logging_level"]) - if (self._frame == None) & (console_logging != 0): + if (self._frame is None) & (console_logging != 0): print("Initiating console logging ...") # self._frame = ConsoleLogFrame(self.getLogger()) @@ -209,7 +210,7 @@ def configureLogging(self): print("Initiated console logging ...") self._logger.info("Initiated console logging ...") - msg = "file_logging: {}, console_logging: {}".format(file_logging, console_logging) + msg = f"file_logging: {file_logging}, console_logging: {console_logging}" print(msg) self._logger.info(msg) @@ -242,17 +243,13 @@ def configureLogging(self): # os.path.samefile(logging_file,handler.baseFilename): #it doesn't seem to work handler.setLevel(file_logging_level) addFileHandler = False - msg = "No change in log file name {}.".format(logging_file) + msg = f"No change in log file name {logging_file}." self._logger.info(msg) else: - msg = ( - "Closing current log file {} as new log file {} requested.".format( - handler.baseFilename, logging_file - ) - ) + msg = f"Closing current log file {handler.baseFilename} as new log file {logging_file} requested." self._logger.info(msg) self._logger.removeHandler(handler) - msg = "Removed existing FILE handler {}".format(handler.baseFilename) + msg = f"Removed existing FILE handler {handler.baseFilename}" print(msg) self._logger.info(msg) if addFileHandler: @@ -263,7 +260,7 @@ def configureLogging(self): fh.setFormatter(formatter) self._logger.addHandler(fh) - msg = "Added file handler {}".format(logging_file) + msg = f"Added file handler {logging_file}" self._logger.info(msg) else: self.closeFileLogging() @@ -271,7 +268,7 @@ def configureLogging(self): def closeFileLogging(self): for handler in self._logger.handlers: if isinstance(handler, logging.FileHandler): - msg = "Removed file handler {}".format(handler.baseFilename) + msg = f"Removed file handler {handler.baseFilename}" self._logger.info(msg) # handler.flush() self._logger.removeHandler(handler) @@ -282,7 +279,7 @@ def closeConsoleLogging(self): self._logger.info("Removed stream handler") # handler.flush() self._logger.removeHandler(handler) - if self._frame != None: + if self._frame is not None: self._frame = None def closeLogging(self): @@ -296,7 +293,7 @@ def flushHandlers(self): def call_tracking_decorator(function: Callable[[str], None]): def wrapper_accepting_arguments(*args): - msg = "Function {} called".format(function.__name__) + msg = f"Function {function.__name__} called" invLogger._logger.info(msg) function(*args) @@ -305,7 +302,6 @@ def wrapper_accepting_arguments(*args): ##################################################################################### # Decorators for error handling -from functools import wraps def error_handling_decorator01(func: Callable[[str], None]): @@ -314,7 +310,7 @@ def error_handling_decorator01(func: Callable[[str], None]): ) # adds the functionality of copying over the function name, docstring, arguments list, etc. def wrapper_function(*args, **kwargs): try: - msg = "Function {} called".format(func.__name__) + msg = f"Function {func.__name__} called" invLogger._logger.info(msg) # print(f"{func.__name__} called") func(*args, **kwargs) @@ -328,7 +324,7 @@ def wrapper_function(*args, **kwargs): def error_handling_decorator02(errorList: List[str]): def Inner(func): def wrapper(*args, **kwargs): - msg = "Function {} called".format(func.__name__) + msg = f"Function {func.__name__} called" invLogger._logger.info(msg) try: func(*args, **kwargs) @@ -348,7 +344,7 @@ def wrapper(*args, **kwargs): def error_handling_decorator03(errorList: Dict[str, str]): def Inner(func): def wrapper(*args, **kwargs): - msg = "Function {} called".format(func.__name__) + msg = f"Function {func.__name__} called" invLogger._logger.info(msg) keys = [key for key in errorList] print("keys:", keys) @@ -377,7 +373,7 @@ def decorator(func): def new_func(*args, **kwargs): try: return func(*args, **kwargs) - except errors as e: + except errors: print("Got error! ") # , repr(e) return default_value diff --git a/invesalius/gui/preferences.py b/invesalius/gui/preferences.py index ddae6e350..c0b13f4f7 100644 --- a/invesalius/gui/preferences.py +++ b/invesalius/gui/preferences.py @@ -2,7 +2,6 @@ import sys from functools import partial -import nibabel as nb import numpy as np import wx @@ -675,7 +674,7 @@ def OnLoadCoil(self, event=None): try: if filename: - with open(filename, "r") as text_file: + with open(filename) as text_file: data = [s.split("\t") for s in text_file.readlines()] registration_coordinates = np.array(data[1:]).astype(np.float32) @@ -714,7 +713,7 @@ def OnLoadCoil(self, event=None): msg = _("Object file successfully loaded") wx.MessageBox(msg, _("InVesalius 3")) - except: + except Exception: wx.MessageBox(_("Object registration file incompatible."), _("InVesalius 3")) Publisher.sendMessage("Update status text in GUI", label="") diff --git a/invesalius/gui/project_properties.py b/invesalius/gui/project_properties.py index 24f765733..229e2a121 100644 --- a/invesalius/gui/project_properties.py +++ b/invesalius/gui/project_properties.py @@ -23,7 +23,6 @@ from invesalius import constants as const from invesalius.gui import utils from invesalius.i18n import tr as _ -from invesalius.pubsub import pub as Publisher ORIENTATION_LABEL = { const.AXIAL: _("Axial"), diff --git a/invesalius/gui/task_efield.py b/invesalius/gui/task_efield.py index 2e63213be..f4c642d98 100644 --- a/invesalius/gui/task_efield.py +++ b/invesalius/gui/task_efield.py @@ -23,7 +23,7 @@ import numpy as np try: - import Trekker + import Trekker # noqa: F401 has_trekker = True except ImportError: @@ -35,24 +35,17 @@ mTMS() has_mTMS = True -except: +except Exception: has_mTMS = False import wx - -try: - import wx.lib.agw.foldpanelbar as fpb -except ImportError: - import wx.lib.foldpanelbar as fpb - import wx.lib.masked.numctrl import invesalius.constants as const import invesalius.data.brainmesh_handler as brain import invesalius.gui.dialogs as dlg import invesalius.session as ses -from invesalius import inv_paths, utils -from invesalius.navigation.iterativeclosestpoint import IterativeClosestPoint +from invesalius.i18n import tr as _ from invesalius.navigation.navigation import Navigation from invesalius.net.neuronavigation_api import NeuronavigationApi from invesalius.net.pedal_connection import PedalConnector @@ -84,10 +77,7 @@ def __init__(self, parent): class InnerTaskPanel(wx.Panel): def __init__(self, parent, navigation): wx.Panel.__init__(self, parent) - try: - default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) - except AttributeError: - default_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_MENUBAR) + default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) self.__bind_events() self.SetBackgroundColour(default_colour) @@ -106,7 +96,7 @@ def __init__(self, parent, navigation): # Check box to enable e-field visualization enable_efield = wx.CheckBox(self, -1, _("Enable E-field")) enable_efield.SetValue(False) - enable_efield.Enable(1) + enable_efield.Enable(True) enable_efield.Bind(wx.EVT_CHECKBOX, partial(self.OnEnableEfield, ctrl=enable_efield)) self.enable_efield = enable_efield @@ -117,28 +107,28 @@ def __init__(self, parent, navigation): show_area = wx.CheckBox(self, -1, _("Show area above threshold")) show_area.SetValue(False) - show_area.Enable(1) + show_area.Enable(True) show_area.Bind( wx.EVT_CHECKBOX, partial(self.OnEnableShowAreaAboveThreshold, ctrl=show_area) ) efield_tools = wx.CheckBox(self, -1, _("Enable Efield targeting tools")) efield_tools.SetValue(False) - efield_tools.Enable(1) + efield_tools.Enable(True) efield_tools.Bind( wx.EVT_CHECKBOX, partial(self.OnEnableEfieldTargetingTools, ctrl=efield_tools) ) efield_cortex_markers = wx.CheckBox(self, -1, _("View cortex Markers")) efield_cortex_markers.SetValue(True) - efield_cortex_markers.Enable(1) + efield_cortex_markers.Enable(True) efield_cortex_markers.Bind( wx.EVT_CHECKBOX, partial(self.OnViewCortexMarkers, ctrl=efield_cortex_markers) ) efield_save_automatically = wx.CheckBox(self, -1, _("Save Automatically")) efield_save_automatically.SetValue(False) - efield_save_automatically.Enable(1) + efield_save_automatically.Enable(True) efield_save_automatically.Bind( wx.EVT_CHECKBOX, partial(self.OnSaveEfieldAutomatically, ctrl=efield_save_automatically) ) @@ -146,7 +136,7 @@ def __init__(self, parent, navigation): tooltip2 = _("Load Brain Json config") btn_act2 = wx.Button(self, -1, _("Load Config"), size=wx.Size(100, 23)) btn_act2.SetToolTip(tooltip2) - btn_act2.Enable(1) + btn_act2.Enable(True) btn_act2.Bind(wx.EVT_BUTTON, self.OnAddConfig) tooltip = _("Save Efield") @@ -163,7 +153,7 @@ def __init__(self, parent, navigation): text_sleep = wx.StaticText(self, -1, _("Sleep (s):")) spin_sleep = wx.SpinCtrlDouble(self, -1, "", size=wx.Size(50, 23), inc=0.01) - spin_sleep.Enable(1) + spin_sleep.Enable(True) spin_sleep.SetRange(0.05, 10.0) spin_sleep.SetValue(self.sleep_nav) spin_sleep.Bind(wx.EVT_TEXT, partial(self.OnSelectSleep, ctrl=spin_sleep)) @@ -171,7 +161,7 @@ def __init__(self, parent, navigation): text_threshold = wx.StaticText(self, -1, _("Threshold:")) spin_threshold = wx.SpinCtrlDouble(self, -1, "", size=wx.Size(50, 23), inc=0.01) - spin_threshold.Enable(1) + spin_threshold.Enable(True) spin_threshold.SetRange(0.1, 1) spin_threshold.SetValue(const.EFIELD_MAX_RANGE_SCALE) spin_threshold.Bind(wx.EVT_TEXT, partial(self.OnSelectThreshold, ctrl=spin_threshold)) @@ -179,7 +169,7 @@ def __init__(self, parent, navigation): text_ROI_size = wx.StaticText(self, -1, _("ROI size:")) spin_ROI_size = wx.SpinCtrlDouble(self, -1, "", size=wx.Size(50, 23), inc=0.01) - spin_ROI_size.Enable(1) + spin_ROI_size.Enable(True) spin_ROI_size.SetValue(const.EFIELD_ROI_SIZE) spin_ROI_size.Bind(wx.EVT_TEXT, partial(self.OnSelectROISize, ctrl=spin_ROI_size)) spin_ROI_size.Bind(wx.EVT_SPINCTRL, partial(self.OnSelectROISize, ctrl=spin_ROI_size)) @@ -456,7 +446,7 @@ def OnComboCoilNameClic(self, evt): self.combo_change_coil.Insert(coil_name, elements) def OnComboCoil(self, evt): - coil_name = evt.GetString() + # coil_name = evt.GetString() coil_index = evt.GetSelection() if coil_index == 6: coil_set = True @@ -523,12 +513,8 @@ def OnSaveEfield(self, evt): proj = prj.Project() timestamp = time.localtime(time.time()) - stamp_date = "{:0>4d}{:0>2d}{:0>2d}".format( - timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday - ) - stamp_time = "{:0>2d}{:0>2d}{:0>2d}".format( - timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec - ) + stamp_date = f"{timestamp.tm_year:0>4d}{timestamp.tm_mon:0>2d}{timestamp.tm_mday:0>2d}" + stamp_time = f"{timestamp.tm_hour:0>2d}{timestamp.tm_min:0>2d}{timestamp.tm_sec:0>2d}" sep = "-" if self.path_meshes is None: import os @@ -563,12 +549,8 @@ def OnSaveAllDataEfield(self, evt): proj = prj.Project() timestamp = time.localtime(time.time()) - stamp_date = "{:0>4d}{:0>2d}{:0>2d}".format( - timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday - ) - stamp_time = "{:0>2d}{:0>2d}{:0>2d}".format( - timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec - ) + stamp_date = f"{timestamp.tm_year:0>4d}{timestamp.tm_mon:0>2d}{timestamp.tm_mday:0>2d}" + stamp_time = f"{timestamp.tm_hour:0>2d}{timestamp.tm_min:0>2d}{timestamp.tm_sec:0>2d}" sep = "-" if self.path_meshes is None: import os diff --git a/invesalius/gui/task_exporter.py b/invesalius/gui/task_exporter.py index 7ce57d543..8e979e0d4 100644 --- a/invesalius/gui/task_exporter.py +++ b/invesalius/gui/task_exporter.py @@ -259,7 +259,7 @@ def __init_menu(self): } for id in self.id_to_name: - item = menu.Append(id, self.id_to_name[id]) + menu.Append(id, self.id_to_name[id]) self.menu_picture = menu menu.Bind(wx.EVT_MENU, self.OnMenuPicture) diff --git a/invesalius/gui/task_generic.py b/invesalius/gui/task_generic.py index c6e710db1..ef86f9321 100644 --- a/invesalius/gui/task_generic.py +++ b/invesalius/gui/task_generic.py @@ -17,8 +17,6 @@ # detalhes. # -------------------------------------------------------------------------- -import os -import sys import wx import wx.lib.hyperlink as hl diff --git a/invesalius/gui/task_importer.py b/invesalius/gui/task_importer.py index 5f8f5dd1a..0cad2ff2b 100644 --- a/invesalius/gui/task_importer.py +++ b/invesalius/gui/task_importer.py @@ -17,7 +17,6 @@ # detalhes. # -------------------------------------------------------------------------- import os -import sys import wx @@ -28,7 +27,6 @@ import wx.lib.platebtn as pbtn import invesalius.constants as const -import invesalius.gui.dialogs as dlg from invesalius import inv_paths from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher diff --git a/invesalius/gui/task_imports.py b/invesalius/gui/task_imports.py index 773ed8bef..ec62c33ae 100644 --- a/invesalius/gui/task_imports.py +++ b/invesalius/gui/task_imports.py @@ -17,11 +17,8 @@ # detalhes. # -------------------------------------------------------------------------- import wx +import wx.lib.agw.foldpanelbar as fpb -try: - import wx.lib.agw.foldpanelbar as fpb -except ModuleNotFoundError: - import wx.lib.foldpanelbar as fpb import invesalius.gui.task_efield as efield import invesalius.gui.task_exporter as exporter import invesalius.gui.task_fmrisupport as fmrisupport @@ -29,6 +26,7 @@ import invesalius.gui.task_slice as slice_ import invesalius.gui.task_surface as surface import invesalius.gui.task_tractography as tractography +from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher @@ -160,10 +158,7 @@ def __init__(self, parent): class InnerFoldPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) - try: - default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) - except AttributeError: - default_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_MENUBAR) + default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) fold_panel = fpb.FoldPanelBar( self, -1, wx.DefaultPosition, wx.DefaultSize, 0, fpb.FPB_SINGLE_FOLD ) @@ -203,7 +198,7 @@ def __init__(self, parent): "%d. %s" % (i + 1, name), collapsed=True, foldIcons=image_list ) fold_panel.ApplyCaptionStyle(item, style) - col = style.GetFirstColour() + # col = style.GetFirstColour() # Add panel to FoldPanel fold_panel.AddFoldPanelWindow( @@ -258,7 +253,7 @@ def SetStateProjectOpen(self): def OnFoldPressCaption(self, evt): id = evt.GetTag().GetId() - closed = evt.GetFoldStatus() + # closed = evt.GetFoldStatus() if id == self.__id_slice: Publisher.sendMessage("Retrieve task slice style") diff --git a/invesalius/gui/task_navigator.py b/invesalius/gui/task_navigator.py index 66633f462..fcb103725 100644 --- a/invesalius/gui/task_navigator.py +++ b/invesalius/gui/task_navigator.py @@ -29,19 +29,14 @@ mTMS() has_mTMS = True -except: +except Exception: has_mTMS = False import sys import uuid import wx - -try: - import wx.lib.agw.foldpanelbar as fpb -except ImportError: - import wx.lib.foldpanelbar as fpb - +import wx.lib.agw.foldpanelbar as fpb import wx.lib.colourselect as csel import wx.lib.masked.numctrl import wx.lib.platebtn as pbtn @@ -54,6 +49,7 @@ from invesalius import inv_paths, utils from invesalius.data.markers.marker import Marker, MarkerType from invesalius.gui.widgets.fiducial_buttons import OrderedFiducialButtons +from invesalius.i18n import tr as _ from invesalius.navigation.navigation import NavigationHub from invesalius.navigation.robot import RobotObjective from invesalius.pubsub import pub as Publisher @@ -280,7 +276,7 @@ def OnFoldPressCaption(self, evt): expanded = evt.GetFoldStatus() if id == self.__id_nav: - status = self.CheckRegistration() + status = self.CheckRegistration() # noqa: F841 if not expanded: self.fold_panel.Expand(evt.GetTag()) @@ -306,10 +302,6 @@ def OpenNavigation(self): class CoregistrationPanel(wx.Panel): def __init__(self, parent, nav_hub): wx.Panel.__init__(self, parent) - try: - default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) - except AttributeError: - default_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_MENUBAR) # Changed from default color for OSX background_colour = (255, 255, 255) self.SetBackgroundColour(background_colour) @@ -346,7 +338,8 @@ def __bind_events(self): Publisher.subscribe(self._FoldImage, "Move to image page") def OnPageChanging(self, evt): - page = evt.GetOldSelection() + # page = evt.GetOldSelection() + pass def OnPageChanged(self, evt): old_page = evt.GetOldSelection() @@ -508,9 +501,7 @@ def LoadImageFiducials(self, label, position): def GetFiducialByAttribute(self, fiducials, attribute_name, attribute_value): found = [fiducial for fiducial in fiducials if fiducial[attribute_name] == attribute_value] - assert len(found) != 0, "No fiducial found for which {} = {}".format( - attribute_name, attribute_value - ) + assert len(found) != 0, f"No fiducial found for which {attribute_name} = {attribute_value}" return found[0] def SetImageFiducial(self, fiducial_name, position): @@ -766,9 +757,7 @@ def StopRegistration(self): def GetFiducialByAttribute(self, fiducials, attribute_name, attribute_value): found = [fiducial for fiducial in fiducials if fiducial[attribute_name] == attribute_value] - assert len(found) != 0, "No fiducial found for which {} = {}".format( - attribute_name, attribute_value - ) + assert len(found) != 0, f"No fiducial found for which {attribute_name} = {attribute_value}" return found[0] def OnSetTrackerFiducial(self, fiducial_name): @@ -1476,7 +1465,6 @@ def OnStartNavigation(self): elif not self.tracker.IsTrackerInitialized(): dlg.ShowNavigationTrackerWarning(0, "choose") - errors = True else: # Prepare GUI for navigation. @@ -2854,7 +2842,7 @@ def ParseValue(self, value): def GetMarkersFromFile(self, filename, overwrite_image_fiducials): try: - with open(filename, "r") as file: + with open(filename) as file: magick_line = file.readline() assert magick_line.startswith(const.MARKER_FILE_MAGICK_STRING) version = int(magick_line.split("_")[-1]) @@ -2928,12 +2916,8 @@ def OnShowHideAllMarkers(self, evt, ctrl): def OnSaveMarkers(self, evt): prj_data = prj.Project() timestamp = time.localtime(time.time()) - stamp_date = "{:0>4d}{:0>2d}{:0>2d}".format( - timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday - ) - stamp_time = "{:0>2d}{:0>2d}{:0>2d}".format( - timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec - ) + stamp_date = f"{timestamp.tm_year:0>4d}{timestamp.tm_mon:0>2d}{timestamp.tm_mday:0>2d}" + stamp_time = f"{timestamp.tm_hour:0>2d}{timestamp.tm_min:0>2d}{timestamp.tm_sec:0>2d}" sep = "-" parts = [stamp_date, stamp_time, prj_data.name, "markers"] default_filename = sep.join(parts) + ".mkss" @@ -2952,16 +2936,16 @@ def OnSaveMarkers(self, evt): const.MARKER_FILE_MAGICK_STRING, const.CURRENT_MARKER_FILE_VERSION, ) - header_line = "%s\n" % Marker.to_csv_header() + header_line = f"{Marker.to_csv_header()}\n" data_lines = [marker.to_csv_row() + "\n" for marker in self.markers.list] try: with open(filename, "w", newline="") as file: file.writelines([version_line, header_line]) file.writelines(data_lines) file.close() - except Error as e: + except Exception as e: wx.MessageBox(_("Error writing markers file."), _("InVesalius 3")) - utils.debug(e) + utils.debug(str(e)) def OnSelectColour(self, evt, ctrl): # TODO: Make sure GetValue returns 3 numbers (without alpha) diff --git a/invesalius/gui/task_slice.py b/invesalius/gui/task_slice.py index e9ef6ccb2..4bfb1bb99 100644 --- a/invesalius/gui/task_slice.py +++ b/invesalius/gui/task_slice.py @@ -32,7 +32,6 @@ import wx.lib.platebtn as pbtn import invesalius.constants as const -import invesalius.data.mask as mask import invesalius.data.slice_ as slice_ import invesalius.gui.dialogs as dlg import invesalius.gui.widgets.gradient as grad @@ -213,7 +212,7 @@ def OnLinkNewMask(self, evt=None): try: evt.data evt = None - except: + except Exception: pass dialog = dlg.NewMask() @@ -255,7 +254,7 @@ def __init__(self, parent): self.inner_panel = inner_panel def GetMaskSelected(self): - x = self.inner_panel.GetMaskSelected() + # x = self.inner_panel.GetMaskSelected() return self.inner_panel.GetMaskSelected() @@ -342,10 +341,10 @@ def __init__(self, parent): def __calc_best_size(self, panel): parent = panel.GetParent() - q = panel.Reparent(self) + _ = panel.Reparent(self) # gbs = self.gbs - fold_panel = self.fold_panel + # fold_panel = self.fold_panel # Calculating the size # gbs.AddGrowableRow(0, 1) @@ -436,7 +435,7 @@ def OnColapsePanel(self, panel_id): pass def GetMaskSelected(self): - x = self.mask_prop_panel.GetMaskSelected() + # x = self.mask_prop_panel.GetMaskSelected() return self.mask_prop_panel.GetMaskSelected() @@ -604,16 +603,16 @@ def AddMask(self, mask): if self.combo_mask_name.IsEmpty(): self.Enable() mask_name = mask.name - mask_thresh = mask.threshold_range - mask_colour = [int(c * 255) for c in mask.colour] - index = self.combo_mask_name.Append(mask_name) + # mask_thresh = mask.threshold_range + # mask_colour = [int(c * 255) for c in mask.colour] + _ = self.combo_mask_name.Append(mask_name) # self.combo_mask_name.SetSelection(index) # self.button_colour.SetColour(mask_colour) # self.gradient.SetColour(mask_colour) # self.combo_mask_name.SetSelection(index) def GetMaskSelected(self): - x = self.combo_mask_name.GetSelection() + # x = self.combo_mask_name.GetSelection() return self.combo_mask_name.GetSelection() def SetThresholdModes(self, thresh_modes_names, default_thresh): @@ -649,7 +648,7 @@ def SetThresholdBounds(self, threshold_range): self.gradient.SetMaxRange(thresh_max) def OnComboName(self, evt): - mask_name = evt.GetString() + # mask_name = evt.GetString() mask_index = evt.GetSelection() Publisher.sendMessage("Change mask selected", index=mask_index) Publisher.sendMessage("Show mask", index=mask_index, value=True) diff --git a/invesalius/gui/task_surface.py b/invesalius/gui/task_surface.py index 9729a001c..e7c24d297 100644 --- a/invesalius/gui/task_surface.py +++ b/invesalius/gui/task_surface.py @@ -35,10 +35,8 @@ import invesalius.constants as const import invesalius.data.slice_ as slice_ import invesalius.gui.dialogs as dlg -import invesalius.project as prj -import invesalius.utils as utl from invesalius import inv_paths -from invesalius.gui.widgets.inv_spinctrl import InvFloatSpinCtrl, InvSpinCtrl +from invesalius.gui.widgets.inv_spinctrl import InvSpinCtrl from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher @@ -153,18 +151,16 @@ def OnButtonNextTask(self, evt): evt.Skip() def OnLinkNewSurface(self, evt=None): - is_pubsub = True - try: evt = evt.data evt = None - except: + except Exception: pass # import invesalius.gui.dialogs as dlg sl = slice_.Slice() - if sl.current_mask == None: + if sl.current_mask is None: dlg.InexistentMask() return @@ -495,7 +491,7 @@ def __init__(self, parent): ## MIX LINE 2 AND 3 flag_link = wx.EXPAND | wx.GROW | wx.RIGHT flag_slider = wx.EXPAND | wx.GROW | wx.LEFT | wx.TOP - flag_combo = wx.EXPAND | wx.GROW | wx.LEFT + # flag_combo = wx.EXPAND | wx.GROW | wx.LEFT fixed_sizer = wx.BoxSizer(wx.HORIZONTAL) fixed_sizer.AddMany( @@ -591,7 +587,7 @@ def InsertNewSurface(self, surface): # Publisher.sendMessage('Update surface data', (index)) def OnComboName(self, evt): - surface_name = evt.GetString() + # surface_name = evt.GetString() surface_index = evt.GetSelection() Publisher.sendMessage( "Change surface selected", surface_index=self.surface_list[surface_index][1] @@ -684,7 +680,4 @@ def __init__(self, parent): self.SetAutoLayout(1) def OnComboQuality(self, evt): - print("TODO: Send Signal - Change surface quality: %s" % (evt.GetString())) - - def OnDecimate(self, evt): - print("TODO: Send Signal - Decimate: %s" % float(self.spin.GetValue()) / 100) + print(f"TODO: Send Signal - Change surface quality: {evt.GetString()}") diff --git a/invesalius/gui/task_tools.py b/invesalius/gui/task_tools.py index 987ed9674..ca8cd1d72 100644 --- a/invesalius/gui/task_tools.py +++ b/invesalius/gui/task_tools.py @@ -20,16 +20,11 @@ import os import wx - -try: - import wx.lib.agw.hyperlink as hl -except ImportError: - import wx.lib.hyperlink as hl - +import wx.lib.agw.hyperlink as hl import wx.lib.platebtn as pbtn -import invesalius.constants as const import invesalius.constants as constants +from invesalius import inv_paths from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher @@ -114,8 +109,8 @@ def __init__(self, parent): self.Bind(wx.EVT_BUTTON, self.OnButton) # Tags and grid sizer for fixed items - flag_link = wx.EXPAND | wx.GROW | wx.LEFT | wx.TOP - flag_button = wx.EXPAND | wx.GROW + # flag_link = wx.EXPAND | wx.GROW | wx.LEFT | wx.TOP + # flag_button = wx.EXPAND | wx.GROW sizer = wx.GridBagSizer(hgap=0, vgap=0) sizer.Add(txt_measure, pos=(0, 0), flag=wx.GROW | wx.EXPAND | wx.TOP, border=3) diff --git a/invesalius/gui/task_tractography.py b/invesalius/gui/task_tractography.py index a338a6773..0443124a9 100644 --- a/invesalius/gui/task_tractography.py +++ b/invesalius/gui/task_tractography.py @@ -36,19 +36,13 @@ mTMS() has_mTMS = True -except: +except Exception: has_mTMS = False -import wx - -try: - import wx.lib.agw.foldpanelbar as fpb -except ImportError: - import wx.lib.foldpanelbar as fpb - import multiprocessing from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait +import wx import wx.lib.agw.genericmessagedialog as GMD import wx.lib.masked.numctrl @@ -60,7 +54,7 @@ import invesalius.gui.dialogs as dlg import invesalius.project as prj import invesalius.utils as utils -from invesalius import inv_paths +from invesalius.i18n import tr as _ from invesalius.pubsub import pub as Publisher @@ -82,10 +76,8 @@ def __init__(self, parent): class InnerTaskPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) - try: - default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) - except AttributeError: - default_colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_MENUBAR) + default_colour = wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENUBAR) + self.SetBackgroundColour(default_colour) self.affine = np.identity(4) @@ -112,28 +104,28 @@ def __init__(self, parent): tooltip = _("Load FOD") btn_load = wx.Button(self, -1, _("FOD"), size=wx.Size(50, 23)) btn_load.SetToolTip(tooltip) - btn_load.Enable(1) + btn_load.Enable(True) btn_load.Bind(wx.EVT_BUTTON, self.OnLinkFOD) # Button for loading Trekker configuration tooltip = _("Load Trekker configuration parameters") btn_load_cfg = wx.Button(self, -1, _("Configure"), size=wx.Size(65, 23)) btn_load_cfg.SetToolTip(tooltip) - btn_load_cfg.Enable(1) + btn_load_cfg.Enable(True) btn_load_cfg.Bind(wx.EVT_BUTTON, self.OnLoadParameters) # Button for creating peel tooltip = _("Create peel") btn_mask = wx.Button(self, -1, _("Peel"), size=wx.Size(50, 23)) btn_mask.SetToolTip(tooltip) - btn_mask.Enable(1) + btn_mask.Enable(True) btn_mask.Bind(wx.EVT_BUTTON, self.OnCreatePeel) # Button for creating new coil tooltip = _("Load anatomical labels") btn_act = wx.Button(self, -1, _("ACT"), size=wx.Size(50, 23)) btn_act.SetToolTip(tooltip) - btn_act.Enable(1) + btn_act.Enable(True) btn_act.Bind(wx.EVT_BUTTON, self.OnLoadACT) # Create a horizontal sizer to represent button save @@ -146,7 +138,7 @@ def __init__(self, parent): # Change peeling depth text_peel_depth = wx.StaticText(self, -1, _("Peeling depth (mm):")) spin_peel_depth = wx.SpinCtrl(self, -1, "", size=wx.Size(50, 23)) - spin_peel_depth.Enable(1) + spin_peel_depth.Enable(True) spin_peel_depth.SetRange(0, const.MAX_PEEL_DEPTH) spin_peel_depth.SetValue(const.PEEL_DEPTH) spin_peel_depth.Bind(wx.EVT_TEXT, partial(self.OnSelectPeelingDepth, ctrl=spin_peel_depth)) @@ -157,7 +149,7 @@ def __init__(self, parent): # Change number of tracts text_ntracts = wx.StaticText(self, -1, _("Number tracts:")) spin_ntracts = wx.SpinCtrl(self, -1, "", size=wx.Size(50, 23)) - spin_ntracts.Enable(1) + spin_ntracts.Enable(True) spin_ntracts.SetRange(1, 2000) spin_ntracts.SetValue(const.N_TRACTS) spin_ntracts.Bind(wx.EVT_TEXT, partial(self.OnSelectNumTracts, ctrl=spin_ntracts)) @@ -166,7 +158,7 @@ def __init__(self, parent): # Change seed offset for computing tracts text_offset = wx.StaticText(self, -1, _("Seed offset (mm):")) spin_offset = wx.SpinCtrlDouble(self, -1, "", size=wx.Size(50, 23), inc=0.1) - spin_offset.Enable(1) + spin_offset.Enable(True) spin_offset.SetRange(0, 100.0) spin_offset.SetValue(self.seed_offset) spin_offset.Bind(wx.EVT_TEXT, partial(self.OnSelectOffset, ctrl=spin_offset)) @@ -176,7 +168,7 @@ def __init__(self, parent): # Change seed radius for computing tracts text_radius = wx.StaticText(self, -1, _("Seed radius (mm):")) spin_radius = wx.SpinCtrlDouble(self, -1, "", size=wx.Size(50, 23), inc=0.1) - spin_radius.Enable(1) + spin_radius.Enable(True) spin_radius.SetRange(0, 100.0) spin_radius.SetValue(self.seed_radius) spin_radius.Bind(wx.EVT_TEXT, partial(self.OnSelectRadius, ctrl=spin_radius)) @@ -195,7 +187,7 @@ def __init__(self, parent): # Change opacity of brain mask visualization text_opacity = wx.StaticText(self, -1, _("Brain opacity:")) spin_opacity = wx.SpinCtrlDouble(self, -1, "", size=wx.Size(50, 23), inc=0.1) - spin_opacity.Enable(0) + spin_opacity.Enable(False) spin_opacity.SetRange(0, 1.0) spin_opacity.SetValue(self.brain_opacity) spin_opacity.Bind(wx.EVT_TEXT, partial(self.OnSelectOpacity, ctrl=spin_opacity)) @@ -251,21 +243,21 @@ def __init__(self, parent): # Check box to enable tract visualization checktracts = wx.CheckBox(self, -1, _("Enable tracts")) checktracts.SetValue(False) - checktracts.Enable(0) + checktracts.Enable(False) checktracts.Bind(wx.EVT_CHECKBOX, partial(self.OnEnableTracts, ctrl=checktracts)) self.checktracts = checktracts # Check box to enable surface peeling checkpeeling = wx.CheckBox(self, -1, _("Peel surface")) checkpeeling.SetValue(False) - checkpeeling.Enable(0) + checkpeeling.Enable(False) checkpeeling.Bind(wx.EVT_CHECKBOX, partial(self.OnShowPeeling, ctrl=checkpeeling)) self.checkpeeling = checkpeeling # Check box to enable tract visualization checkACT = wx.CheckBox(self, -1, _("ACT")) checkACT.SetValue(False) - checkACT.Enable(0) + checkACT.Enable(False) checkACT.Bind(wx.EVT_CHECKBOX, partial(self.OnEnableACT, ctrl=checkACT)) self.checkACT = checkACT @@ -418,7 +410,7 @@ def OnCreatePeel(self, event=None): self.tp.running = False t_end = time.time() - print("Elapsed time - {}".format(t_end - t_init)) + print(f"Elapsed time - {t_end - t_init}") self.tp.Close() if self.tp.error: dlgg = GMD.GenericMessageDialog( @@ -488,7 +480,7 @@ def OnLinkFOD(self, event=None): self.TrekkerCallback(completed_future) t_end = time.time() - print("Elapsed time - {}".format(t_end - t_init)) + print(f"Elapsed time - {t_end - t_init}") self.tp.Close() if self.tp.error: dlgg = GMD.GenericMessageDialog( @@ -497,7 +489,7 @@ def OnLinkFOD(self, event=None): dlgg.ShowModal() del self.tp wx.MessageBox(_("FOD Import successful"), _("InVesalius 3")) - except: + except Exception: Publisher.sendMessage( "Update status text in GUI", label=_("Trekker initialization failed.") ) @@ -508,11 +500,11 @@ def OnLinkFOD(self, event=None): def TrekkerCallback(self, trekker): self.tp.running = False print("Import Complete") - if trekker != None: + if trekker is not None: self.trekker = trekker.result() self.trekker, n_threads = dti.set_trekker_parameters(self.trekker, self.trekker_cfg) - self.checktracts.Enable(1) + self.checktracts.Enable(True) self.checktracts.SetValue(True) self.view_tracts = True @@ -556,7 +548,7 @@ def OnLoadACT(self, event=None): self.tp.running = False t_end = time.time() - print("Elapsed time - {}".format(t_end - t_init)) + print(f"Elapsed time - {t_end - t_init}") self.tp.Close() if self.tp.error: dlgg = GMD.GenericMessageDialog( @@ -564,7 +556,7 @@ def OnLoadACT(self, event=None): ) dlgg.ShowModal() del self.tp - self.checkACT.Enable(1) + self.checkACT.Enable(True) self.checkACT.SetValue(True) Publisher.sendMessage("Update ACT data", data=self.act_data_arr) Publisher.sendMessage("Enable ACT", data=True) @@ -572,7 +564,7 @@ def OnLoadACT(self, event=None): "Update status text in GUI", label=_("Trekker ACT loaded") ) wx.MessageBox(_("ACT Import successful"), _("InVesalius 3")) - except: + except Exception: Publisher.sendMessage( "Update status text in GUI", label=_("ACT initialization failed.") ) @@ -646,14 +638,14 @@ def OnCloseProject(self): self.trekker_cfg = const.TREKKER_CONFIG self.checktracts.SetValue(False) - self.checktracts.Enable(0) + self.checktracts.Enable(False) self.checkpeeling.SetValue(False) - self.checkpeeling.Enable(0) + self.checkpeeling.Enable(False) self.checkACT.SetValue(False) - self.checkACT.Enable(0) + self.checkACT.Enable(False) self.spin_opacity.SetValue(const.BRAIN_OPACITY) - self.spin_opacity.Enable(0) + self.spin_opacity.Enable(False) Publisher.sendMessage("Update peel", flag=False, actor=self.brain_actor) self.peel_depth = const.PEEL_DEPTH diff --git a/invesalius/gui/utils.py b/invesalius/gui/utils.py index 10aaaa7cd..72d7483cb 100644 --- a/invesalius/gui/utils.py +++ b/invesalius/gui/utils.py @@ -16,10 +16,12 @@ # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. # -------------------------------------------------------------------- +from typing import TYPE_CHECKING -import wx +if TYPE_CHECKING: + import wx -def calc_width_needed(widget, num_chars): +def calc_width_needed(widget: "wx.Window", num_chars: int) -> int: width, height = widget.GetTextExtent("M" * num_chars) return width diff --git a/invesalius/gui/widgets/canvas_renderer.py b/invesalius/gui/widgets/canvas_renderer.py index 84737a04e..c1e3306f7 100644 --- a/invesalius/gui/widgets/canvas_renderer.py +++ b/invesalius/gui/widgets/canvas_renderer.py @@ -421,7 +421,7 @@ def OnPaint(self, evt: wx.Event, obj: Any) -> None: self._ordered_draw_list = sorted(self._follow_draw_list(), key=lambda x: x[0]) for ( - l, + _, d, ) in ( self._ordered_draw_list diff --git a/invesalius/i18n.py b/invesalius/i18n.py index bf3e588b4..3de9095b6 100644 --- a/invesalius/i18n.py +++ b/invesalius/i18n.py @@ -24,7 +24,7 @@ import locale import os import sys -from typing import Optional +from typing import Callable, Optional import invesalius.utils as utl from invesalius.inv_paths import LOCALE_DIR @@ -71,10 +71,12 @@ def GetLocaleOS() -> Optional[str]: return locale.getdefaultlocale()[0] -def InstallLanguage(language: str): +def InstallLanguage(language: str) -> Callable[[str], str]: file_path = os.path.split(__file__)[0] language_dir = LOCALE_DIR - if hasattr(sys, "frozen") and (sys.frozen == "windows_exe" or sys.frozen == "console_exe"): # type: ignore + if hasattr(sys, "frozen") and ( + getattr(sys, "frozen") == "windows_exe" or getattr(sys, "frozen") == "console_exe" + ): abs_file_path = os.path.abspath(file_path + os.sep + "..") abs_file_path = os.path.abspath(abs_file_path + os.sep + ".." + os.sep + "..") language_dir = os.path.join(abs_file_path, "locale") @@ -86,13 +88,8 @@ def InstallLanguage(language: str): lang = gettext.translation("invesalius", language_dir, languages=[language]) - # Using unicode - try: - lang.install(unicode=1) - return lang.ugettext - except TypeError: - lang.install() - return lang.gettext + lang.install() + return lang.gettext class Translator: diff --git a/invesalius/inv_paths.py b/invesalius/inv_paths.py index 80e45d642..0839602b0 100644 --- a/invesalius/inv_paths.py +++ b/invesalius/inv_paths.py @@ -52,7 +52,7 @@ # Inside the windows executable if hasattr(sys, "frozen") and ( - sys.frozen == "windows_exe" or sys.frozen == "console_exe" # type: ignore + getattr(sys, "frozen") == "windows_exe" or getattr(sys, "frozen") == "console_exe" ): abs_path = INV_TOP_DIR.parent.resolve() ICON_DIR = abs_path.joinpath("icons") diff --git a/invesalius/navigation/image.py b/invesalius/navigation/image.py index 4ff2563dc..b60693e69 100644 --- a/invesalius/navigation/image.py +++ b/invesalius/navigation/image.py @@ -62,7 +62,7 @@ def SetImageFiducial(self, fiducial_index, position): self.fiducials[fiducial_index, :] = position self.UpdateFiducialMarker(fiducial_index) - print("Image fiducial {} set to coordinates {}".format(fiducial_index, position)) + print(f"Image fiducial {fiducial_index} set to coordinates {position}") ses.Session().ChangeProject() self.SaveState() diff --git a/invesalius/navigation/iterativeclosestpoint.py b/invesalius/navigation/iterativeclosestpoint.py index 683b09437..eb513eb5a 100644 --- a/invesalius/navigation/iterativeclosestpoint.py +++ b/invesalius/navigation/iterativeclosestpoint.py @@ -108,4 +108,4 @@ def ResetICP(self): self.SaveState() def GetFreForUI(self): - return "{:.2f}".format(self.icp_fre) if self.icp_fre else "" + return f"{self.icp_fre:.2f}" if self.icp_fre else "" diff --git a/invesalius/navigation/markers.py b/invesalius/navigation/markers.py index 05f5d5e6b..63f7c379a 100644 --- a/invesalius/navigation/markers.py +++ b/invesalius/navigation/markers.py @@ -22,7 +22,7 @@ import invesalius.session as ses from invesalius.data.markers.marker import Marker, MarkerType from invesalius.data.markers.marker_transformator import MarkerTransformator -from invesalius.navigation.robot import Robot, RobotObjective +from invesalius.navigation.robot import RobotObjective from invesalius.pubsub import pub as Publisher from invesalius.utils import Singleton diff --git a/invesalius/navigation/mtms.py b/invesalius/navigation/mtms.py index f6daeac6e..ee8b72bf6 100644 --- a/invesalius/navigation/mtms.py +++ b/invesalius/navigation/mtms.py @@ -71,7 +71,7 @@ def UpdateTarget(self, coil_pose, brain_target): "coil_pose(nav)": coil_pose_flip, "intensity": self.intensity, } - self.df = self.df.append((pd.DataFrame([new_row], columns=self.df.columns))) + self.df = self.df.append(pd.DataFrame([new_row], columns=self.df.columns)) else: print("Target is not valid. The offset is: ", offset) @@ -84,13 +84,13 @@ def GetOffset(self, distance): def FindmTMSParameters(self, offset): # fname = "C:\\mTMS\\mTMS parameters\\PP\\PP31 mikael 1mm 15deg 5-coil grid.txt" fname = self.vi.GetControlValue("Get Pulse-parameters file") - with open(fname, "r") as the_file: + with open(fname) as the_file: all_data = [line.strip() for line in the_file.readlines()] data = all_data[18:] data = np.array([line.split("\t") for line in data]) separator = "_" - target = separator.join(["{}".format(x) for x in offset]) + target = separator.join([f"{x}" for x in offset]) target_index = np.where(data[:, 0] == target) return target, target_index @@ -119,12 +119,8 @@ def SendToMTMS(self, target): def SaveSequence(self): timestamp = time.localtime(time.time()) - stamp_date = "{:0>4d}{:0>2d}{:0>2d}".format( - timestamp.tm_year, timestamp.tm_mon, timestamp.tm_mday - ) - stamp_time = "{:0>2d}{:0>2d}{:0>2d}".format( - timestamp.tm_hour, timestamp.tm_min, timestamp.tm_sec - ) + stamp_date = f"{timestamp.tm_year:0>4d}{timestamp.tm_mon:0>2d}{timestamp.tm_mday:0>2d}" + stamp_time = f"{timestamp.tm_hour:0>2d}{timestamp.tm_min:0>2d}{timestamp.tm_sec:0>2d}" sep = "_" parts = [stamp_date, stamp_time, self.log_name, "sequence"] default_filename = sep.join(parts) + ".csv" diff --git a/invesalius/navigation/navigation.py b/invesalius/navigation/navigation.py index 54d8e87ee..4a5cc9563 100644 --- a/invesalius/navigation/navigation.py +++ b/invesalius/navigation/navigation.py @@ -35,8 +35,8 @@ import invesalius.data.vtk_utils as vtk_utils import invesalius.project as prj import invesalius.session as ses -import invesalius.utils as utils from invesalius.data.markers.marker import MarkerType +from invesalius.i18n import tr as _ from invesalius.navigation.image import Image from invesalius.navigation.iterativeclosestpoint import IterativeClosestPoint from invesalius.navigation.markers import MarkersControl diff --git a/invesalius/navigation/robot.py b/invesalius/navigation/robot.py index 5af163d7e..cc3551b04 100644 --- a/invesalius/navigation/robot.py +++ b/invesalius/navigation/robot.py @@ -21,14 +21,11 @@ import numpy as np import wx -from wx import ID_OK -import invesalius.constants as const import invesalius.data.coregistration as dcr import invesalius.gui.dialogs as dlg import invesalius.session as ses from invesalius.i18n import tr as _ -from invesalius.navigation.tracker import Tracker from invesalius.pubsub import pub as Publisher from invesalius.utils import Singleton diff --git a/invesalius/navigation/tracker.py b/invesalius/navigation/tracker.py index b5d290711..051654569 100644 --- a/invesalius/navigation/tracker.py +++ b/invesalius/navigation/tracker.py @@ -212,9 +212,7 @@ def SetTrackerFiducial(self, ref_mode_id, fiducial_index): # Update tracker fiducial with tracker coordinates self.tracker_fiducials[fiducial_index, :] = coord[0:3] - assert 0 <= fiducial_index <= 2, "Fiducial index out of range (0-2): {}".format( - fiducial_index - ) + assert 0 <= fiducial_index <= 2, f"Fiducial index out of range (0-2): {fiducial_index}" self.tracker_fiducials_raw[2 * fiducial_index, :] = coord_raw[0, :] self.tracker_fiducials_raw[2 * fiducial_index + 1, :] = coord_raw[1, :] @@ -226,7 +224,7 @@ def SetTrackerFiducial(self, ref_mode_id, fiducial_index): coord_raw, 1 ) - print("Set tracker fiducial {} to coordinates {}.".format(fiducial_index, coord[0:3])) + print(f"Set tracker fiducial {fiducial_index} to coordinates {coord[0:3]}.") self.SaveState() diff --git a/invesalius/project.py b/invesalius/project.py index b730e6a9a..6d1ca0af6 100644 --- a/invesalius/project.py +++ b/invesalius/project.py @@ -31,7 +31,8 @@ import invesalius.constants as const from invesalius import inv_paths -from invesalius.data import imagedata_utils + +# from invesalius.data import imagedata_utils from invesalius.presets import Presets from invesalius.pubsub import pub as Publisher from invesalius.utils import Singleton, TwoWaysDictionary, debug, decode @@ -386,8 +387,8 @@ def create_project_file( folder = tempfile.mkdtemp() if not os.path.exists(folder): os.mkdir(folder) - image_file = os.path.join(folder, "matrix.dat") - image_mmap = imagedata_utils.array2memmap(image, image_file) + # image_file = os.path.join(folder, "matrix.dat") + # image_mmap = imagedata_utils.array2memmap(image, image_file) matrix = {"filename": "matrix.dat", "shape": image.shape, "dtype": str(image.dtype)} project = { # Format info diff --git a/invesalius/reader/bitmap_reader.py b/invesalius/reader/bitmap_reader.py index dda01bbbe..bafe2a530 100644 --- a/invesalius/reader/bitmap_reader.py +++ b/invesalius/reader/bitmap_reader.py @@ -21,8 +21,6 @@ import re import sys import tempfile -import threading -from multiprocessing import cpu_count import numpy import wx @@ -67,7 +65,7 @@ def __init__(self, klass): self.instance = None def __call__(self, *args, **kwds): - if self.instance == None: + if self.instance is None: self.instance = self.klass(*args, **kwds) return self.instance @@ -177,7 +175,7 @@ def run(self): img.SetAxisMagnificationFactor(2, 1) img.Update() - tp = img.GetOutput().GetScalarTypeAsString() + # tp = img.GetOutput().GetScalarTypeAsString() image_copy = vtkImageData() image_copy.DeepCopy(img.GetOutput()) @@ -309,7 +307,7 @@ def ScipyRead(filepath): return simage else: return r - except IOError: + except OSError: return False @@ -369,7 +367,7 @@ def ReadBitmap(filepath): if _has_win32api: filepath = win32api.GetShortPathName(filepath) - if t == False: + if t is False: try: measures_info = GetPixelSpacingFromInfoFile(filepath) except UnicodeDecodeError: @@ -382,7 +380,7 @@ def ReadBitmap(filepath): img_array = VtkRead(filepath, t) if not (isinstance(img_array, numpy.ndarray)): - no_error = True + # no_error = True img_array = ScipyRead(filepath) @@ -399,12 +397,12 @@ def GetPixelSpacingFromInfoFile(filepath): return False try: - fi = open(filepath, "r") + fi = open(filepath) lines = fi.readlines() except UnicodeDecodeError: # fix uCTI from CTI file try: - fi = open(filepath, "r", encoding="iso8859-1") + fi = open(filepath, encoding="iso8859-1") lines = fi.readlines() except UnicodeDecodeError: return False @@ -424,12 +422,12 @@ def GetPixelSpacingFromInfoFile(filepath): return [spx * 0.001, spy * 0.001, spz * 0.001] else: # info text from skyscan - for l in lines: - if "Pixel Size" in l: - if "um" in l: + for line in lines: + if "Pixel Size" in line: + if "um" in line: measure_scale = "um" - value = l.split("=")[-1] + value = line.split("=")[-1] values.append(value) if len(values) > 0: @@ -466,5 +464,5 @@ def VerifyDataType(filepath): return t else: return False - except IOError: + except OSError: return False diff --git a/invesalius/reader/dicom.py b/invesalius/reader/dicom.py index 87225ba88..8bbe45815 100644 --- a/invesalius/reader/dicom.py +++ b/invesalius/reader/dicom.py @@ -17,10 +17,10 @@ # PARTICULAR. Consulte a Licenca Publica Geral GNU para obter mais # detalhes. # --------------------------------------------------------------------- -# import gdcm -import sys import time +import gdcm + import invesalius.constants as const import invesalius.utils as utils from invesalius.i18n import tr as _ @@ -325,28 +325,15 @@ def GetAccessionNumber(self): DICOM standard tag (0x0008, 0x0050) was used. """ - # data = self.data_image[0x008][0x050] - return "" - if data: - try: - value = int(str(data)) - except ValueError: # Problem in the other\iCatDanielaProjeto - value = 0 - return value - return "" - - def GetAcquisitionTime(self): - """ - Return string containing the acquisition time using the - format "hh:mm:ss". - Return "" (empty string) if not set. - - DICOM standard tag (0x0008,0x0032) was used. - """ - data = self.data_image[str(0x008)][str(0x032)] - if (data) and (data != ""): - return self.__format_time(str(data)) return "" + # data = self.data_image[0x008][0x050] + # if data: + # try: + # value = int(str(data)) + # except ValueError: # Problem in the other\iCatDanielaProjeto + # value = 0 + # return value + # return "" def GetPatientAdmittingDiagnosis(self): """ @@ -782,22 +769,6 @@ def GetPhysicianeReferringTelephone(self): return data return "" - def GetProtocolName(self): - """ - Return string containing the protocal name - used in the acquisition - - DICOM standard tag (0x0018, 0x1030) was used. - """ - try: - data = self.data_image[str(0x0018)][str(0x1030)] - except KeyError: - return None - - if data: - return data - return None - def GetImageType(self): """ Return list containing strings related to image origin. @@ -857,23 +828,6 @@ def GetSOPInstanceUID(self): return data return "" - def GetStudyInstanceUID(self): - """ - Return string containing Unique Identifier of the - Study Instance. - Return "" if field is not defined. - - Critical DICOM Tag (0x0020,0x000D). Cannot be edited. - """ - try: - data = self.data_image[str(0x0020)][str(0x000D)] - except KeyError: - return "" - - if data: - return data - return "" - def GetImagePatientOrientation(self): """ Return matrix [x0, x1, x2, y0, y1, y2] related to patient @@ -1646,11 +1600,10 @@ class DicomWriter: """ def __init__(self): - self.reader = "" self.anony = gdcm.Anonymizer() self.path = "" - self.new_dicom = vtkgdcm.vtkGDCMImageWriter() - reader = self.reader = gdcm.Reader() + self.new_dicom = vtkgdcm.vtkGDCMImageWriter() # noqa: F821 + self.reader = gdcm.Reader() def SetFileName(self, path): """ @@ -1693,7 +1646,7 @@ def SaveIsNew(self, img_data): self.anony.SetFile(self.reader.GetFile()) def Save(self): - reader = self.reader + # reader = self.reader writer = gdcm.Writer() writer.SetFile(self.reader.GetFile()) @@ -1728,7 +1681,7 @@ def SetImageLocation(self, location): """ Set slice location value requeries float type """ - self.anony.Replace(gdcm.Tag(0x0020, 0x1041), str(number)) + self.anony.Replace(gdcm.Tag(0x0020, 0x1041), str(location)) def SetImagePosition(self, position): """ @@ -1842,7 +1795,7 @@ def DumpDictionary(filename, dictionary=info): # print info -class Dicom(object): +class Dicom: def __init__(self): pass @@ -1867,7 +1820,7 @@ def LoadAcquisitionInfo(self): self.acquisition.SetParser(self.parser) -class Patient(object): +class Patient: def __init__(self): pass @@ -1880,7 +1833,7 @@ def SetParser(self, parser): self.physician = parser.GetPhysicianReferringName() -class Acquisition(object): +class Acquisition: def __init__(self): pass @@ -1901,7 +1854,7 @@ def SetParser(self, parser): self.sop_class_uid = parser.GetSOPClassUID() -class Image(object): +class Image: def __init__(self): pass diff --git a/invesalius/reader/dicom_grouper.py b/invesalius/reader/dicom_grouper.py index 82d55cef9..0930aa7c4 100644 --- a/invesalius/reader/dicom_grouper.py +++ b/invesalius/reader/dicom_grouper.py @@ -99,7 +99,7 @@ def AddSlice(self, dicom): # Case to test: \other\higroma # condition created, if any dicom with the same # position, but 3D, leaving the same series. - if not "DERIVED" in dicom.image.type: + if "DERIVED" not in dicom.image.type: # if any dicom with the same position if pos not in self.slices_dict.keys(): self.slices_dict[pos] = dicom @@ -138,7 +138,7 @@ def GetFilenameList(self): sorter.SetZSpacingTolerance(1e-10) try: sorter.Sort([utils.encode(i, const.FS_ENCODE) for i in filelist]) - except TypeError as e: + except TypeError: sorter.Sort(filelist) filelist = sorter.GetFilenames() @@ -152,8 +152,8 @@ def GetHandSortedList(self): # This will be used to fix problem 1, after merging # single DicomGroups of same study_id and orientation list_ = list(self.slices_dict.values()) - dicom = list_[0] - axis = ORIENT_MAP[dicom.image.orientation_label] + # dicom = list_[0] + # axis = ORIENT_MAP[dicom.image.orientation_label] # list_ = sorted(list_, key = lambda dicom:dicom.image.position[axis]) list_ = sorted(list_, key=lambda dicom: dicom.image.number) return list_ @@ -311,7 +311,7 @@ def FixProblem1(self, dict): axis = ORIENT_MAP[group_key[0]] # based on orientation for index in range(len(sorted_list) - 1): current = sorted_list[index] - next = sorted_list[index + 1] + # next = sorted_list[index + 1] pos_current = current.image.position[axis] pos_next = current.image.position[axis] diff --git a/invesalius/reader/dicom_reader.py b/invesalius/reader/dicom_reader.py index 1fd4f21d5..b0297f2b2 100644 --- a/invesalius/reader/dicom_reader.py +++ b/invesalius/reader/dicom_reader.py @@ -18,9 +18,6 @@ # -------------------------------------------------------------------------- import os import sys -import tempfile -import threading -from multiprocessing import cpu_count import gdcm @@ -31,15 +28,12 @@ except AttributeError: pass -import glob -import plistlib from vtkmodules.vtkCommonCore import vtkFileOutputWindow, vtkOutputWindow import invesalius.constants as const import invesalius.reader.dicom as dicom import invesalius.reader.dicom_grouper as dicom_grouper -import invesalius.session as ses import invesalius.utils as utils from invesalius import inv_paths from invesalius.data import imagedata_utils @@ -56,24 +50,6 @@ _has_win32api = False -def ReadDicomGroup(dir_): - patient_group = GetDicomGroups(dir_) - if len(patient_group) > 0: - filelist, dicom, zspacing = SelectLargerDicomGroup(patient_group) - filelist = SortFiles(filelist, dicom) - size = dicom.image.size - bits = dicom.image.bits_allocad - - imagedata = CreateImageData(filelist, zspacing, size, bits) - - session = ses.Session() - session.SetConfig("project_status", const.PROJECT_STATUS_NEW) - - return imagedata, dicom - else: - return False - - def SelectLargerDicomGroup(patient_group): maxslices = 0 for patient in patient_group: @@ -137,7 +113,6 @@ def run(self): stf = gdcm.StringFilter() stf.SetFile(file) - field_dict = {} data_dict = {} tag = gdcm.Tag(0x0008, 0x0005) @@ -175,7 +150,7 @@ def run(self): tag_labels[stag] = data[0] - if not group in data_dict.keys(): + if group not in data_dict.keys(): data_dict[group] = {} if not (utils.VerifyInvalidPListCharacter(data[1])): @@ -200,7 +175,7 @@ def run(self): tag_labels[stag] = data[0] - if not group in data_dict.keys(): + if group not in data_dict.keys(): data_dict[group] = {} if not (utils.VerifyInvalidPListCharacter(data[1])): diff --git a/invesalius/segmentation/deep_learning/segment.py b/invesalius/segmentation/deep_learning/segment.py index 2e296a37e..9d319977f 100644 --- a/invesalius/segmentation/deep_learning/segment.py +++ b/invesalius/segmentation/deep_learning/segment.py @@ -1,19 +1,15 @@ import itertools import multiprocessing import os -import pathlib -import sys import tempfile import traceback import numpy as np from skimage.transform import resize -from vtkmodules.vtkIOXML import vtkXMLImageDataWriter import invesalius.data.slice_ as slc from invesalius import inv_paths from invesalius.data import imagedata_utils -from invesalius.data.converters import to_vtk from invesalius.net.utils import download_url_to_file from invesalius.utils import new_name_by_pattern @@ -76,7 +72,7 @@ def segment_keras(image, weights_file, overlap, probability_array, comm_array, p import keras # Loading model - with open(weights_file, "r") as json_file: + with open(weights_file) as json_file: model = keras.models.model_from_json(json_file.read()) model.load_weights(str(weights_file.parent.joinpath("model.h5"))) model.compile("Adam", "binary_crossentropy") diff --git a/invesalius/utils.py b/invesalius/utils.py index a736fd2ad..84365b777 100644 --- a/invesalius/utils.py +++ b/invesalius/utils.py @@ -25,7 +25,7 @@ import time import traceback from functools import wraps -from typing import Any, List, Optional, Tuple +from typing import Any, List, Optional import numpy as np from packaging.version import Version @@ -102,11 +102,11 @@ def next_copy_name(original_name: str, names_list: List[str]) -> str: # yes, lets check if it ends with a number if isinstance(eval(parts[-1]), int): last_index = int(parts[-1]) - 1 - first_copy = "%s copy" % parts[0] + first_copy = f"{parts[0]} copy" # no... well, so will build the copy name from zero else: last_index = -1 - first_copy = "%s copy" % original_name + first_copy = f"{original_name} copy" # apparently this isthe new copy name, check it if first_copy not in names_list: return first_copy @@ -115,7 +115,7 @@ def next_copy_name(original_name: str, names_list: List[str]) -> str: # no, apparently there are no copies, as # separator was not found -- returned ("", " copy#", "") last_index = -1 - first_copy = "%s copy" % original_name + first_copy = f"{original_name} copy" # apparently this isthe new copy name, check it if first_copy not in names_list: @@ -298,98 +298,6 @@ def calculate_resizing_tofitmemory(x_size, y_size, n_slices, byte): return round(resize, 2) -# DEPRECATED -def predict_memory(nfiles: int, x: int, y: int, p: int) -> Tuple[float, float]: - """ - Predict how much memory will be used, giving the following - information: - nfiles: number of dicom files - x, y: dicom image size - p: bits allocated for each pixel sample - """ - m = nfiles * (x * y * p) - # physical_memory in Byte - physical_memory = get_physical_memory() - - if sys.platform == "win32": - if platform.architecture()[0] == "32bit": - # (314859200 = 300 MB) - # (26999999 = 25 MB) - # case occupy more than 300 MB image is reduced to 1.5, - # and 25 MB each image is resized 0.04. - if m >= 314859200: - porcent = 1.5 + (m - 314859200) / 26999999 * 0.04 - else: - return (x, y) - else: # 64 bits architecture - # 2147483648 byte = 2.0 GB - # 4294967296 byte = 4.0 GB - - if (physical_memory <= 2147483648) and (nfiles <= 1200): - porcent = 1.5 + (m - 314859200) / 26999999 * 0.04 - - elif (physical_memory <= 2147483648) and (nfiles > 1200): - porcent = 1.5 + (m - 314859200) / 26999999 * 0.05 - - elif ( - (physical_memory > 2147483648) - and (physical_memory <= 4294967296) - and (nfiles <= 1200) - ): - porcent = 1.5 + (m - 314859200) / 26999999 * 0.02 - - else: - return (x, y) - - return (x / porcent, y / porcent) - - elif sys.platform.startswith("linux"): - if platform.architecture()[0] == "32bit": - # 839000000 = 800 MB - if (m <= 839000000) and (physical_memory <= 2147483648): - return (x, y) - elif (m > 839000000) and (physical_memory <= 2147483648) and (nfiles <= 1200): - porcent = 1.5 + (m - 314859200) / 26999999 * 0.02 - else: - return (x, y) - - else: - if (m <= 839000000) and (physical_memory <= 2147483648): - return (x, y) - elif (m > 839000000) and (physical_memory <= 2147483648) and (nfiles <= 1200): - porcent = 1.5 + (m - 314859200) / 26999999 * 0.02 - else: - return (x, y) - - return (x / porcent, y / porcent) - - elif sys.platform == "darwin": - return (x / 2, y / 2) - raise Exception("Platform not supported") - - -# def convert_bytes(bytes): -# if bytes >= 1073741824: -# return str(bytes / 1024 / 1024 / 1024) + ' GB' -# elif bytes >= 1048576: -# return str(bytes / 1024 / 1024) + ' MB' -# elif bytes >= 1024: -# return str(bytes / 1024) + ' KB' -# elif bytes < 1024: -# return str(bytes) + ' bytes' - - -# DEPRECATED -def get_physical_memory(): - """ - Return physical memory in bytes - """ - sg = sigar.open() - mem = sg.mem() - sg.close() - return int(mem.total()) - - def get_system_encoding() -> Optional[str]: if sys.platform == "win32": return locale.getdefaultlocale()[1] diff --git a/pyproject.toml b/pyproject.toml index 1c73cbcc0..dfbe93231 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -93,6 +93,7 @@ line-length = 100 [tool.ruff.lint] extend-select = ["UP","I"] # Introduces linting rules for pyupgrade and isort +extend-ignore = ["E731"] [tool.ruff.format] line-ending = "lf" diff --git a/setup.py b/setup.py index 1df96d88f..8e0537f3c 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,3 @@ -import logging import os import pathlib import subprocess @@ -60,7 +59,7 @@ def run(self): plugins_folder = inv_folder.joinpath("plugins") for p in compilable_plugins: plugin_folder = plugins_folder.joinpath(p) - self.announce("Compiling plugin: {}".format(p)) + self.announce(f"Compiling plugin: {p}") os.chdir(plugin_folder) subprocess.check_call([sys.executable, "setup.py", "build_ext", "--inplace"]) os.chdir(inv_folder) diff --git a/typings/wx-stubs/__init__.pyi b/typings/wx-stubs/__init__.pyi index bb67a43fa..0fc537e18 100644 --- a/typings/wx-stubs/__init__.pyi +++ b/typings/wx-stubs/__init__.pyi @@ -1 +1 @@ -from .core import * +from .core import * # noqa: F403 diff --git a/typings/wx-stubs/core.pyi b/typings/wx-stubs/core.pyi index da0b0dd6d..8026cd836 100644 --- a/typings/wx-stubs/core.pyi +++ b/typings/wx-stubs/core.pyi @@ -24,7 +24,10 @@ Everything you need for building typical GUI applications is here. # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= # This code block was included from src/core_ex.py +import os import sys as _sys +import warnings +from collections import namedtuple from typing import Any, Callable, Iterable, Iterator, Literal, NoReturn, Sequence, overload import numpy as np @@ -39,6 +42,7 @@ from .type_defs import ( EventType, GBPositionType, GBSpanType, + MDIChildFrameBase, PenCap, PenStyle, PolygonFillMode, @@ -49,13 +53,14 @@ from .type_defs import ( ) from .type_defs import PyAssertionError as PyAssertionError from .type_defs import PyNoAppError as PyNoAppError +from .type_defs import wxAssertionError as wxAssertionError # Load version numbers from __version__ and some other initialization tasks... if "wxEVT_NULL" in dir(): import wx._core - from wx.__version__ import * + from wx.__version__ import * # noqa: F403 - __version__ = VERSION_STRING # type: ignore + __version__ = VERSION_STRING # type: ignore # noqa: F405 # Add the build type to PlatformInfo # PlatformInfo = PlatformInfo + ("build-type: " + BUILD_TYPE,) @@ -76,8 +81,6 @@ else: # be used in the python code here. wx = _sys.modules[__name__] -import warnings - class wxPyDeprecationWarning(DeprecationWarning): pass @@ -90,78 +93,6 @@ def deprecated(item, msg="", useName=False): used with callable objects (functions, methods, classes) or with properties. """ - import warnings - - name = "" - if useName: - try: - name = " " + item.__name__ - except AttributeError: - pass - - if isinstance(item, type): - # It is a class. Make a subclass that raises a warning. - class DeprecatedClassProxy(item): # type: ignore - def __init__(*args, **kw): - warnings.warn( - "Using deprecated class%s. %s" % (name, msg), - wxPyDeprecationWarning, - stacklevel=2, - ) - item.__init__(*args, **kw) - - DeprecatedClassProxy.__name__ = item.__name__ - return DeprecatedClassProxy - - elif callable(item): - # wrap a new function around the callable - def deprecated_func(*args, **kw): - warnings.warn( - "Call to deprecated item%s. %s" % (name, msg), wxPyDeprecationWarning, stacklevel=2 - ) - if not kw: - return item(*args) - return item(*args, **kw) - deprecated_func.__name__ = item.__name__ - deprecated_func.__doc__ = item.__doc__ - if hasattr(item, "__dict__"): - deprecated_func.__dict__.update(item.__dict__) - return deprecated_func - - elif hasattr(item, "__get__"): - # it should be a property if there is a getter - class DepGetProp: - def __init__(self, item, msg): - self.item = item - self.msg = msg - def __get__(self, inst, klass): - warnings.warn( - "Accessing deprecated property. %s" % msg, wxPyDeprecationWarning, stacklevel=2 - ) - return self.item.__get__(inst, klass) - - class DepGetSetProp(DepGetProp): - def __set__(self, inst, val): - warnings.warn( - "Accessing deprecated property. %s" % msg, wxPyDeprecationWarning, stacklevel=2 - ) - return self.item.__set__(inst, val) - - class DepGetSetDelProp(DepGetSetProp): - def __delete__(self, inst): - warnings.warn( - "Accessing deprecated property. %s" % msg, wxPyDeprecationWarning, stacklevel=2 - ) - return self.item.__delete__(inst) - - if hasattr(item, "__set__") and hasattr(item, "__delete__"): - return DepGetSetDelProp(item, msg) - elif hasattr(item, "__set__"): - return DepGetSetProp(item, msg) - else: - return DepGetProp(item, msg) - else: - raise TypeError("unsupported type %s" % type(item)) def deprecatedMsg(msg): """ @@ -4943,7 +4874,6 @@ def GetLocale(): # ---------------------------------------------------------------------------- # Add the directory where the wxWidgets catalogs were installed # to the default catalog path, if they were put in the package dir. -import os _localedir = os.path.join(os.path.dirname(__file__), "locale") if os.path.exists(_localedir): @@ -6773,25 +6703,13 @@ def GetDisplaySizeMM(): DefaultPosition = Point() DefaultSize = Size() -from collections import namedtuple - _im_Point = namedtuple("_im_Point", ["x", "y"]) -del namedtuple - -from collections import namedtuple _im_Size = namedtuple("_im_Size", ["width", "height"]) -del namedtuple - -from collections import namedtuple _im_Rect = namedtuple("_im_Rect", ["x", "y", "width", "height"]) -del namedtuple - -from collections import namedtuple _im_RealPoint = namedtuple("_im_RealPoint", ["x", "y"]) -del namedtuple def IntersectRect(self, r1, r2): """ @@ -7255,15 +7173,9 @@ class Rect2D: # end of class Rect2D -from collections import namedtuple - _im_Point2D = namedtuple("_im_Point2D", ["x", "y"]) -del namedtuple - -from collections import namedtuple _im_Rect2D = namedtuple("_im_Rect2D", ["x", "y", "width", "height"]) -del namedtuple # -- end-geometry --# # -- begin-affinematrix2d --# @@ -7620,10 +7532,7 @@ class Position: # end of class Position -from collections import namedtuple - _im_Position = namedtuple("_im_Position", ["Row", "Col"]) -del namedtuple # -- end-position --# # -- begin-colour --# C2S_NAME: int @@ -7920,10 +7829,7 @@ LIGHT_GREY = Colour() RED = Colour() WHITE = Colour() -from collections import namedtuple - _im_Colour = namedtuple("_im_Colour", ["red", "green", "blue", "alpha"]) -del namedtuple NamedColour = wx.deprecated(Colour, "Use Colour instead.") # -- end-colour --# @@ -15152,13 +15058,99 @@ class GraphicsFont(GraphicsObject): """ # end of class GraphicsFont -# end of class GraphicsPath -NullGraphicsPen = GraphicsPen() -NullGraphicsBrush = GraphicsBrush() -NullGraphicsFont = GraphicsFont() -NullGraphicsBitmap = GraphicsBitmap() +class GraphicsMatrix(GraphicsObject): + """ + A wxGraphicsMatrix is a native representation of an affine matrix. + """ + + def Concat(self, t): + """ + Concat(t) + + Concatenates the matrix passed with the current matrix. + """ + + def Get(self): + """ + Get() -> (a, b, c, d, tx, ty) + + Returns the component values of the matrix via the argument pointers. + """ + + def GetNativeMatrix(self): + """ + GetNativeMatrix() -> void + + Returns the native representation of the matrix. + """ + + def Invert(self): + """ + Invert() + + Inverts the matrix. + """ + + def IsEqual(self, t): + """ + IsEqual(t) -> bool + + Returns true if the elements of the transformation matrix are equal. + """ + + def IsIdentity(self): + """ + IsIdentity() -> bool + + Return true if this is the identity matrix. + """ + + def Rotate(self, angle): + """ + Rotate(angle) + + Rotates this matrix clockwise (in radians). + """ + + def Scale(self, xScale, yScale): + """ + Scale(xScale, yScale) + + Scales this matrix. + """ + + def Set(self, a=1.0, b=0.0, c=0.0, d=1.0, tx=0.0, ty=0.0): + """ + Set(a=1.0, b=0.0, c=0.0, d=1.0, tx=0.0, ty=0.0) + + Sets the matrix to the respective values (default values are the + identity matrix). + """ + + def TransformDistance(self, dx, dy): + """ + TransformDistance(dx, dy) -> (dx, dy) + + Applies this matrix to a distance (ie. + """ + + def TransformPoint(self, x, y): + """ + TransformPoint(x, y) -> (x, y) + + Applies this matrix to a point. + """ + + def Translate(self, dx, dy): + """ + Translate(dx, dy) + + Translates this matrix. + """ + NativeMatrix = property(None, None) + +# end of class GraphicsMatrix NullGraphicsMatrix = GraphicsMatrix() -NullGraphicsPath = GraphicsPath() class GraphicsPenInfo: """ @@ -16051,99 +16043,6 @@ class GraphicsGradientStops: # end of class GraphicsGradientStops -class GraphicsMatrix(GraphicsObject): - """ - A wxGraphicsMatrix is a native representation of an affine matrix. - """ - - def Concat(self, t): - """ - Concat(t) - - Concatenates the matrix passed with the current matrix. - """ - - def Get(self): - """ - Get() -> (a, b, c, d, tx, ty) - - Returns the component values of the matrix via the argument pointers. - """ - - def GetNativeMatrix(self): - """ - GetNativeMatrix() -> void - - Returns the native representation of the matrix. - """ - - def Invert(self): - """ - Invert() - - Inverts the matrix. - """ - - def IsEqual(self, t): - """ - IsEqual(t) -> bool - - Returns true if the elements of the transformation matrix are equal. - """ - - def IsIdentity(self): - """ - IsIdentity() -> bool - - Return true if this is the identity matrix. - """ - - def Rotate(self, angle): - """ - Rotate(angle) - - Rotates this matrix clockwise (in radians). - """ - - def Scale(self, xScale, yScale): - """ - Scale(xScale, yScale) - - Scales this matrix. - """ - - def Set(self, a=1.0, b=0.0, c=0.0, d=1.0, tx=0.0, ty=0.0): - """ - Set(a=1.0, b=0.0, c=0.0, d=1.0, tx=0.0, ty=0.0) - - Sets the matrix to the respective values (default values are the - identity matrix). - """ - - def TransformDistance(self, dx, dy): - """ - TransformDistance(dx, dy) -> (dx, dy) - - Applies this matrix to a distance (ie. - """ - - def TransformPoint(self, x, y): - """ - TransformPoint(x, y) -> (x, y) - - Applies this matrix to a point. - """ - - def Translate(self, dx, dy): - """ - Translate(dx, dy) - - Translates this matrix. - """ - NativeMatrix = property(None, None) - -# end of class GraphicsMatrix - class GraphicsPath(GraphicsObject): """ A wxGraphicsPath is a native representation of a geometric path. @@ -16302,6 +16201,13 @@ class GraphicsPath(GraphicsObject): CurrentPoint = property(None, None) NativePath = property(None, None) +# end of class GraphicsPath +NullGraphicsPen = GraphicsPen() +NullGraphicsBrush = GraphicsBrush() +NullGraphicsFont = GraphicsFont() +NullGraphicsBitmap = GraphicsBitmap() +NullGraphicsPath = GraphicsPath() + class GraphicsRenderer(Object): """ A wxGraphicsRenderer is the instance corresponding to the rendering @@ -25977,12 +25883,7 @@ class GridBagSizer(FlexGridSizer): # end of class GridBagSizer -from collections import namedtuple - _im_GBPosition = namedtuple("_im_GBPosition", ["row", "col"]) -del namedtuple - -from collections import namedtuple _im_GBSpan = namedtuple("_im_GBSpan", ["rowspan", "colspan"]) del namedtuple @@ -28482,7 +28383,7 @@ class Window(WindowBase): with the currently selected font. """ - def GetTextExtent(self, string): + def GetTextExtent(self, string: str) -> Size: """ GetTextExtent(string) -> Size @@ -39103,7 +39004,7 @@ class ScrollBar(Control): Returns the length of the scrollbar. """ - def GetThumbPosition(self): + def GetThumbPosition(self) -> int: """ GetThumbPosition() -> int @@ -43113,18 +43014,7 @@ if "wxMac" in wx.PlatformInfo: style=CLRP_DEFAULT_STYLE, validator=wx.DefaultValidator, name="colourpicker", - ): - if type(colour) != wx.Colour: - colour = wx.Colour(colour) - wx.PickerBase.__init__(self) - self.CreateBase(parent, id, colour.GetAsString(), pos, size, style, validator, name) - widget = ColourPickerCtrl.ColourPickerButton( - self, -1, colour, style=self.GetPickerStyle(style) - ) - self.SetPickerCtrl(widget) - widget.Bind(wx.EVT_COLOURPICKER_CHANGED, self.OnColourChange) - self.PostCreation() - + ): ... def GetColour(self): """Set the displayed colour.""" return self.GetPickerCtrl().GetColour() @@ -48133,7 +48023,7 @@ class MDIParentFrame(Frame): # end of class MDIParentFrame -class MDIChildFrame(MDIChildFrameBase): # type: ignore +class MDIChildFrame(MDIChildFrameBase): """ MDIChildFrame() MDIChildFrame(parent, id=ID_ANY, title=EmptyString, pos=DefaultPosition, size=DefaultSize, style=DEFAULT_FRAME_STYLE, name=FrameNameStr) diff --git a/typings/wx-stubs/type_defs.pyi b/typings/wx-stubs/type_defs.pyi index 9c942c32b..4b7914cfe 100644 --- a/typings/wx-stubs/type_defs.pyi +++ b/typings/wx-stubs/type_defs.pyi @@ -31,3 +31,4 @@ GBSpanType = tuple[int, int] | list[int] | wx.GBSpan class wxAssertionError(AssertionError): ... class PyAssertionError(wxAssertionError): ... class PyNoAppError(RuntimeError): ... +class MDIChildFrameBase(wx.Frame): ...