Skip to content

Commit

Permalink
FIX: ruff linting errors (#829)
Browse files Browse the repository at this point in the history
* FIX: ruff linting errors

* Format task_navigator
  • Loading branch information
omar-abdelgawad authored Sep 16, 2024
1 parent 631e830 commit 875e0b6
Show file tree
Hide file tree
Showing 81 changed files with 675 additions and 1,187 deletions.
54 changes: 19 additions & 35 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
# detalhes.
# -------------------------------------------------------------------------

from __future__ import print_function

import argparse
import multiprocessing
import os
Expand Down Expand Up @@ -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'):
Expand All @@ -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
Expand All @@ -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()
Expand All @@ -96,8 +86,6 @@
except FileNotFoundError:
pass

import invesalius.gui.log as log


class InVesalius(wx.App):
"""
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)

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

Expand All @@ -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)
Expand All @@ -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)

Expand Down Expand Up @@ -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():
Expand All @@ -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"
Expand All @@ -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")


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


Expand Down
28 changes: 13 additions & 15 deletions invesalius/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -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..."
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion invesalius/data/actor_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from invesalius import inv_paths


class ActorFactory(object):
class ActorFactory:
def __init__(self):
pass

Expand Down
2 changes: 1 addition & 1 deletion invesalius/data/brainmesh_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
2 changes: 1 addition & 1 deletion invesalius/data/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions invesalius/data/cursor_actors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
"""
Expand Down Expand Up @@ -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]
Expand All @@ -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):
"""
Expand Down
2 changes: 1 addition & 1 deletion invesalius/data/e_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
16 changes: 8 additions & 8 deletions invesalius/data/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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]]
Expand Down
Loading

0 comments on commit 875e0b6

Please sign in to comment.