|
| 1 | +import json |
| 2 | +from pathlib import Path |
| 3 | +import typing as ty |
| 4 | + |
| 5 | +import nibabel as nb |
| 6 | +import numpy as np |
| 7 | + |
| 8 | +from nibabel import cifti2 as ci |
| 9 | +from nipype.interfaces.base import TraitedSpec, traits, File, SimpleInterface |
| 10 | +from nipype.utils.filemanip import split_filename |
| 11 | +from templateflow import api as tf |
| 12 | + |
| 13 | + |
| 14 | +class _GenerateDScalarInputSpec(TraitedSpec): |
| 15 | + surface_target = traits.Enum( |
| 16 | + "fsLR", |
| 17 | + usedefault=True, |
| 18 | + desc="CIFTI surface target space", |
| 19 | + ) |
| 20 | + grayordinates = traits.Enum( |
| 21 | + "91k", "170k", usedefault=True, desc="Final CIFTI grayordinates" |
| 22 | + ) |
| 23 | + scalar_surfs = traits.List( |
| 24 | + File(exists=True), |
| 25 | + mandatory=True, |
| 26 | + desc="list of surface BOLD GIFTI files (length 2 with order [L,R])", |
| 27 | + ) |
| 28 | + scalar_name = traits.Str(mandatory=True, desc="Name of scalar") |
| 29 | + |
| 30 | + |
| 31 | +class _GenerateDScalarOutputSpec(TraitedSpec): |
| 32 | + out_file = File(desc="generated CIFTI file") |
| 33 | + out_metadata = File(desc="CIFTI metadata JSON") |
| 34 | + |
| 35 | + |
| 36 | +class GenerateDScalar(SimpleInterface): |
| 37 | + """ |
| 38 | + Generate a HCP-style CIFTI-2 image from scalar surface files. |
| 39 | + """ |
| 40 | + input_spec = _GenerateDScalarInputSpec |
| 41 | + output_spec = _GenerateDScalarOutputSpec |
| 42 | + |
| 43 | + def _run_interface(self, runtime): |
| 44 | + |
| 45 | + surface_labels, metadata = _prepare_cifti(self.inputs.grayordinates) |
| 46 | + self._results["out_file"] = _create_cifti_image( |
| 47 | + self.inputs.scalar_surfs, |
| 48 | + surface_labels, |
| 49 | + self.inputs.scalar_name, |
| 50 | + metadata, |
| 51 | + ) |
| 52 | + metadata_file = Path("dscalar.json").absolute() |
| 53 | + metadata_file.write_text(json.dumps(metadata, indent=2)) |
| 54 | + self._results["out_metadata"] = str(metadata_file) |
| 55 | + return runtime |
| 56 | + |
| 57 | + |
| 58 | +def _prepare_cifti(grayordinates: str) -> ty.Tuple[list, dict]: |
| 59 | + """ |
| 60 | + Fetch the required templates needed for CIFTI-2 generation, based on input surface density. |
| 61 | +
|
| 62 | + Parameters |
| 63 | + ---------- |
| 64 | + grayordinates : |
| 65 | + Total CIFTI grayordinates (91k, 170k) |
| 66 | +
|
| 67 | + Returns |
| 68 | + ------- |
| 69 | + surface_labels |
| 70 | + Surface label files for vertex inclusion/exclusion. |
| 71 | + metadata |
| 72 | + Dictionary with BIDS metadata. |
| 73 | +
|
| 74 | + Examples |
| 75 | + -------- |
| 76 | + >>> surface_labels, metadata = _prepare_cifti('91k') |
| 77 | + >>> surface_labels # doctest: +ELLIPSIS |
| 78 | + ['.../tpl-fsLR_hemi-L_den-32k_desc-nomedialwall_dparc.label.gii', \ |
| 79 | + '.../tpl-fsLR_hemi-R_den-32k_desc-nomedialwall_dparc.label.gii'] |
| 80 | + >>> metadata # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE |
| 81 | + {'Density': '91,282 grayordinates corresponding to all of the grey matter sampled at a \ |
| 82 | +2mm average vertex spacing...', 'SpatialReference': {'CIFTI_STRUCTURE_CORTEX_LEFT': ...}} |
| 83 | +
|
| 84 | + """ |
| 85 | + |
| 86 | + grayord_key = { |
| 87 | + "91k": { |
| 88 | + "surface-den": "32k", |
| 89 | + "tf-res": "02", |
| 90 | + "grayords": "91,282", |
| 91 | + "res-mm": "2mm" |
| 92 | + }, |
| 93 | + "170k": { |
| 94 | + "surface-den": "59k", |
| 95 | + "tf-res": "06", |
| 96 | + "grayords": "170,494", |
| 97 | + "res-mm": "1.6mm" |
| 98 | + } |
| 99 | + } |
| 100 | + if grayordinates not in grayord_key: |
| 101 | + raise NotImplementedError("Grayordinates {grayordinates} is not supported.") |
| 102 | + |
| 103 | + total_grayords = grayord_key[grayordinates]['grayords'] |
| 104 | + res_mm = grayord_key[grayordinates]['res-mm'] |
| 105 | + surface_density = grayord_key[grayordinates]['surface-den'] |
| 106 | + # Fetch templates |
| 107 | + surface_labels = [ |
| 108 | + str( |
| 109 | + tf.get( |
| 110 | + "fsLR", |
| 111 | + density=surface_density, |
| 112 | + hemi=hemi, |
| 113 | + desc="nomedialwall", |
| 114 | + suffix="dparc", |
| 115 | + raise_empty=True, |
| 116 | + ) |
| 117 | + ) |
| 118 | + for hemi in ("L", "R") |
| 119 | + ] |
| 120 | + |
| 121 | + tf_url = "https://templateflow.s3.amazonaws.com" |
| 122 | + surfaces_url = ( # midthickness is the default, but varying levels of inflation are all valid |
| 123 | + f"{tf_url}/tpl-fsLR/tpl-fsLR_den-{surface_density}_hemi-%s_midthickness.surf.gii" |
| 124 | + ) |
| 125 | + metadata = { |
| 126 | + "Density": ( |
| 127 | + f"{total_grayords} grayordinates corresponding to all of the grey matter sampled at a " |
| 128 | + f"{res_mm} average vertex spacing on the surface" |
| 129 | + ), |
| 130 | + "SpatialReference": { |
| 131 | + "CIFTI_STRUCTURE_CORTEX_LEFT": surfaces_url % "L", |
| 132 | + "CIFTI_STRUCTURE_CORTEX_RIGHT": surfaces_url % "R", |
| 133 | + } |
| 134 | + } |
| 135 | + return surface_labels, metadata |
| 136 | + |
| 137 | + |
| 138 | +def _create_cifti_image( |
| 139 | + scalar_surfs: ty.Tuple[str, str], |
| 140 | + surface_labels: ty.Tuple[str, str], |
| 141 | + scalar_name: str, |
| 142 | + metadata: ty.Optional[dict] = None, |
| 143 | +): |
| 144 | + """ |
| 145 | + Generate CIFTI image in target space. |
| 146 | +
|
| 147 | + Parameters |
| 148 | + ---------- |
| 149 | + scalar_surfs |
| 150 | + Surface scalar files (L,R) |
| 151 | + surface_labels |
| 152 | + Surface label files used to remove medial wall (L,R) |
| 153 | + metadata |
| 154 | + Metadata to include in CIFTI header |
| 155 | + scalar_name |
| 156 | + Name to apply to scalar map |
| 157 | +
|
| 158 | + Returns |
| 159 | + ------- |
| 160 | + out : |
| 161 | + BOLD data saved as CIFTI dtseries |
| 162 | + """ |
| 163 | + brainmodels = [] |
| 164 | + arrays = [] |
| 165 | + |
| 166 | + for idx, hemi in enumerate(('left', 'right')): |
| 167 | + labels = nb.load(surface_labels[idx]) |
| 168 | + mask = np.bool_[labels.darrays[0].data] |
| 169 | + |
| 170 | + struct = f'cortex_{hemi}' |
| 171 | + brainmodels.append( |
| 172 | + ci.BrainModelAxis(struct, vertex=np.nonzero(mask)[0], nvertices={struct: len(mask)}) |
| 173 | + ) |
| 174 | + |
| 175 | + morph_scalar = nb.load(scalar_surfs[idx]) |
| 176 | + arrays.append(morph_scalar.darrays[0].data[mask].astype("float32")) |
| 177 | + |
| 178 | + # provide some metadata to CIFTI matrix |
| 179 | + if not metadata: |
| 180 | + metadata = { |
| 181 | + "surface": "fsLR", |
| 182 | + } |
| 183 | + |
| 184 | + # generate and save CIFTI image |
| 185 | + hdr = ci.Cifti2Header.from_axes( |
| 186 | + (ci.ScalarAxis([scalar_name]), brainmodels[0] + brainmodels[1]) |
| 187 | + ) |
| 188 | + hdr.matrix.metadata.update(metadata) |
| 189 | + |
| 190 | + img = ci.Cifti2Image(dataobj=np.atleast_2d(np.concatenate(arrays)), header=hdr) |
| 191 | + img.nifti_header.set_intent("NIFTI_INTENT_CONNECTIVITY_DENSE_SCALARS") |
| 192 | + |
| 193 | + out_file = "{}.dscalar.nii".format(split_filename(scalar_surfs[0])[1]) |
| 194 | + img.to_filename(out_file) |
| 195 | + return Path.cwd() / out_file |
0 commit comments