Skip to content

Commit

Permalink
bump version, merge pull request #17 from AMYPAD/centiloid
Browse files Browse the repository at this point in the history
centiloid
  • Loading branch information
casperdcl authored Aug 6, 2022
2 parents dfb7dbd + 3ebd2a7 commit 8857b3d
Show file tree
Hide file tree
Showing 11 changed files with 96 additions and 58 deletions.
12 changes: 4 additions & 8 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,12 @@ jobs:
check:
if: github.event_name != 'push' || github.ref != 'refs/heads/devel'
runs-on: ubuntu-latest
strategy:
matrix:
python: [2.7, 3.6, 3.9]
name: Check py${{ matrix.python }}
name: Check
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python }}
python-version: '3.x'
- name: set PYSHA
run: echo "PYSHA=$(python -VV | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV
- uses: actions/cache@v1
Expand All @@ -35,14 +32,13 @@ jobs:
env:
REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
EVENT: ${{ github.event_name }}
- if: startsWith(matrix.python, '3')
run: pre-commit run -a --show-diff-on-failure
- run: pre-commit run -a --show-diff-on-failure
test:
if: github.event_name != 'pull_request' || github.head_ref != 'devel'
runs-on: ubuntu-latest
strategy:
matrix:
python: [2.7, 3.6, 3.9]
python: [3.6, '3.10']
name: Test py${{ matrix.python }}
steps:
- uses: actions/checkout@v2
Expand Down
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ default_language_version:
python: python3
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
rev: v4.3.0
hooks:
- id: check-added-large-files
- id: check-case-conflict
Expand Down Expand Up @@ -36,10 +36,10 @@ repos:
- flake8-debugger
- flake8-string-format
- repo: https://github.com/psf/black
rev: 21.7b0
rev: 22.6.0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 5.9.3
rev: 5.10.1
hooks:
- id: isort
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ write_to = "spm12/_dist_ver.py"
write_to_template = "__version__ = '{version}'\n"

[tool.black]
target_version = ["py27", "py36", "py38"]
target_version = ["py36", "py310"]
line_length = 99
10 changes: 5 additions & 5 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ classifiers=
Operating System :: Microsoft :: Windows
Operating System :: POSIX :: Linux
Programming Language :: Other Scripting Engines
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
Programming Language :: Python :: 3.10
Topic :: Scientific/Engineering :: Medical Science Apps.
Topic :: Software Development :: Libraries
Topic :: System :: Installation/Setup
Expand All @@ -46,7 +45,7 @@ install_requires=
scipy
include_package_data=True
packages=find:
python_requires=>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*
python_requires=>=3.6
[options.extras_require]
dev=
pre-commit
Expand All @@ -72,12 +71,13 @@ exclude=tests
universal = 1

[flake8]
max_line_length=88
extend-ignore=E203,P1
max_line_length=99
extend_ignore=E203,P1
exclude=.git,__pycache__,build,dist,.eggs

[isort]
profile=black
line_length=99
known_first_party=spm12,tests

[tool:pytest]
Expand Down
9 changes: 5 additions & 4 deletions spm12/amypad_normw.m
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
function out = amypad_normw(def_file, flist4norm)
function out = amypad_normw(def_file, flist4norm, voxsz, intrp, bbox)
job.subj.def = {def_file};
job.subj.resample = flist4norm;
job.woptions.bb = [NaN, NaN, NaN; NaN, NaN, NaN];
job.woptions.vox = [2, 2, 2];
job.woptions.interp = 4;
%job.woptions.bb = [NaN, NaN, NaN; NaN, NaN, NaN];
job.woptions.bb = bbox;
job.woptions.vox = [voxsz, voxsz, voxsz];
job.woptions.interp = intrp;
job.woptions.prefix = 'w';
spm_run_norm(job);
out=0;
Expand Down
4 changes: 1 addition & 3 deletions spm12/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@


