Skip to content

ENH: Add an activation count map interface #2522

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

Merged
merged 23 commits into from
Apr 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
56fbac3
[ENH] Add a activation count map interface
oesteban Mar 30, 2018
f6a9a81
add credit to @jokedurnez [skip ci]
oesteban Mar 30, 2018
756088a
fix several issues
oesteban Mar 31, 2018
4cf7f66
Merge remote-tracking branch 'upstream/master' into enh/activations-c…
oesteban Apr 1, 2018
81167ca
cleaner reading
oesteban Apr 1, 2018
8a294e0
make specs
oesteban Apr 1, 2018
068dda0
drop nb.load
oesteban Apr 1, 2018
5b9fc04
Merge branch 'enh/activations-count-map' of github.com:oesteban/nipyp…
oesteban Apr 1, 2018
beaf3b8
TEST: Activation count map smoke test
effigies Apr 10, 2018
4b93c9e
address @effigies' comments
oesteban Apr 10, 2018
60e97d5
Merge pull request #7 from effigies/enh/activations-count-map
oesteban Apr 10, 2018
608c4d2
update test and autotest
oesteban Apr 10, 2018
f81c1cf
remove old autotest
oesteban Apr 10, 2018
b126b70
Merge branch 'enh/activations-count-map' of https://github.com/oesteb…
djarecka Apr 13, 2018
6e53f01
adding tests that checks pos/neg for normal distribution
djarecka Apr 17, 2018
6348862
increasing atol in the test
djarecka Apr 17, 2018
9e07a6e
Merge pull request #9 from djarecka/oesteban-enh/activations-count-map
oesteban Apr 25, 2018
d3d75f7
Merge remote-tracking branch 'upstream/master' into enh/activations-c…
oesteban Apr 25, 2018
e0ba996
make threshold mandatory without default
oesteban Apr 25, 2018
02b7dfd
Merge branch 'enh/activations-count-map' of github.com:oesteban/nipyp…
oesteban Apr 25, 2018
cfb19c4
forgot make specs
oesteban Apr 25, 2018
31bc311
[skip ci] improve description
oesteban Apr 25, 2018
728bc1b
fix test
oesteban Apr 25, 2018
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
68 changes: 68 additions & 0 deletions nipype/algorithms/stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Managing statistical maps
"""
from __future__ import (print_function, division, unicode_literals,
absolute_import)
import os
import nibabel as nb
import numpy as np

from ..interfaces.base import (
BaseInterfaceInputSpec, TraitedSpec, SimpleInterface,
traits, InputMultiPath, File
)
from ..utils.filemanip import split_filename


class ActivationCountInputSpec(BaseInterfaceInputSpec):
in_files = InputMultiPath(File(exists=True), mandatory=True,
desc='input file, generally a list of z-stat maps')
threshold = traits.Float(
mandatory=True, desc='binarization threshold. E.g. a threshold of 1.65 '
'corresponds to a two-sided Z-test of p<.10')


class ActivationCountOutputSpec(TraitedSpec):
out_file = File(exists=True, desc='output activation count map')
acm_pos = File(exists=True, desc='positive activation count map')
acm_neg = File(exists=True, desc='negative activation count map')


class ActivationCount(SimpleInterface):
"""
Calculate a simple Activation Count Maps

