Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
329c74d
add variance-driven component selection, return component metadata
rciric Jan 19, 2019
17f3e12
expose metadata to interface, fix component selection for multiple masks
rciric Jan 19, 2019
114e6d4
propagate failure mode if provided
rciric Jan 19, 2019
6f4fc19
allow mask naming in metadata
rciric Jan 19, 2019
4d2208e
add contributor
rciric Jan 19, 2019
bfbde82
include component index in metadata
rciric Jan 19, 2019
0373879
update autotests and make naming consistent
rciric Jan 19, 2019
2c551d0
(CompCor) more intuitive interface following review from @effigies
rciric Jan 20, 2019
a53cd46
manually set `num_components` in test
rciric Jan 20, 2019
b811d47
manually set `num_components` in test
rciric Jan 20, 2019
2743189
Merge branch 'master' of https://github.com/rciric/nipype
rciric Jan 21, 2019
577e395
add unit test for variance_threshold condition
rciric Jan 21, 2019
66c7540
provide mask name to circumvent test failure
rciric Jan 21, 2019
0bb0096
(CompCor) try using an OrderedDict for metadata
rciric Jan 21, 2019
94bea4a
first-pass refactor CompCor to SimpleInterface
rciric Feb 4, 2019
addb0e9
return metadata for all components regardless of retention criterion
rciric Feb 6, 2019
b04c9ca
@oesteban: limit np array use, clean up conditionals, remove invalid obj
rciric Feb 8, 2019
e957e87
less np array use; unique names for dropped components
rciric Feb 9, 2019
797801e
ensure absolute path to components file
rciric Feb 9, 2019
67a3276
(CompCor) try BaseInterface
rciric Feb 9, 2019
fe430f5
ensure absolute path to components file
rciric Feb 9, 2019
1625bdb
update per @oesteban 's review
rciric Feb 15, 2019
9afb3f5
assign output to _results
rciric Feb 15, 2019
689d064
assign output to _results
rciric Feb 15, 2019
f390bc6
some fixes
oesteban Feb 16, 2019
ad3d440
testing pickling of variance_threshold
oesteban Feb 16, 2019
fd41b74
``traits.Range`` cannot be pickled with traits>=5 and python 2.7
oesteban Feb 16, 2019
01a78ec
Merge pull request #1 from oesteban/rciric-patch-1
rciric Feb 16, 2019
a742c9c
pacify codacy
rciric Feb 16, 2019
518a489
revert unnecessary squeeze, correct docs
rciric Feb 21, 2019
deceb95
revise in accordance with @effigies review
rciric Feb 22, 2019
fa64907
revise in accordance with @effigies review
rciric Feb 23, 2019
e6dfe7d
ensure s is defined, support NaN failure mode with empty mask
rciric Mar 1, 2019
27ed03f
filter handles empty masks, use `squeeze_image`
rciric Mar 27, 2019
422c04c
Merge branch 'master' of https://github.com/nipy/nipype
rciric Mar 27, 2019
144fca3
Merge branch 'master' of https://github.com/nipy/nipype
rciric Mar 28, 2019
82a25c2
default to old behaviour for temporal filters
rciric Mar 28, 2019
4c1af8a
Merge branch 'master' into master
effigies Apr 11, 2019
79e840d
integrate @effigies review comments
rciric Apr 19, 2019
1b1b6fa
propagate retention status to metadata; use list instead of generator…
rciric Apr 19, 2019
89ba3b4
Merge branch 'master' of https://github.com/rciric/nipype
rciric Apr 19, 2019
b80a3d7
update unit test to include new metadata field
rciric Apr 19, 2019
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
Prev Previous commit
Next Next commit
expose metadata to interface, fix component selection for multiple masks
  • Loading branch information
rciric committed Jan 19, 2019
commit 17f3e120b5cb48e14000a43203828c78c23b76d0
67 changes: 49 additions & 18 deletions nipype/algorithms/confounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,16 @@ class CompCorInputSpec(BaseInterfaceInputSpec):
'components_file.txt',
usedefault=True,
desc='Filename to store physiological components')
num_components = traits.Int(6, usedefault=True) # 6 for BOLD, 4 for ASL
num_components = traits.Float(6, usedefault=True,
desc='Number of components to return from the decomposition.'
'If `num_components` is a positive integer, then '
'`num_components` components will be retained. If '
'`num_components` is a fractional value between 0 and 1, then '
'the number of components retained will be equal to the minimum '
'number of components necessary to explain the provided '
'fraction of variance in the masked time series. If '
'`num_components` is -1, then all components will be retained.')
# 6 for BOLD, 4 for ASL
pre_filter = traits.Enum(
'polynomial',
'cosine',
Expand Down Expand Up @@ -418,6 +427,8 @@ class CompCorInputSpec(BaseInterfaceInputSpec):
'unspecified')
save_pre_filter = traits.Either(
traits.Bool, File, desc='Save pre-filter basis as text file')
save_metadata = traits.Either(
traits.Bool, File, desc='Save component metadata as text file')
ignore_initial_volumes = traits.Range(
low=0,
usedefault=True,
Expand All @@ -433,6 +444,7 @@ class CompCorOutputSpec(TraitedSpec):
components_file = File(
exists=True, desc='text file containing the noise components')
pre_filter_file = File(desc='text file containing high-pass filter basis')
metadata_file = File(desc='text file containing component metadata')


class CompCor(BaseInterface):
Expand Down Expand Up @@ -548,7 +560,7 @@ def _run_interface(self, runtime):
'{} cannot detect repetition time from image - '
'Set the repetition_time input'.format(self._header))

