basic functionality implemented + one doctest
@@ -8,6 +8,7 @@ Interfaces for handling BIDS-like neuroimaging structures
"""
import os
+from json import dumps
from pathlib import Path
from shutil import copytree, rmtree
@@ -287,6 +288,24 @@ class DerivativesDataSink(SimpleInterface):
'.../niworkflows/sub-02/ses-noanat/func/sub-02_ses-noanat_task-rest_run-01_\
desc-preproc_bold.nii.gz'
+ >>> bids_dir = tmpdir / 'bidsroot' / 'sub-02' / 'ses-noanat' / 'func'
+ >>> bids_dir.mkdir(parents=True, exist_ok=True)
+ >>> tricky_source = bids_dir / 'sub-02_ses-noanat_task-rest_run-01_bold.nii.gz'
+ >>> tricky_source.open('w').close()
+ >>> dsink = DerivativesDataSink(base_directory=str(tmpdir), check_hdr=False)
+ >>> dsink.inputs.in_file = str(tmpfile)
+ >>> dsink.inputs.source_file = str(tricky_source)
+ >>> dsink.inputs.keep_dtype = True
+ >>> dsink.inputs.desc = 'preproc'
+ >>> dsink.inputs.RepetitionTime = 0.75
+ >>> res = dsink.run()
+ >>> res.outputs.out_meta # doctest: +ELLIPSIS
+ '.../niworkflows/sub-02/ses-noanat/func/sub-02_ses-noanat_task-rest_run-01_\
+desc-preproc_bold.json'
+
+ >>> Path(res.outputs.out_meta).read_text().splitlines()[1]
+ ' "RepetitionTime": 0.75'
+
"""
input_spec = DerivativesDataSinkInputSpec
output_spec = DerivativesDataSinkOutputSpec
@@ -294,6 +313,11 @@ desc-preproc_bold.nii.gz'
_always_run = True
def __init__(self, out_path_base=None, **inputs):
+ self._metadata = {}
+ self._static_traits = self.input_spec.class_editable_traits()
+ for dynamic_input in set(inputs) - set(self._static_traits):
+ self._metadata[dynamic_input] = inputs.pop(dynamic_input)
+
super(DerivativesDataSink, self).__init__(**inputs)
self._results['out_file'] = []
if out_path_base:
@@ -382,6 +406,16 @@ desc-preproc_bold.nii.gz'
# Rewrite file with new header
nii.__class__(nii.get_data(), nii.affine, hdr).to_filename(
out_file)
+
+ if len(self._results['out_file']) == 1:
+ meta_fields = self.inputs.copyable_trait_names()
+ meta_dict = {k: getattr(self.inputs, k)
+ for k in meta_fields if k not in self._static_traits}
+ if meta_dict:
+ sidecar = (Path(self._results['out_file'][0]).parent /
+ ('%s.json' % _splitext(self._results['out_file'][0])[0]))
+ sidecar.write_text(dumps(meta_dict, sort_keys=True, indent=2))
+ self._results['out_meta'] = str(sidecar)
return runtime
