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] Adds initial workflow class #14

Open
wants to merge 31 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
844032b
[REF] Return space/den when resampling
rmarkello Sep 7, 2021
161746f
[ENH] Adds initial workflow class
rmarkello Sep 7, 2021
da2534e
[DOC] Adds basic workflow doc-strings
rmarkello Sep 8, 2021
53e659a
[FIX] Fix load_data array handling
rmarkello Sep 8, 2021
46c62bb
[REF] Parcellater holds density
rmarkello Sep 8, 2021
751ec98
[REF] Transformed images have intent
rmarkello Sep 8, 2021
2c14010
[REF] Analysis() handles parcellations
rmarkello Sep 8, 2021
f2acb26
[ENH] Adds vol res estimator
rmarkello Sep 9, 2021
a82662d
[FIX] Nilearn wants str not path
rmarkello Sep 9, 2021
aab1242
[FIX] Better res/den parcellate estimate
rmarkello Sep 9, 2021
05d82a9
[REF] Use vol res estimator
rmarkello Sep 9, 2021
a5802e0
[REF] Use resample_images in workflows
rmarkello Sep 9, 2021
9792199
[ENH] Workflow accept target annot dicts
rmarkello Sep 9, 2021
ea03d65
[FIX] Handle parcellations in vol nulls
rmarkello Sep 9, 2021
42166e8
[TEST] Add test parcellation structures
rmarkello Sep 9, 2021
c783138
[TEST] Add workbench marker
rmarkello Sep 9, 2021
4e4c431
[FIX] Vol null parc handling
rmarkello Sep 9, 2021
eb8ff7d
[TEST] Add some basic workflow tests
rmarkello Sep 9, 2021
7bbd92f
[REF] Suppress redundant warnings
rmarkello Sep 10, 2021
e76fa1a
[REF] Use estimate_res in resampling
rmarkello Sep 10, 2021
745f34e
[FIX] Don't load_gifti() strings
rmarkello Sep 10, 2021
8d3fe57
[TEST] Consolidate workflow tests
rmarkello Sep 10, 2021
dc6ff13
[DOC] Doc-string to trigger test
rmarkello Nov 3, 2021
bb61605
[FIX] Connectivity error with Session
rmarkello Nov 10, 2021
d361d02
[MNT] Extra test dependencies
rmarkello Nov 10, 2021
639fb75
[FIX] Trying Session without token
liuzhenqi77 Nov 10, 2021
0774660
[FIX] Try fixing deps
liuzhenqi77 Nov 10, 2021
5b120c5
[FIX] Try fixing style
liuzhenqi77 Nov 10, 2021
82d1afa
[FIX] Trying another fix
liuzhenqi77 Nov 10, 2021
50079e0
[FIX] Fix for volumetric target
justinehansen Dec 9, 2021
77a18d7
[FIX] Works for hill2010 data
justinehansen Dec 13, 2021
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
7 changes: 5 additions & 2 deletions neuromaps/datasets/annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,8 @@ def fetch_annotation(*, source=None, desc=None, space=None, den=None, res=None,
token = _get_token(token=token)
return_restricted = False if (token is None or not token) else True
data_dir = get_data_dir(data_dir=data_dir)
if space == 'MNI152' and hemi == ('L', 'R'):
hemi = None
info = _match_annot(get_dataset_info('annotations', return_restricted),
source=source, desc=desc, space=space, den=den,
res=res, hemi=hemi, tags=tags, format=format)
Expand All @@ -223,8 +225,9 @@ def fetch_annotation(*, source=None, desc=None, space=None, den=None, res=None,
for dset in info:
fn = Path(data_dir) / 'annotations' / dset['rel_path'] / dset['fname']
if not fn.exists():
dl_file = _fetch_file(dset['url'], str(fn.parent), verbose=verbose,
md5sum=dset['checksum'], session=session)
dl_file = _fetch_file(dset['url'], str(fn.parent),
verbose=verbose, md5sum=dset['checksum'],
session=session)
shutil.move(dl_file, fn)
data.append(str(fn))

Expand Down
2 changes: 2 additions & 0 deletions neuromaps/datasets/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ def test__get_token():
assert utils._get_token('test') == 'test'
if orig is not None: # reset env variable
os.environ['NEUROMAPS_OSF_TOKEN'] = orig
else:
os.environ.pop('NEUROMAPS_OSF_TOKEN', None)


@pytest.mark.xfail
Expand Down
14 changes: 10 additions & 4 deletions neuromaps/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os
from pathlib import Path
from typing import Iterable
import warnings

import nibabel as nib
from nibabel.filebasedimages import ImageFileError
Expand Down Expand Up @@ -133,7 +134,9 @@ def load_nifti(img):
"""

try:
img = nib.load(img)
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
img = nib.load(img)
except (TypeError) as err:
msg = ('stat: path should be string, bytes, os.PathLike or integer, '
'not Nifti1Image')
Expand Down Expand Up @@ -161,7 +164,9 @@ def load_gifti(img):
"""

try:
img = nib.load(img)
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
img = nib.load(img)
except (ImageFileError, TypeError) as err:
# it's gzipped, so read the gzip and pipe it in
if isinstance(err, ImageFileError) and str(err).endswith('.gii.gz"'):
Expand Down Expand Up @@ -199,8 +204,9 @@ def load_data(data):
out = np.hstack([load_gifti(img).agg_data() for img in data])
except (AttributeError, TypeError):
out = np.stack([load_nifti(img).get_fdata() for img in data], axis=3)
except ValueError as err:
if str(err) == 'stat: embedded null character in path':
except (ValueError, FileNotFoundError) as err:
if (str(err) == 'stat: embedded null character in path'
or str(err).startswith('No such file or no access:')):
out = np.stack(data, axis=-1)

return np.squeeze(out)
Expand Down
34 changes: 23 additions & 11 deletions neuromaps/nulls/nulls.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ def _surf_surrogates(data, atlas, density, parcellation, distmat, n_proc):
yield hdata[mask], dist[np.ix_(mask, mask)], None, idx[mask]


def _vol_surrogates(data, atlas, density, parcellation, distmat, **kwargs):
def _vol_surrogates(data, atlas, density, parcellation, distmat, *args):
if atlas != 'MNI152':
raise ValueError('Cannot compute volumetric surrogates if atlas is '
f'"MNI152". Received: {atlas}')
Expand All @@ -418,18 +418,24 @@ def _vol_surrogates(data, atlas, density, parcellation, distmat, **kwargs):

# get data + coordinates of valid datapoints
data = load_data(data)
if mni152.shape != data.shape:
raise ValueError('Provided `data` array must have same affine as '
'specified MNI152 atlas')
data *= load_data(atlas['brainmask'])
mask = np.logical_not(np.logical_or(np.isclose(data, 0), np.isnan(data)))
xyz = nib.affines.apply_affine(affine, np.column_stack(np.where(mask)))

if parcellation is not None:
if parcellation is None:
if mni152.shape != data.shape:
raise ValueError('Provided `data` array must have same affine as '
'specified MNI152 atlas')
data *= load_data(atlas['brainmask'])
mask = ~np.logical_or(np.isclose(data, 0), np.isnan(data))
data = data[mask]
else:
parcellation = load_data(
mni152_to_mni152(parcellation, density, 'nearest')
)[mask]
)
labels = np.trim_zeros(np.unique(parcellation))
mask = ~np.logical_or(
np.isclose(parcellation, 0), np.isnan(parcellation)
)
parcellation = parcellation[mask]

xyz = nib.affines.apply_affine(affine, np.column_stack(np.where(mask)))

# calculate distance matrix
index = None
Expand Down Expand Up @@ -458,7 +464,13 @@ def _vol_surrogates(data, atlas, density, parcellation, distmat, **kwargs):
if parcellation is None:
index = np.argsort(dist, axis=-1)

yield data[mask], dist, index, slice(-1)
if parcellation is not None:
dist = np.row_stack([
dist[parcellation == lab].mean(axis=0) for lab in labels
])
dist[np.diag_indices_from(dist)] = 0

yield data, dist, index, slice(None)


def _make_surrogates(data, method, atlas='fsaverage', density='10k',
Expand Down
9 changes: 8 additions & 1 deletion neuromaps/parcellate.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
from neuromaps.datasets import ALIAS, DENSITIES
from neuromaps.images import construct_shape_gii, load_gifti
from neuromaps.resampling import resample_images
from neuromaps.transforms import _check_hemi
from neuromaps.transforms import (_check_hemi, _estimate_density,
_estimate_resolution)
from neuromaps.nulls.spins import vertices_to_parcels, parcels_to_vertices


Expand Down Expand Up @@ -60,6 +61,12 @@ def __init__(self, parcellation, space, resampling_target='data',
self.hemi = hemi
self._volumetric = self.space == 'MNI152'

if not self._volumetric:
self._density, = _estimate_density((self.parcellation,), self.hemi)
else:
self._density, = _estimate_resolution((self.parcellation,))
self.hemi = ('L', 'R') if hemi is None else hemi

if self.resampling_target == 'parcellation':
self._resampling = 'transform_to_trg'
else:
Expand Down
Loading