Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions deepaneseg/data/generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def generate_transforms(trans=None, rot=None, center=None, disp=None):
affine = None
else:
t = np.zeros(3)
if not trans is None:
if trans is not None:
if np.isscalar(trans):
t = trans * np.ones(3)
elif len(trans) == 3:
Expand All @@ -31,7 +31,7 @@ def generate_transforms(trans=None, rot=None, center=None, disp=None):
raise TypeError("trans argument should be either a scalar or a 3-vector")
t = t * (2 * (np.random.random_sample(3) - 0.5))
r = np.zeros(3)
if not rot is None:
if rot is not None:
if np.isscalar(rot):
r = rot * np.ones(3)
elif len(rot) == 3:
Expand All @@ -44,7 +44,7 @@ def generate_transforms(trans=None, rot=None, center=None, disp=None):
affine[:3, :3] = Rotation.from_euler("zyx", r, degrees=True).as_matrix()
affine[:3, 3] = t if center is None else t + center.ravel() @ (np.eye(3) - affine[:3, :3]).T

if not disp is None:
if disp is not None:
if np.isscalar(disp):
amp = disp * np.ones(3)
elif len(disp) == 3:
Expand Down
21 changes: 11 additions & 10 deletions deepaneseg/data/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import os
import nibabel as ni
import pandas as pd
import json, glob
import json
import glob

from deepaneseg.volume.selection import select_points
from deepaneseg.utils import get_logger
Expand Down Expand Up @@ -105,12 +106,12 @@ def read_patient_data(vol_file, ane_file, normalize=None, vessel_file=None):
- 'Normal': rescaling to 0-mean and unit-variance data
"""
d, a = read_nii_from_file(vol_file)
if not vessel_file is None:
if vessel_file is not None:
seg, _ = read_nii_from_file(vessel_file)
seg = np.where(seg > 0, 1, 0).astype(np.uint8) # just in case
else:
seg = None
if not ane_file is None:
if ane_file is not None:
s = read_points_from_csv(ane_file)
else:
s = None
Expand All @@ -126,7 +127,7 @@ def read_patient_data_from_config(cfg_name, volume="init volume", normalize=None
dir = os.path.dirname(cfg_name)
with open(cfg_name, "r") as f:
c = json.load(f)
if not vessel is None and os.path.isfile(os.path.join(dir, dir.split("/")[-1] + ".nii.gz")): # c['vessel']))
if vessel is not None and os.path.isfile(os.path.join(dir, dir.split("/")[-1] + ".nii.gz")): # c['vessel']))
vessel_file = os.path.join(dir, dir.split("/")[-1] + ".nii.gz") # c['vessel'])
else:
vessel_file = None
Expand Down Expand Up @@ -214,8 +215,8 @@ def csv2fcsv(csv_pathname):
head = f"# Markups fiducial file version = 4.10\n# CoordinateSystem = 0\n# columns = {','.join(df)}\n"
with open(fcsv_file_out, "w") as f:
f.write(head)
for i, l in df.iterrows():
f.write(",".join([f"{v}" for v in l]) + "\n")
for i, row in df.iterrows():
f.write(",".join([f"{v}" for v in row]) + "\n")


def fcsv2csv(fcsv_file):
Expand All @@ -224,13 +225,13 @@ def fcsv2csv(fcsv_file):
csv_file_out = filename + ".csv"

with open(fcsv_file, "r") as f:
l = f.readlines()
lines = f.readlines()
# coordinate system
cs = l[1].strip().split("=")[1].strip()
cs = lines[1].strip().split("=")[1].strip()
# column names
cn = list(map(str.strip, l[2].split("=")[1].split(",")))
cn = list(map(str.strip, lines[2].split("=")[1].split(",")))
# data
data = [s.strip().split(",") for s in l[3:]]
data = [s.strip().split(",") for s in lines[3:]]
# check coordinate systems and column names
# RAS: if cs='RAS' or cs='0'
# LPS: if cs='LPS' or cs='1'
Expand Down
6 changes: 3 additions & 3 deletions deepaneseg/inference/evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def confusion_matrix(pred, vox2met, spheres, min_size=None, tp_proportion=0.3):
"""
# label CC in prediction
label_pred = skme.label(pred.astype(np.uint8))
if not min_size is None: # also perform relabelling to keep consecutive labels
if min_size is not None: # also perform relabelling to keep consecutive labels
label_pred = skme.label(skmo.remove_small_objects(label_pred, min_size=min_size))
ncc_pred = np.max(label_pred.ravel())