def main(argv=None):
logging.basicConfig(
level=logging.DEBUG, format="%(levelname)s:%(funcName)s:%(message)s"
)
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s:%(funcName)s:%(message)s")
args = argopt(__doc__).parse_args(argv)
ensure_spm(cache=args.cache, version=args.spm_version)
print("SPM{v} is successfully installed".format(v=args.spm_version))
Expand Down
89 changes: 72 additions & 17 deletions spm12/regseg.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import re
import shutil
from pathlib import PurePath
from textwrap import dedent

import numpy as np
Expand Down Expand Up @@ -46,9 +47,7 @@ def smoothim(fim, fwhm=4, fout=""):
)
if not fout:
f = nii.file_parts(fim)
fout = os.path.join(
f[0], "{}_smo{}{}".format(f[1], str(fwhm).replace(".", "-"), f[2])
)
fout = os.path.join(f[0], "{}_smo{}{}".format(f[1], str(fwhm).replace(".", "-"), f[2]))
nii.array2nii(
imsmo,
imd["affine"],
Expand All @@ -63,13 +62,52 @@ def smoothim(fim, fwhm=4, fout=""):
return {"im": imsmo, "fim": fout, "fwhm": fwhm, "affine": imd["affine"]}


def get_bbox(fnii):
"""get the SPM equivalent of the bounding box for
NIfTI image `fnii` which can be a dictionary or file.
"""

if isinstance(fnii, (str, PurePath)):
niidct = nii.getnii(fnii, output="all")
elif isinstance(fnii, dict) and "hdr" in fnii:
niidct = fnii
else:
raise ValueError("incorrect input NIfTI file/dictionary")

dim = niidct["hdr"]["dim"]
corners = np.array(
[
[1, 1, 1, 1],
[1, 1, dim[3], 1],
[1, dim[2], 1, 1],
[1, dim[2], dim[3], 1],
[dim[1], 1, 1, 1],
[dim[1], 1, dim[3], 1],
[dim[1], dim[2], 1, 1],
[dim[1], dim[2], dim[3], 1],
]
)

XYZ = np.dot(niidct["affine"][:3, :], corners.T)

# FIXME: weird correction for SPM bounding box (??)
crr = np.dot(niidct["affine"][:3, :3], [1, 1, 1])

# bounding box as matrix
bbox = np.concatenate((np.min(XYZ, axis=1) - crr, np.max(XYZ, axis=1) - crr))
bbox.shape = (2, 3)

return bbox


def coreg_spm(
imref,
imflo,
matlab_eng_name="",
fwhm_ref=0,
fwhm_flo=0,
outpath="",
output_eng=False,
fname_aff="",
fcomment="",
pickname="ref",
Expand Down Expand Up @@ -137,9 +175,7 @@ def coreg_spm(
imrefu = smodct["fim"]

log.info(
"smoothed the reference image with FWHM={} and saved to\n{}".format(
fwhm_ref, imrefu
)
"smoothed the reference image with FWHM={} and saved to\n{}".format(fwhm_ref, imrefu)
)

# floating
Expand All @@ -162,9 +198,7 @@ def coreg_spm(
imflou = smodct["fim"]

log.info(
"smoothed the floating image with FWHM={} and saved to\n{}".format(
fwhm_ref, imrefu
)
"smoothed the floating image with FWHM={} and saved to\n{}".format(fwhm_flo, imflou)
)

# run the MATLAB SPM registration
Expand Down Expand Up @@ -233,7 +267,8 @@ def coreg_spm(
out["faff"] = faff
out["rotations"] = x[3:]
out["translations"] = x[:3]
out["matlab_eng"] = eng
if output_eng:
out["matlab_eng"] = eng
return out


Expand All @@ -243,7 +278,7 @@ def resample_spm(
M,
matlab_eng_name="",
fwhm=0,
intrp=1.0,
intrp=1,
which=1,
mask=0,
mean=0,
Expand Down Expand Up @@ -299,9 +334,7 @@ def resample_spm(
M = np.load(M)
log.info("matrix M given in the form of NumPy file")
else:
raise IOError(
errno.ENOENT, M, "Unrecognised file extension for the affine."
)
raise IOError(errno.ENOENT, M, "Unrecognised file extension for the affine.")
elif isinstance(M, (np.ndarray, np.generic)):
log.info("matrix M given in the form of Numpy array")
else:
Expand All @@ -311,7 +344,14 @@ def resample_spm(
import matlab as ml

eng.amypad_resample(
imrefu, imflou, ml.double(M.tolist()), mask, mean, intrp, which, prefix
imrefu,
imflou,
ml.double(M.tolist()),
mask,
mean,
float(intrp),
which,
prefix,
)

# -compress the output
Expand Down Expand Up @@ -415,17 +455,32 @@ def seg_spm(
return out


def normw_spm(f_def, files4norm, matlab_eng_name="", outpath=None):
def normw_spm(f_def, files4norm, voxsz=2, intrp=4, bbox=None, matlab_eng_name="", outpath=None):
"""
Write normalisation output to NIfTI files using SPM12.
Args:
f_def: NIfTI file of definitions for non-rigid normalisation
files4norm: list of input NIfTI file paths in format ['file, 1']
voxsz: voxel size of the output (normalised) images
intrp: interpolation level used for the normalised images
(4: B-spline, default)
matlab_eng_name: name of the Python engine for Matlab.
outpath: output folder path for the normalisation files
"""

import matlab as ml

if bbox is None:
bb = ml.double([[np.NaN, np.NaN, np.NaN], [np.NaN, np.NaN, np.NaN]])
elif isinstance(bbox, np.ndarray) and bbox.shape == (2, 3):
bb = ml.double(bbox.tolist())
elif isinstance(bbox, list) and len(bbox) == 2:
bb = ml.double(bbox)
else:
raise ValueError("unrecognised format for bounding box")

eng = ensure_spm(matlab_eng_name) # get_matlab
eng.amypad_normw(f_def, files4norm)
eng.amypad_normw(f_def, files4norm, float(voxsz), float(intrp), bb)
out = [] # output list
if outpath is not None:
create_dir(outpath)
Expand Down
10 changes: 2 additions & 8 deletions spm12/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from functools import wraps
from functools import lru_cache, wraps
from os import path
from textwrap import dedent

Expand All @@ -8,11 +8,6 @@
from miutil.web import urlopen_cached
from pkg_resources import resource_filename

try:
from functools import lru_cache
except ImportError: # fix py2.7
from backports.functools_lru_cache import lru_cache

__all__ = ["ensure_spm", "get_matlab", "spm_dir"]
PATH_M = resource_filename(__name__, "")
log = logging.getLogger(__name__)
Expand Down Expand Up @@ -46,8 +41,7 @@ def ensure_spm(name=None, cache="~/.spm12", version=12):
try:
log.info("Downloading to %s", cache)
with urlopen_cached(
"https://www.fil.ion.ucl.ac.uk/"
"spm/download/restricted/eldorado/spm12.zip",
"https://www.fil.ion.ucl.ac.uk/spm/download/restricted/eldorado/spm12.zip",
cache,
) as fd:
extractall(fd, cache)
Expand Down
4 changes: 1 addition & 3 deletions tests/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
from .conftest import HOME

log = logging.getLogger(__name__)
DATA_URL = (
"https://zenodo.org/record/3877529/files/amyloidPET_FBP_TP0_extra.zip?download=1"
)
DATA_URL = "https://zenodo.org/record/3877529/files/amyloidPET_FBP_TP0_extra.zip?download=1"


def main():
Expand Down
5 changes: 0 additions & 5 deletions tests/test_main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
from miutil.mlab import matlabroot
from pytest import mark, skip

try:
FileNotFoundError
except NameError: # fix py2.7
FileNotFoundError = OSError

pytestmark = mark.filterwarnings("ignore:numpy.ufunc size changed.*:RuntimeWarning")


Expand Down
2 changes: 1 addition & 1 deletion tests/test_regseg.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def assert_equal_arrays(x, y, nmse_tol=0, denan=True):
if denan:
x, y = map(np.nan_to_num, (x, y))
if nmse_tol:
if ((x - y) ** 2).mean() / (y ** 2).mean() < nmse_tol:
if ((x - y) ** 2).mean() / (y**2).mean() < nmse_tol:
return
elif (x == y).all():
return
Expand Down

0 comments on commit 8857b3d

Please sign in to comment.