Skip to content

Commit

Permalink
FIX: Cleanups suggested by ruff (#18)
Browse files Browse the repository at this point in the history
* FIX: Undefined variable should be unused ge_cas

* STY: Remove unused imports

* MNT: Configure ruff to ignore things that are okay

* RF: Clean up coef_file_parse()

* Use context manager to ensure file is closed promptly
* Skip unnecessary regex compilation
* Give line fields variable a meaningful name

* FIX: Provide a more informative error for get_ge_coef

* STY: Keep imports at top of files

* RF: Remove indirect import of math.factorial

* FIX: Revert "valid line" condition, but keep the shorter name
  • Loading branch information
effigies authored May 17, 2024
1 parent 4af3c75 commit 09a8b78
Show file tree
Hide file tree
Showing 7 changed files with 36 additions and 42 deletions.
36 changes: 20 additions & 16 deletions gradunwarp/core/coeffs.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import numpy as np
import logging
import re
from . import globals
from .globals import siemens_cas, ge_cas


Expand Down Expand Up @@ -44,19 +43,15 @@ def coef_file_parse(cfile, txt_var_map):
modifies txt_var_map in place
'''
# parse .coef file. Strip unneeded characters. a valid line in that file is
# broken into validline_list
coef_re = re.compile(r'^[^\#]') # regex for first character not a '#'
coef_file = open(cfile, 'r')
for line in coef_file.readlines():
if coef_re.match(line):
validline_list = line.lstrip(' \t').rstrip(';\n').split()
if validline_list:
log.info('Parsed : %s' % validline_list)
l = validline_list
x = int(l[1])
y = int(l[2])
txt_var_map[l[0]][x, y] = float(l[3])
with open(cfile) as coef_file:
for line in coef_file:
if re.match(r'^[^#]', line):
fields = line.lstrip(' \t').rstrip(';\n').split()
if fields:
log.info('Parsed : %s' % fields)
x = int(fields[1])
y = int(fields[2])
txt_var_map[fields[0]][x, y] = float(fields[3])


def get_siemens_coef(cfile):
Expand Down Expand Up @@ -96,7 +91,15 @@ def get_siemens_coef(cfile):
def get_ge_coef(cfile):
''' Parse the GE .coef file.
'''
txt_var_map = create_txt_var_map(coef_array_sz)
# R0_m has never been defined in gradunwarp for this function
# This function would raise a NameError if it were ever called, so
# let's provide a meaningful runtime error.
raise RuntimeError(
"R0_m has never been defined in gradunwarp for this function. "
"If you know how to determine it, please contact the developers."
)

txt_var_map = create_txt_var_map(ge_cas)

coef_file_parse(cfile, txt_var_map)

Expand All @@ -107,7 +110,8 @@ def get_ge_coef(cfile):
txt_var_map['beta_y'],
txt_var_map['beta_x'],
txt_var_map['beta_z'],
R0_m)
R0_m) # noqa: F821


def grad_file_parse(gfile, txt_var_map):
xmax = 0
Expand Down
2 changes: 1 addition & 1 deletion gradunwarp/core/gradient_unwarp.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def argument_parse_gradunwarp():
try:
p = arg.ArgumentParser(usage=globals.usage)
p.add_argument('--version', '-v', action='version', version=globals.VERSION)
except:
except TypeError:
#maintain compatibility with pre py2.7 argparse (deprecated in py2.7 but fails in py3)
p = arg.ArgumentParser(version=globals.VERSION, usage=globals.usage)

Expand Down
3 changes: 1 addition & 2 deletions gradunwarp/core/tests/test_gradient_unwarp.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import tempfile

import numpy as np
import nibabel as nb
Expand All @@ -13,7 +12,7 @@ class Arguments:


def test_trivial_unwarp():
with InTemporaryDirectory() as tmpdir:
with InTemporaryDirectory():
# Siemens Allegra coefficient arrays are 15x15, keeping things small and fast
coef_file = "allegra.coef"
open(coef_file, 'wb').close() # touch
Expand Down
10 changes: 6 additions & 4 deletions gradunwarp/core/tests/test_regression.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import os
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')

import numpy as np
from numpy.testing import assert_array_almost_equal, assert_allclose
from numpy.testing import assert_array_almost_equal

from gradunwarp.core.unwarp_resample import cart2sph, siemens_B
from gradunwarp.core import coeffs

DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')

from gradunwarp.core import coeffs, utils
from gradunwarp.core.unwarp_resample import siemens_B, cart2sph

def test_siemens_B():
gradfile = os.path.join(DATA_DIR, 'gradunwarp_coeffs.grad')
Expand Down
8 changes: 2 additions & 6 deletions gradunwarp/core/unwarp_resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@
from __future__ import absolute_import, print_function
import numpy as np
import sys
import pdb
import gc
import math
import logging
from scipy import ndimage
from . import utils
from .utils import CoordsVector as CV
from .utils import factorial
from . import globals
from .globals import siemens_max_det
import nibabel as nib
import subprocess
import scipy.special

#np.seterr(all='raise')
Expand Down Expand Up @@ -385,8 +381,8 @@ def siemens_B(alpha, beta, r, cosine_theta, theta, phi, R0):
# this is Siemens normalization
if m > 0:
normfact = math.pow(-1, m) * \
math.sqrt(float((2 * n + 1) * factorial(n - m)) \
/ float(2 * factorial(n + m)))
math.sqrt(float((2 * n + 1) * math.factorial(n - m)) \
/ float(2 * math.factorial(n + m)))
_p *= normfact
b += f * _p * f2
return b
Expand Down
16 changes: 3 additions & 13 deletions gradunwarp/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
from __future__ import print_function
import numpy as np
from collections import namedtuple
import math
from math import sqrt, cos, pi

import numpy as np
import nibabel as nib
from nibabel.affines import apply_affine

# This is a container class that has 3 np.arrays which contain
# the x, y and z coordinates respectively. For example, the output
Expand All @@ -18,19 +17,10 @@
# cv = CoordsVector(x=x, y=y, z=z)
CoordsVector = namedtuple('CoordsVector', 'x, y, z')

from nibabel.affines import apply_affine

def transform_coordinates(A, M):
transformed = apply_affine(M, np.stack(A).T).T
return CoordsVector(*transformed)

def get_vol_affine(infile):
try:
import nibabel as nib
except ImportError:
raise ImportError('gradunwarp needs nibabel for I/O of mgz/nifti files.'
' Please install')
nibimage = nib.load(infile)
return np.asanyarray(nibimage.dataobj), nibimage.affine

factorial = math.factorial
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,6 @@ push = false
[tool.cibuildwheel]
# Do not bother building pypy wheels
skip = "pp*"

[tool.ruff.extend-per-file-ignores]
"*/__init__.py" = ["F401"]

0 comments on commit 09a8b78

Please sign in to comment.