Expand Down Expand Up @@ -86,12 +86,12 @@ def adam_evaluation(pred, vox2met, spheres, pretraited=None, min_size=None):
"""
# label CC in prediction
label_pred = skme.label(pred.astype(np.uint8))
if not min_size is None: # also perform relabelling to keep consecutive labels
if min_size is not None: # also perform relabelling to keep consecutive labels
label_pred = skme.label(skmo.remove_small_objects(label_pred, min_size=min_size))
ncc_pred = np.max(label_pred.ravel())

# Exculude pretraited aneurysms
if not pretraited is None:
if pretraited is not None:
print("pretraited")
for i in range(1, ncc_pred + 1):
tmp = label_pred.copy()
Expand Down
2 changes: 1 addition & 1 deletion deepaneseg/models/building_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def create_conv(in_channels, out_channels, kernel_size, order, padding):
elif char == "l":
modules.append(("LeakyReLU", nn.LeakyReLU(inplace=True)))
elif char == "c":
bias = not ("b" in order)
bias = "b" not in order
modules.append(("conv", create_conv3d(in_channels, out_channels, kernel_size, padding=padding, bias=bias)))
elif char == "b":
is_before_conv = i < order.index("c")
Expand Down
3 changes: 2 additions & 1 deletion deepaneseg/training/dataset.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import math
import torch, random
import torch
import random
import numpy as np

from torch.utils.data import DataLoader
Expand Down
5 changes: 2 additions & 3 deletions deepaneseg/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import numpy as np
import torch
from torch.optim.lr_scheduler import ReduceLROnPlateau, _LRScheduler

from hydra.utils import instantiate

Expand Down Expand Up @@ -183,8 +184,6 @@ def init_model(m):


########### WarmUp scheduler ########
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau


class GradualWarmupScheduler(_LRScheduler):
Expand Down Expand Up @@ -242,7 +241,7 @@ def step_reduce_lr_on_plateau(self, metrics, epoch=None):
self.after_scheduler.step(metrics) # , None)

def step(self, epoch=None, metrics=None):
if type(self.after_scheduler) != ReduceLROnPlateau:
if not isinstance(self.after_scheduler, ReduceLROnPlateau):
if self.finished and self.after_scheduler:
if epoch is None:
self.after_scheduler.step(None)
Expand Down
8 changes: 4 additions & 4 deletions deepaneseg/volume/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ def inv_trans_point(p, center, size, affine=None, disp=None, order=3):
"""
x = p.copy()
# apply affine transform
if not affine is None:
if affine is not None:
D = np.linalg.inv(affine)
x = D[:3, :] @ np.vstack((x, np.ones(x.shape[1])))

# then apply inverse of deformation
if not disp is None:
if disp is not None:
center = np.asarray(center)
size = np.asarray(size)
# determine abscissa relative to the cube
Expand Down Expand Up @@ -52,10 +52,10 @@ def trans_point(p, center, size, affine=None, disp=None):
p stored in an 3xN array
"""
x = p.copy()
if not disp is None:
if disp is not None:
ores = sopt.minimize(_euclidean_dist, x.ravel(), method="CG", args=(p.ravel(), center, size, affine, disp))
x = ores.x.reshape((3, -1))
elif not affine is None:
elif affine is not None:
x = affine[:3, :] @ np.vstack((x, np.ones(x.shape[1])))
return x

Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ extend-exclude = ["notebooks"]
line-ending = "lf"

[tool.ruff.lint]
select = ["E9", "F"]
# ruff's default rules: pycodestyle errors and pyflakes
select = ["E4", "E7", "E9", "F"]

[tool.ruff.lint.per-file-ignores]
# still references TensorFlow from an earlier port and computes metrics it never reports;
Expand Down
5 changes: 2 additions & 3 deletions scripts/experimental/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@ def main():
try:
with open(cfg, "r") as f:
config = json.load(f)
except:
print(f"No such config file {cfg}")
exit()
except OSError:
sys.exit(f"No such config file {cfg}")

logger = get_logger("Evaluation")

Expand Down
2 changes: 1 addition & 1 deletion scripts/experimental/evaluate_perf.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
pred, vox2met = dio.read_nii_from_file(fname)
pred = np.where(pred < threshold, 0, 1).astype(np.uint8)

if not vmin is None:
if vmin is not None:
pred = skimo.remove_small_objects(skime.label(pred), min_size=vmin)
pred = np.where(pred > 0, 1, 0)

Expand Down
Loading