本文整理汇总了Python中bids.BIDSLayout方法的典型用法代码示例。如果您正苦于以下问题:Python bids.BIDSLayout方法的具体用法?Python bids.BIDSLayout怎么用?Python bids.BIDSLayout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bids
的用法示例。
在下文中一共展示了bids.BIDSLayout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bids_layout
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def bids_layout(bids_dir, deriv_dir, sub_fmriprep,
sub_metadata, bold_file, preproc_file,
sub_events, confounds_file, brainmask_file,
sub_rest_metadata, rest_file):
layout = BIDSLayout(
str(bids_dir),
derivatives=str(deriv_dir),
index_metadata=False)
# only index bold file metadata
indexer = BIDSLayoutIndexerPatch(layout)
metadata_filter = {
'extension': ['nii', 'nii.gz', 'json'],
'suffix': 'bold',
}
indexer.index_metadata(**metadata_filter)
return layout
示例2: bids_db_file
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def bids_db_file(
bids_dir, deriv_dir, sub_fmriprep, sub_metadata, bold_file, preproc_file,
sub_events, confounds_file, brainmask_file, atlas_file, atlas_lut,
):
from bids import BIDSLayout
from .workflows.utils import BIDSLayoutIndexerPatch
db_file = bids_dir / ".dbcache"
layout = BIDSLayout(
str(bids_dir),
derivatives=str(deriv_dir),
index_metadata=False,
database_file=str(db_file),
reset_database=True)
# only index bold file metadata
indexer = BIDSLayoutIndexerPatch(layout)
metadata_filter = {
'extension': ['nii', 'nii.gz', 'json'],
'suffix': 'bold',
}
indexer.index_metadata(**metadata_filter)
return db_file
示例3: load_data
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def load_data(self, bids_filter=None):
"""Returns data, default is the input data.
bids_filter : dict
default is None. If set, load data will load all files found by the bids_filter.
Any preset BIDS filter is used as well, but will get overwritten by this input.
"""
if bids_filter is None:
files = self.get_selected_files()
else:
filters = dict(self.bids_filter)
filters.update(bids_filter)
files = self.BIDSLayout.get(**filters)
data = {}
for f in files:
if f.filename in data:
raise ValueError('Same name appears twice in selected files')
data[f.filename], _ = self.load_file(f)
return data
示例4: init_getters
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def init_getters(self):
"""Initializes the getters methods for input paths and feature readers."""
from visualqc.features import diffusion_mri_features
self.feature_extractor = diffusion_mri_features
if 'BIDS' in self.in_dir_type.upper():
from bids import BIDSLayout
self.bids_layout = BIDSLayout(self.in_dir)
self.units = diffusion_traverse_bids(self.bids_layout)
# file name of each scan is the unique identifier,
# as it essentially contains all the key info.
self.unit_by_id = {basename(sub_data['image']): sub_data
for _, sub_data in self.units.items()}
self.id_list = list(self.unit_by_id.keys())
else:
raise NotImplementedError('Only the BIDS format is supported for now!')
示例5: _init_layout
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def _init_layout(in_file=None, bids_dir=None, validate=True):
if isinstance(bids_dir, BIDSLayout):
return bids_dir
if bids_dir is None:
in_file = Path(in_file)
for parent in in_file.parents:
if parent.name.startswith("sub-"):
bids_dir = parent.parent.resolve()
break
if bids_dir is None:
raise RuntimeError("Could not infer BIDS root")
layout = BIDSLayout(str(bids_dir), validate=validate)
return layout
示例6: __init__
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def __init__(self, bids_dir, selected_pipeline, bids_filter=None, bidsvalidator=False,
update_pipeline=True, history=None, exist_ok=False, layout=None):
import bids
if layout is None:
self.BIDSLayout = bids.BIDSLayout(bids_dir, derivatives=True)
else:
self.BIDSLayout = layout
self.bids_dir = bids_dir
self.selected_pipeline = selected_pipeline
if bids_filter is None:
self.bids_filter = {}
else:
self.bids_filter = bids_filter
if history is not None:
self.history = {}
self.exist_ok = exist_ok
with open(tenetopath[0] + '/config/tenetobids/tenetobids_description.json') as f:
self.tenetobids_description = json.load(f)
self.tenetobids_description['PipelineDescription']['Version'] = tenetoversion
with open(tenetopath[0] + '/config/tenetobids/tenetobids_structure.json') as f:
self.tenetobids_structure = json.load(f)
# def set_selected_pipeline(self, selected_pipeline):
# bids.
示例7: update_bids_layout
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def update_bids_layout(self):
self.BIDSLayout = bids.BIDSLayout(self.bids_dir, derivatives=True)
示例8: get_selected_files
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def get_selected_files(self, output=None):
"""
Uses information in selected_pipeline and the bids layout and shows the files that will be processed when calling TenetoBIDS.run().
If you specify a particular output, it will tell you which files will get selected for that output
"""
if output is not None:
filters = self.tenetobids_structure[output]['input']
else:
# input can only be these files
filters = {'extension': ['tsv', 'nii', 'nii.gz']}
# Add predefined filters to the check
filters.update(self.bids_filter)
files = self.BIDSLayout.get(scope=self.selected_pipeline, **filters)
return files
示例9: get_confounds
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def get_confounds(self, bidsfile, confound_filters=None):
"""Tries to automatically get the confounds file of an input file, and loads it
Paramters
==========
bidsfile : BIDSDataFile or BIDSImageFile
The BIDS file that the confound file is gong to be matched.
"""
if confound_filters is None:
confound_filters = {}
# Get the entities of the filename
file_entities = bidsfile.get_entities()
# Ensure that the extension and suffix are correct
file_entities['suffix'] = 'regressors'
file_entities['extension'] = 'tsv'
if 'desc' in file_entities:
file_entities.pop('desc')
confoundsfile = self.BIDSLayout.get(**file_entities)
if len(confoundsfile) == 0:
raise ValueError('Non confounds found')
elif len(confoundsfile) > 1:
raise ValueError('More than one confounds file found')
# Load the confounds file
confounds = load_tabular_file(
confoundsfile[0].dirname + '/' + confoundsfile[0].filename, index_col=False)
return confounds
示例10: init_getters
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def init_getters(self):
"""Initializes the getters methods for input paths and feature readers."""
from visualqc.features import functional_mri_features
self.feature_extractor = functional_mri_features
if 'BIDS' in self.in_dir_type.upper():
from bids import BIDSLayout
self.bids_layout = BIDSLayout(self.in_dir)
self.units = func_mri_traverse_bids(self.bids_layout,
**cfg.func_mri_BIDS_filters)
# file name of each BOLD scan is the unique identifier,
# as it essentially contains all the key info.
self.unit_by_id = {basename(sub_data['image']): sub_data
for _, sub_data in self.units.items()}
self.id_list = list(self.unit_by_id.keys())
elif 'GENERIC' in self.in_dir_type.upper():
if self.id_list is None or self.images_for_id is None:
raise ValueError('id_list or images_for_id can not be None '
'for generic in_dir')
self.unit_by_id = self.images_for_id.copy()
else:
raise NotImplementedError('Only two formats are supported: BIDS and ' \
'GENERIC with regex spec for filenames')
示例11: find_anatomical_images_in_BIDS
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def find_anatomical_images_in_BIDS(bids_dir):
"""Traverses the BIDS structure to find all the relevant anatomical images."""
from bids import BIDSLayout
bids_layout = BIDSLayout(bids_dir)
images = anatomical_traverse_bids(bids_layout)
# file name of each scan is the unique identifier,
# as it essentially contains all the key info.
images_by_id = {basename(sub_data['image']): sub_data
for _, sub_data in images.items()}
id_list = np.array(list(images_by_id.keys()))
return id_list, images_by_id
示例12: _run_interface
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def _run_interface(self, runtime):
import bids
from bids.analysis import auto_model
models = self.inputs.model
if not isinstance(models, list):
database_path = self.inputs.database_path
layout = bids.BIDSLayout.load(database_path=database_path)
if not isdefined(models):
# model is not yet standardized, so validate=False
# Ignore all subject directories and .git/ and .datalad/ directories
small_layout = bids.BIDSLayout(
layout.root, derivatives=[d.root for d in layout.derivatives.values()],
validate=False,
ignore=[re.compile(r'sub-'),
re.compile(r'\.(git|datalad)')])
# PyBIDS can double up, so find unique models
models = list(set(small_layout.get(suffix='smdl', return_type='file')))
if not models:
raise ValueError("No models found")
elif models == 'default':
models = auto_model(layout)
models = [_ensure_model(m) for m in models]
if self.inputs.selectors:
# This is almost certainly incorrect
models = [model for model in models
if all(val in model['input'].get(key, [val])
for key, val in self.inputs.selectors.items())]
self._results['model_spec'] = models
return runtime
示例13: _list_outputs
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def _list_outputs(self):
from bids.layout import BIDSLayout
base_dir = self.inputs.base_directory
os.makedirs(base_dir, exist_ok=True)
layout = BIDSLayout(base_dir, validate=False)
path_patterns = self.inputs.path_patterns
if not isdefined(path_patterns):
path_patterns = None
out_files = []
for entities, in_file in zip(self.inputs.entities,
self.inputs.in_file):
ents = {**self.inputs.fixed_entities}
ents.update(entities)
ents = {k: snake_to_camel(str(v)) for k, v in ents.items()}
out_fname = os.path.join(
base_dir, layout.build_path(
ents, path_patterns, validate=False))
os.makedirs(os.path.dirname(out_fname), exist_ok=True)
_copy_or_convert(in_file, out_fname)
out_files.append(out_fname)
return {'out_file': out_files}
示例14: collect_data
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def collect_data(bids_dir, participant_label, bids_validate=True):
"""Replacement for niworkflows' version."""
if isinstance(bids_dir, BIDSLayout):
layout = bids_dir
else:
layout = BIDSLayout(str(bids_dir), validate=bids_validate)
queries = {
"fmap": {"datatype": "fmap"},
"dwi": {"datatype": "dwi", "suffix": "dwi"},
"flair": {"datatype": "anat", "suffix": "FLAIR"},
"t2w": {"datatype": "anat", "suffix": "T2w"},
"t1w": {"datatype": "anat", "suffix": "T1w"},
"roi": {"datatype": "anat", "suffix": "roi"},
}
subj_data = {
dtype: sorted(
layout.get(
return_type="file",
subject=participant_label,
extension=["nii", "nii.gz"],
**query
)
)
for dtype, query in queries.items()
}
return subj_data, layout
示例15: test_dcm2bids
# 需要导入模块: import bids [as 别名]
# 或者: from bids import BIDSLayout [as 别名]
def test_dcm2bids():
# tmpBase = os.path.join(TEST_DATA_DIR, "tmp")
# bidsDir = TemporaryDirectory(dir=tmpBase)
bidsDir = TemporaryDirectory()
tmpSubDir = os.path.join(bidsDir.name, DEFAULT.tmpDirName, "sub-01")
shutil.copytree(os.path.join(TEST_DATA_DIR, "sidecars"), tmpSubDir)
app = Dcm2bids(
[TEST_DATA_DIR],
"01",
os.path.join(TEST_DATA_DIR, "config_test.json"),
bidsDir.name,
)
app.run()
layout = BIDSLayout(bidsDir.name, validate=False)
assert layout.get_subjects() == ["01"]
assert layout.get_sessions() == []
assert layout.get_tasks() == ["rest"]
assert layout.get_runs() == [1, 2, 3]
app = Dcm2bids(
[TEST_DATA_DIR],
"01",
os.path.join(TEST_DATA_DIR, "config_test.json"),
bidsDir.name,
)
app.run()
fmapFile = os.path.join(bidsDir.name, "sub-01", "fmap", "sub-01_echo-492_fmap.json")
data = load_json(fmapFile)
fmapMtime = os.stat(fmapFile).st_mtime
assert data["IntendedFor"] == "dwi/sub-01_dwi.nii.gz"
data = load_json(
os.path.join(
bidsDir.name, "sub-01", "localizer", "sub-01_run-01_localizer.json"
)
)
assert data["ProcedureStepDescription"] == "Modify by dcm2bids"
# rerun
shutil.rmtree(tmpSubDir)
shutil.copytree(os.path.join(TEST_DATA_DIR, "sidecars"), tmpSubDir)
app = Dcm2bids(
[TEST_DATA_DIR],
"01",
os.path.join(TEST_DATA_DIR, "config_test.json"),
bidsDir.name,
)
app.run()
fmapMtimeRerun = os.stat(fmapFile).st_mtime
assert fmapMtime == fmapMtimeRerun
if os.name != 'nt':
bidsDir.cleanup()