components, filter_basis = compute_noise_components(
components, filter_basis, metadata = compute_noise_components(
imgseries.get_data(), mask_images, self.inputs.num_components,
self.inputs.pre_filter, degree, self.inputs.high_pass_cutoff, TR)

Expand Down Expand Up @@ -597,6 +609,16 @@ def _run_interface(self, runtime):
header='\t'.join(header),
comments='')

if self.inputs.save_metadata:
metadata_file = self._list_outputs()['metadata_file']
np.savetxt(
metadata_file,
np.vstack(metadata.values()).T,
fmt=['%s', b'%.10f', b'%.10f', b'%.10f'],
delimiter='\t',
header='\t'.join(list(metadata.keys())),
comments='')

return runtime

def _process_masks(self, mask_images, timeseries=None):
Expand All @@ -613,6 +635,12 @@ def _list_outputs(self):
save_pre_filter = os.path.abspath('pre_filter.tsv')
outputs['pre_filter_file'] = save_pre_filter

save_metadata = self.inputs.save_metadata
if save_metadata:
if isinstance(save_metadata, bool):
save_metadata = os.path.abspath('component_metadata.tsv')
outputs['metadata_file'] = save_metadata

return outputs

def _make_headers(self, num_col):
Expand Down Expand Up @@ -1139,7 +1167,7 @@ def combine_mask_files(mask_files, mask_method=None, mask_index=None):
return [img]


def compute_noise_components(imgseries, mask_images, num_components=0.5,
def compute_noise_components(imgseries, mask_images, components_criterion=0.5,
filter_type=False, degree=0, period_cut=128,
repetition_time=None, failure_mode='error'):
"""Compute the noise components from the imgseries for each mask
Expand All @@ -1153,11 +1181,11 @@ def compute_noise_components(imgseries, mask_images, num_components=0.5,
according to the spatial extent of each mask, and the subset data is
then decomposed using principal component analysis. Masks should be
coextensive with either anatomical or spatial noise ROIs.
num_components: float
components_criterion: float
Number of noise components to return. If this is a decimal value
between 0 and 1, then `create_noise_components` will instead return
the smallest number of components necessary to explain the indicated
fraction of variance. If `num_components` is -1, then all
fraction of variance. If `components_criterion` is -1, then all
components will be returned.
filter_type: str
Type of filter to apply to time series before computing
Expand Down Expand Up @@ -1204,38 +1232,40 @@ def compute_noise_components(imgseries, mask_images, num_components=0.5,
voxel_timecourses, repetition_time, period_cut)
elif filter_type in ('polynomial', False):
# from paper:
# "The constant and linear trends of the columns in the matrix M were
# removed [prior to ...]"
# "The constant and linear trends of the columns in the matrix M
# were removed [prior to ...]"
voxel_timecourses, basis = regress_poly(degree, voxel_timecourses)

# "Voxel time series from the noise ROI (either anatomical or tSTD) were
# placed in a matrix M of size Nxm, with time along the row dimension
# and voxels along the column dimension."
# "Voxel time series from the noise ROI (either anatomical or tSTD)
# were placed in a matrix M of size Nxm, with time along the row
# dimension and voxels along the column dimension."
M = voxel_timecourses.T

# "[... were removed] prior to column-wise variance normalization."
M = M / _compute_tSTD(M, 1.)

# "The covariance matrix C = MMT was constructed and decomposed into its
# principal components using a singular value decomposition."
# "The covariance matrix C = MMT was constructed and decomposed into
# its principal components using a singular value decomposition."
try:
u, s, _ = fallback_svd(M, full_matrices=False)
except np.linalg.LinAlgError:
if self.inputs.failure_mode == 'error':
raise
if num_components >= 1:
u = np.empty((M.shape[0], num_components),
if components_criterion >= 1:
u = np.empty((M.shape[0], components_criterion),
dtype=np.float32) * np.nan
else:
continue

variance_explained = np.array([value**2/np.sum(s**2) for value in s])
cumulative_variance_explained = np.cumsum(variance_explained)
if 0 < num_components < 1:
if 0 < components_criterion < 1:
num_components = np.searchsorted(cumulative_variance_explained,
num_components) + 1
elif num_components == -1:
components_criterion) + 1
elif components_criterion == -1:
num_components = len(s)
else:
num_components = components_criterion
if components is None:
components = u[:, :num_components]
metadata = {
Expand All @@ -1258,7 +1288,8 @@ def compute_noise_components(imgseries, mask_images, num_components=0.5,
if components is None and num_components != 0:
if self.inputs.failure_mode == 'error':
raise ValueError('No components found')
components = np.ones((M.shape[0], num_components), dtype=np.float32) * np.nan
components = np.ones((M.shape[0], num_components),
dtype=np.float32) * np.nan
return components, basis, metadata


Expand Down