Adapted from: https://github.com/poldracklab/CNP_task_analysis/\
blob/61c27f5992db9d8800884f8ffceb73e6957db8af/CNP_2nd_level_ACM.py
"""
input_spec = ActivationCountInputSpec
output_spec = ActivationCountOutputSpec

def _run_interface(self, runtime):
allmaps = nb.concat_images(self.inputs.in_files).get_data()
acm_pos = np.mean(allmaps > self.inputs.threshold,
axis=3, dtype=np.float32)
acm_neg = np.mean(allmaps < -1.0 * self.inputs.threshold,
axis=3, dtype=np.float32)
acm_diff = acm_pos - acm_neg

template_fname = self.inputs.in_files[0]
ext = split_filename(template_fname)[2]
fname_fmt = os.path.join(runtime.cwd, 'acm_{}' + ext).format

self._results['out_file'] = fname_fmt('diff')
self._results['acm_pos'] = fname_fmt('pos')
self._results['acm_neg'] = fname_fmt('neg')

img = nb.load(template_fname)
img.__class__(acm_diff, img.affine, img.header).to_filename(
self._results['out_file'])
img.__class__(acm_pos, img.affine, img.header).to_filename(
self._results['acm_pos'])
img.__class__(acm_neg, img.affine, img.header).to_filename(
self._results['acm_neg'])

return runtime
31 changes: 31 additions & 0 deletions nipype/algorithms/tests/test_auto_ActivationCount.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..stats import ActivationCount


def test_ActivationCount_inputs():
input_map = dict(
ignore_exception=dict(
deprecated='1.0.0',
nohash=True,
usedefault=True,
),
in_files=dict(mandatory=True, ),
threshold=dict(mandatory=True, ),
)
inputs = ActivationCount.input_spec()

for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_ActivationCount_outputs():
output_map = dict(
acm_neg=dict(),
acm_pos=dict(),
out_file=dict(),
)
outputs = ActivationCount.output_spec()

for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
45 changes: 45 additions & 0 deletions nipype/algorithms/tests/test_stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:

import numpy as np
import nibabel as nb
from nipype.algorithms.stats import ActivationCount
import pytest


def test_ActivationCount(tmpdir):
tmpdir.chdir()
in_files = ['{:d}.nii'.format(i) for i in range(3)]
for fname in in_files:
nb.Nifti1Image(np.random.normal(size=(5, 5, 5)),
np.eye(4)).to_filename(fname)

acm = ActivationCount(in_files=in_files, threshold=1.65)
res = acm.run()
diff = nb.load(res.outputs.out_file)
pos = nb.load(res.outputs.acm_pos)
neg = nb.load(res.outputs.acm_neg)
assert np.allclose(diff.get_data(), pos.get_data() - neg.get_data())
Copy link
Collaborator

@djarecka djarecka Apr 13, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we could also check some statistics pos.get_data itself?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The main things I can think of that should be true of performing this on some random noise would be np.all(pos.get_data() > 0) and np.all(neg.get_data() > 0).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I understand correctly, the interface just checks how many point are above threshold or below -threshold. If we draw points from random distribution and we slightly increase the size of the array, we should be able to compare to theoretical value.
Let me finish something and I'll add a simple example to show what do I mean.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here is an example: oesteban@6e53f01

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That looks valid, but I'm not fully clear on what assurances this gets us for the interface. I guess, roughly, that Gaussian noise is being filtered as we'd expect?

I'm okay if this test goes in, but my overall feeling is that a useful test asserts properties that should be true given any real or simulated inputs, and this seems tied to the specific distribution of simulated random variates.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you usually use specific cases for tests, and often some simple cases, so you know the answer.

The interface should work for any real or simulated inputs, but I'm checking here for a specific distribution (exactly the same as @oesteban used in the original test). Obviously I'm not able to predict answers for completely random set of numbers, but for the normal distribution I can.

I just thought that this adds extra checks to the original @oesteban test, that was only checking pos-neg == diff, but I won't insist to include it.

Copy link
Collaborator

@djarecka djarecka Apr 17, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can also just generate a small array and calculate the expected output of the interface.



@pytest.mark.parametrize("threshold, above_thresh", [
(1, 15.865), # above one standard deviation (one side)
(2, 2.275), # above two standard deviations (one side)
(3, 0.135) # above three standard deviations (one side)
])
def test_ActivationCount_normaldistr(tmpdir, threshold, above_thresh):
tmpdir.chdir()
in_files = ['{:d}.nii'.format(i) for i in range(3)]
for fname in in_files:
nb.Nifti1Image(np.random.normal(size=(100, 100, 100)),
np.eye(4)).to_filename(fname)

acm = ActivationCount(in_files=in_files, threshold=threshold)
res = acm.run()
pos = nb.load(res.outputs.acm_pos)
neg = nb.load(res.outputs.acm_neg)
assert np.isclose(pos.get_data().mean(),
above_thresh * 1.e-2, rtol=0.1, atol=1.e-4)
assert np.isclose(neg.get_data().mean(),
above_thresh * 1.e-2, rtol=0.1, atol=1.e-4)