Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Calculate T1/T2 ratio #451

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
90 changes: 90 additions & 0 deletions smriprep/interfaces/calc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2024 The NiPreps Developers <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# We support and encourage derived works from this project, please read
# about our expectations at
#
# https://www.nipreps.org/community/licensing/
#
"""Image calculation interfaces."""

import os
from pathlib import Path

import nibabel as nb
import numpy as np
from nipype.interfaces.base import (
File,
SimpleInterface,
TraitedSpec,
)


class T1T2RatioInputSpec(TraitedSpec):
t1w_file = File(exists=True, mandatory=True, desc='T1-weighted image')
t2w_file = File(exists=True, mandatory=True, desc='T2-weighted image')
mask_file = File(exists=True, desc='Brain mask')


class T1T2RatioOutputSpec(TraitedSpec):
t1t2_file = File(exists=True, desc='T1/T2 ratio image')


class T1T2Ratio(SimpleInterface):
input_spec = T1T2RatioInputSpec
output_spec = T1T2RatioOutputSpec

def _run_interface(self, runtime):
self._results['t1t2_file'] = make_t1t2_ratio(
self.inputs.t1w_file, self.inputs.t2w_file, self.inputs.mask_file, newpath=runtime.cwd
)
return runtime


def make_t1t2_ratio(
t1w_file: str,
t2w_file: str,
mask_file: str | None = None,
newpath: str | None = None,
) -> str:
t1w = nb.load(t1w_file)
t2w = nb.load(t2w_file)
if mask_file is not None:
mask = np.asanyarray(nb.load(mask_file).dataobj) != 0
else:
mask = np.ones(t1w.shape, dtype=bool)

t1w_data = t1w.get_fdata(dtype=np.float32)
t2w_data = t2w.get_fdata(dtype=np.float32)

t1t2_data = np.zeros_like(t1w_data)

ratio = t1w_data[mask] / t2w_data[mask]
ratio[~np.isfinite(ratio)] = 0
minval = ratio.min()
maxval = ratio.max()

t1t2_data[mask] = (ratio - minval) / (maxval - minval) * 100

t1t2 = nb.Nifti1Image(t1t2_data, t1w.affine, t1w.header)
t1t2.header.set_data_dtype(np.float32)

t1t2_path = Path(newpath or os.getcwd()) / 't1t2_ratio.nii.gz'

t1t2.to_filename(t1t2_path)

return str(t1t2_path)
24 changes: 24 additions & 0 deletions smriprep/interfaces/tests/test_calc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import nibabel as nb
from nipype.pipeline import engine as pe
from templateflow import api as tf

from ..calc import T1T2Ratio


def test_T1T2Ratio(tmp_path):
t1w = tf.get('MNI152NLin2009cAsym', desc=None, resolution=1, suffix='T1w')
t2w = tf.get('MNI152NLin2009cAsym', desc=None, resolution=1, suffix='T2w')
mask = tf.get('MNI152NLin2009cAsym', desc='brain', resolution=1, suffix='mask')

t1t2 = pe.Node(
T1T2Ratio(t1w_file=t1w, t2w_file=t2w, mask_file=mask),
name='t1t2',
base_dir=tmp_path,
)

result = t1t2.run()

t1t2ratio = nb.load(result.outputs.t1t2_file)
assert t1t2ratio.shape == (193, 229, 193)
assert t1t2ratio.get_fdata().min() == 0.0
assert t1t2ratio.get_fdata().max() == 100.0
13 changes: 13 additions & 0 deletions smriprep/workflows/anatomical.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@
import smriprep

from ..interfaces import DerivativesDataSink

# from ..interfaces.calc import T1T2Ratio
from ..utils.misc import apply_lut as _apply_bids_lut
from ..utils.misc import fs_isRunning as _fs_isRunning
from .fit.registration import init_register_template_wf
Expand Down Expand Up @@ -645,6 +647,7 @@ def init_anat_fit_wf(
'sphere_reg_fsLR',
'sphere_reg_msm',
'anat_ribbon',
't1t2_ratio',
# Reverse transform; not computable from forward transform
'std2anat_xfm',
# Metadata
Expand Down Expand Up @@ -1308,6 +1311,16 @@ def init_anat_fit_wf(
LOGGER.info('ANAT Stage 8a: Found pre-computed cortical ribbon mask')
outputnode.inputs.anat_ribbon = precomputed['anat_ribbon']

if t2w and 't1t2ratio' not in precomputed:
LOGGER.info('ANAT Stage 8b: Creating T1w/T2w ratio map')
# Commented out to pacify linter.
# t1t2_ratio = pe.Node(T1T2Ratio(), name='t1t2_ratio')

elif not t2w:
LOGGER.info('ANAT No T2w images provided - skipping Stage 8b')
else:
LOGGER.info('ANAT Found precomputed T1w/T2w ratio map - skipping Stage 8b')

# Stage 9: Baseline fsLR registration
if len(precomputed.get('sphere_reg_fsLR', [])) < 2:
LOGGER.info('ANAT Stage 9: Creating fsLR registration sphere')
Expand Down
Loading
Loading