def test_pconnscalar(): parcel_map = create_parcel_map((0, 1)) scalar_map = create_scalar_map((2, )) matrix = ci.Cifti2Matrix() matrix.append(parcel_map) matrix.append(scalar_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(3, 3, 13) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_' 'PARCELLATED_SCALAR') with InTemporaryDirectory(): ci.save(img, 'test.pconnscalar.nii') img2 = ci.load('test.pconnscalar.nii') assert_equal(img.nifti_header.get_intent()[0], 'ConnPPSc') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) assert_equal(img2.header.matrix.get_index_map(0), img2.header.matrix.get_index_map(1)) check_parcel_map(img2.header.matrix.get_index_map(0)) check_scalar_map(img2.header.matrix.get_index_map(2)) del img2
def test_pconnscalar(): parcel_map = create_parcel_map((0, 1)) scalar_map = create_scalar_map((2, )) matrix = ci.Cifti2Matrix() matrix.append(parcel_map) matrix.append(scalar_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(3, 3, 13) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_' 'PARCELLATED_SCALAR') with InTemporaryDirectory(): ci.save(img, 'test.pconnscalar.nii') img2 = ci.load('test.pconnscalar.nii') assert_equal(img.nifti_header.get_intent()[0], 'ConnPPSc') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) assert_equal(img2.header.matrix.get_index_map(0), img2.header.matrix.get_index_map(1)) check_parcel_map(img2.header.matrix.get_index_map(0)) check_scalar_map(img2.header.matrix.get_index_map(2)) del img2
def test_pconn(): mapping = create_parcel_map((0, 1)) matrix = ci.Cifti2Matrix() matrix.append(mapping) hdr = ci.Cifti2Header(matrix) data = np.random.randn(3, 3) img = ci.Cifti2Image(data, hdr) with InTemporaryDirectory(): ci.save(img, 'test.pconn.nii') img2 = ci.load('test.pconn.nii') assert_true((img2.get_data() == data).all()) assert_equal(img2.header.matrix.get_index_map(0), img2.header.matrix.get_index_map(1)) check_parcel_map(img2.header.matrix.get_index_map(0)) del img2
def test_plabel(): label_map = create_label_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(label_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 3) img = ci.Cifti2Image(data, hdr) with InTemporaryDirectory(): ci.save(img, 'test.plabel.nii') img2 = ci.load('test.plabel.nii') assert_true((img2.get_data() == data).all()) check_label_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_dscalar(): scalar_map = create_scalar_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(scalar_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 9) img = ci.Cifti2Image(data, hdr) with InTemporaryDirectory(): ci.save(img, 'test.dscalar.nii') img2 = ci.load('test.dscalar.nii') assert_true((img2.get_data() == data).all()) check_scalar_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_plabel(): label_map = create_label_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(label_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 4) img = ci.Cifti2Image(data, hdr) with InTemporaryDirectory(): ci.save(img, 'test.plabel.nii') img2 = ci.load('test.plabel.nii') assert img.nifti_header.get_intent()[0] == 'ConnUnknown' assert isinstance(img2, ci.Cifti2Image) assert_array_equal(img2.get_fdata(), data) check_label_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_pconn(): mapping = create_parcel_map((0, 1)) matrix = ci.Cifti2Matrix() matrix.append(mapping) hdr = ci.Cifti2Header(matrix) data = np.random.randn(4, 4) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED') with InTemporaryDirectory(): ci.save(img, 'test.pconn.nii') img2 = ci.load('test.pconn.nii') assert img.nifti_header.get_intent()[0] == 'ConnParcels' assert isinstance(img2, ci.Cifti2Image) assert_array_equal(img2.get_fdata(), data) assert img2.header.matrix.get_index_map( 0) == img2.header.matrix.get_index_map(1) check_parcel_map(img2.header.matrix.get_index_map(0)) del img2
def test_dconn(): mapping = create_geometry_map((0, 1)) matrix = ci.Cifti2Matrix() matrix.append(mapping) hdr = ci.Cifti2Header(matrix) data = np.random.randn(9, 9) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE') with InTemporaryDirectory(): ci.save(img, 'test.dconn.nii') img2 = nib.load('test.dconn.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDense') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) assert_equal(img2.header.matrix.get_index_map(0), img2.header.matrix.get_index_map(1)) check_geometry_map(img2.header.matrix.get_index_map(0)) del img2
def test_dconn(): mapping = create_geometry_map((0, 1)) matrix = ci.Cifti2Matrix() matrix.append(mapping) hdr = ci.Cifti2Header(matrix) data = np.random.randn(9, 9) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE') with InTemporaryDirectory(): ci.save(img, 'test.dconn.nii') img2 = nib.load('test.dconn.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDense') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) assert_equal(img2.header.matrix.get_index_map(0), img2.header.matrix.get_index_map(1)) check_geometry_map(img2.header.matrix.get_index_map(0)) del img2
def test_plabel(): label_map = create_label_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(label_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 3) img = ci.Cifti2Image(data, hdr) with InTemporaryDirectory(): ci.save(img, 'test.plabel.nii') img2 = ci.load('test.plabel.nii') assert_equal(img.nifti_header.get_intent()[0], 'ConnUnknown') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_label_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_pscalar(): scalar_map = create_scalar_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(scalar_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 4) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SCALAR') with InTemporaryDirectory(): ci.save(img, 'test.pscalar.nii') img2 = nib.load('test.pscalar.nii') assert img2.nifti_header.get_intent()[0] == 'ConnParcelScalr' assert isinstance(img2, ci.Cifti2Image) assert_array_equal(img2.get_fdata(), data) check_scalar_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_dlabel(): label_map = create_label_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(label_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 10) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_LABELS') with InTemporaryDirectory(): ci.save(img, 'test.dlabel.nii') img2 = nib.load('test.dlabel.nii') assert img2.nifti_header.get_intent()[0] == 'ConnDenseLabel' assert isinstance(img2, ci.Cifti2Image) assert_array_equal(img2.get_fdata(), data) check_label_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_dtseries(): series_map = create_series_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(series_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(13, 10) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES') with InTemporaryDirectory(): ci.save(img, 'test.dtseries.nii') img2 = nib.load('test.dtseries.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDenseSeries') assert_true(isinstance(img2, ci.Cifti2Image)) assert_array_equal(img2.get_fdata(), data) check_series_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_pdconn(): geometry_map = create_geometry_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(geometry_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(10, 4) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_DENSE') with InTemporaryDirectory(): ci.save(img, 'test.pdconn.nii') img2 = ci.load('test.pdconn.nii') assert img2.nifti_header.get_intent()[0] == 'ConnParcelDense' assert isinstance(img2, ci.Cifti2Image) assert_array_equal(img2.get_fdata(), data) check_geometry_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_ptseries(): series_map = create_series_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(series_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(13, 3) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SERIES') with InTemporaryDirectory(): ci.save(img, 'test.ptseries.nii') img2 = nib.load('test.ptseries.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnParcelSries') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_series_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_dpconn(): parcel_map = create_parcel_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(parcel_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 3) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_PARCELLATED') with InTemporaryDirectory(): ci.save(img, 'test.dpconn.nii') img2 = ci.load('test.dpconn.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDenseParcel') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_parcel_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_dscalar(): scalar_map = create_scalar_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(scalar_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 9) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_SCALARS') with InTemporaryDirectory(): ci.save(img, 'test.dscalar.nii') img2 = nib.load('test.dscalar.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDenseScalar') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_scalar_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_dpconn(): parcel_map = create_parcel_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(parcel_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 3) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_PARCELLATED') with InTemporaryDirectory(): ci.save(img, 'test.dpconn.nii') img2 = ci.load('test.dpconn.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDenseParcel') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_parcel_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_ptseries(): series_map = create_series_map((0, )) parcel_map = create_parcel_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(series_map) matrix.append(parcel_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(13, 3) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SERIES') with InTemporaryDirectory(): ci.save(img, 'test.ptseries.nii') img2 = nib.load('test.ptseries.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnParcelSries') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_series_map(img2.header.matrix.get_index_map(0)) check_parcel_map(img2.header.matrix.get_index_map(1)) del img2
def test_dscalar(): scalar_map = create_scalar_map((0, )) geometry_map = create_geometry_map((1, )) matrix = ci.Cifti2Matrix() matrix.append(scalar_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) data = np.random.randn(2, 9) img = ci.Cifti2Image(data, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_SCALARS') with InTemporaryDirectory(): ci.save(img, 'test.dscalar.nii') img2 = nib.load('test.dscalar.nii') assert_equal(img2.nifti_header.get_intent()[0], 'ConnDenseScalar') assert_true(isinstance(img2, ci.Cifti2Image)) assert_true((img2.get_data() == data).all()) check_scalar_map(img2.header.matrix.get_index_map(0)) check_geometry_map(img2.header.matrix.get_index_map(1)) del img2
def test_readwritedata(): with InTemporaryDirectory(): for name in datafiles: img = ci.load(name) ci.save(img, 'test.nii') img2 = ci.load('test.nii') assert len(img.header.matrix) == len(img2.header.matrix) # Order should be preserved in load/save for mim1, mim2 in zip(img.header.matrix, img2.header.matrix): named_maps1 = [m_ for m_ in mim1 if isinstance(m_, ci.Cifti2NamedMap)] named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)] assert len(named_maps1) == len(named_maps2) for map1, map2 in zip(named_maps1, named_maps2): assert map1.map_name == map2.map_name if map1.label_table is None: assert map2.label_table is None else: assert len(map1.label_table) == len(map2.label_table) assert_array_almost_equal(img.dataobj, img2.dataobj)
def main(): args = parse_arguments() if args.t: print( "roi : {}\n".format(args.roi) + "input : {}\n".format(args.input) + "prefix : {}\n".format(args.prefix) ) return 0 # do file checking here if not os.path.isfile(args.roi): print("roi file does not exist: {}".format(args.roi)) return -1 df = pd.read_csv(args.input) for i in df.FilePath: if not os.path.isfile(i): print("input file does not exist: {}".format(i)) return -1 out_dir = os.path.dirname(args.prefix) if len(out_dir) == 0: out_dir = "./" out_base = os.path.basename(args.prefix) if not os.path.isdir(out_dir): print("out directory does not exist: {}".format(out_dir)) return -1 m1, m2 = calc_group_correlation(df, args.roi) rcii = ci.load(args.roi) out_m1 = CH.create_dscalar_from_template(rcii, m1, df.Identifier) out_m2 = CH.create_dscalar_from_template(rcii, m2, df.Identifier) ci.save(out_m1, args.prefix + "_m1.dscalar.nii") ci.save(out_m2, args.prefix + "_m2.dscalar.nii") return 0
def test_readwritedata(): with InTemporaryDirectory(): for name in datafiles: img = ci.load(name) ci.save(img, 'test.nii') img2 = ci.load('test.nii') assert_equal(len(img.header.matrix), len(img2.header.matrix)) # Order should be preserved in load/save for mim1, mim2 in zip(img.header.matrix, img2.header.matrix): named_maps1 = [m_ for m_ in mim1 if isinstance(m_, ci.Cifti2NamedMap)] named_maps2 = [m_ for m_ in mim2 if isinstance(m_, ci.Cifti2NamedMap)] assert_equal(len(named_maps1), len(named_maps2)) for map1, map2 in zip(named_maps1, named_maps2): assert_equal(map1.map_name, map2.map_name) if map1.label_table is None: assert_true(map2.label_table is None) else: assert_equal(len(map1.label_table), len(map2.label_table)) assert_array_almost_equal(img.dataobj, img2.dataobj)
def _create_cifti_image(bold_file, label_file, annotation_files, gii_files, volume_target, surface_target, tr): """ Generate CIFTI image in target space Parameters bold_file : 4D BOLD timeseries label_file : label atlas annotation_files : FreeSurfer annotations gii_files : 4D BOLD surface timeseries in GIFTI format volume_target : label atlas space surface_target : gii_files space tr : repetition timeseries Returns out_file : BOLD data as CIFTI dtseries """ label_img = nb.load(label_file) bold_img = resample_to_img(bold_file, label_img) bold_data = bold_img.get_data() timepoints = bold_img.shape[3] label_data = label_img.get_data() # set up CIFTI information series_map = ci.Cifti2MatrixIndicesMap((0, ), 'CIFTI_INDEX_TYPE_SERIES', number_of_series_points=timepoints, series_exponent=0, series_start=0.0, series_step=tr, series_unit='SECOND') # Create CIFTI brain models idx_offset = 0 brainmodels = [] bm_ts = np.empty((timepoints, 0)) for structure, labels in CIFTI_STRUCT_WITH_LABELS.items(): if labels is None: # surface model model_type = "CIFTI_MODEL_TYPE_SURFACE" # use the corresponding annotation hemi = structure.split('_')[-1] annot = nb.freesurfer.read_annot(annotation_files[hemi == "RIGHT"]) # currently only supports L/R cortex gii = nb.load(gii_files[hemi == "RIGHT"]) # calculate total number of vertices surf_verts = len(annot[0]) # remove medial wall for CIFTI format vert_idx = np.nonzero(annot[0] != annot[2].index(b'unknown'))[0] # extract values across volumes ts = np.array([tsarr.data[vert_idx] for tsarr in gii.darrays]) vert_idx = ci.Cifti2VertexIndices(vert_idx) bm = ci.Cifti2BrainModel(index_offset=idx_offset, index_count=len(vert_idx), model_type=model_type, brain_structure=structure, vertex_indices=vert_idx, n_surface_vertices=surf_verts) bm_ts = np.column_stack((bm_ts, ts)) idx_offset += len(vert_idx) brainmodels.append(bm) else: model_type = "CIFTI_MODEL_TYPE_VOXELS" vox = [] ts = None for label in labels: ijk = np.nonzero(label_data == label) ts = (bold_data[ijk] if ts is None else np.concatenate((ts, bold_data[ijk]))) vox += [[ijk[0][ix], ijk[1][ix], ijk[2][ix]] for ix, row in enumerate(ts)] bm_ts = np.column_stack((bm_ts, ts.T)) vox = ci.Cifti2VoxelIndicesIJK(vox) bm = ci.Cifti2BrainModel(index_offset=idx_offset, index_count=len(vox), model_type=model_type, brain_structure=structure, voxel_indices_ijk=vox) idx_offset += len(vox) brainmodels.append(bm) volume = ci.Cifti2Volume( bold_img.shape[:3], ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ(-3, bold_img.affine)) brainmodels.append(volume) # create CIFTI geometry based on brainmodels geometry_map = ci.Cifti2MatrixIndicesMap((1, ), 'CIFTI_INDEX_TYPE_BRAIN_MODELS', maps=brainmodels) # provide some metadata to CIFTI matrix meta = { "target_surface": surface_target, "target_volume": volume_target, } # generate and save CIFTI image matrix = ci.Cifti2Matrix() matrix.append(series_map) matrix.append(geometry_map) matrix.metadata = ci.Cifti2MetaData(meta) hdr = ci.Cifti2Header(matrix) img = ci.Cifti2Image(bm_ts, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES') _, out_base, _ = split_filename(bold_file) out_file = "{}.dtseries.nii".format(out_base) ci.save(img, out_file) return os.path.join(os.getcwd(), out_file)
def _create_dtseries_cifti(timepoints, models): """Create a dense timeseries CIFTI-2 file""" import nibabel.cifti2 as ci def create_series_map(): return ci.Cifti2MatrixIndicesMap((0, ), 'CIFTI_INDEX_TYPE_SERIES', number_of_series_points=timepoints, series_exponent=0, series_start=0, series_step=1, series_unit='SECOND') def create_geometry_map(): index_offset = 0 brain_models = [] timeseries = np.zeros((timepoints, 0)) for name, data in models: if "CORTEX" in name: model_type = "CIFTI_MODEL_TYPE_SURFACE" attr = "vertex_indices" indices = ci.Cifti2VertexIndices(np.arange(len(data))) else: model_type = "CIFTI_MODEL_TYPE_VOXELS" attr = "voxel_indices_ijk" indices = ci.Cifti2VoxelIndicesIJK(np.arange(len(data))) bm = ci.Cifti2BrainModel( index_offset=index_offset, index_count=len(data), model_type=model_type, brain_structure=name, ) setattr(bm, attr, indices) index_offset += len(data) brain_models.append(bm) timeseries = np.column_stack((timeseries, data.T)) brain_models.append( ci.Cifti2Volume( (4, 4, 4), ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ( -3, np.eye(4)), )) return ci.Cifti2MatrixIndicesMap( (1, ), "CIFTI_INDEX_TYPE_BRAIN_MODELS", maps=brain_models, ), timeseries matrix = ci.Cifti2Matrix() series_map = create_series_map() geometry_map, ts = create_geometry_map() matrix.append(series_map) matrix.append(geometry_map) hdr = ci.Cifti2Header(matrix) img = ci.Cifti2Image(dataobj=ts, header=hdr) img.nifti_header.set_intent("NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES") out_file = Path("test.dtseries.nii").absolute() ci.save(img, out_file) return out_file
def _create_cifti_image(bold_file, label_file, bold_surfs, annotation_files, tr, targets): """ Generate CIFTI image in target space. Parameters ---------- bold_file : str BOLD volumetric timeseries label_file : str Subcortical label file bold_surfs : list BOLD surface timeseries [L,R] annotation_files : list Surface label files used to remove medial wall tr : float BOLD repetition time targets : tuple or list Surface and volumetric output spaces Returns ------- out : BOLD data saved as CIFTI dtseries """ bold_img = nb.load(bold_file) label_img = nb.load(label_file) if label_img.shape != bold_img.shape[:3]: warnings.warn("Resampling bold volume to match label dimensions") bold_img = resample_to_img(bold_img, label_img) bold_data = bold_img.get_fdata(dtype='float32') timepoints = bold_img.shape[3] label_data = np.asanyarray(label_img.dataobj).astype('int16') # Create brain models idx_offset = 0 brainmodels = [] bm_ts = np.empty((timepoints, 0)) for structure, labels in CIFTI_STRUCT_WITH_LABELS.items(): if labels is None: # surface model model_type = "CIFTI_MODEL_TYPE_SURFACE" # use the corresponding annotation hemi = structure.split('_')[-1] # currently only supports L/R cortex surf = nb.load(bold_surfs[hemi == "RIGHT"]) surf_verts = len(surf.darrays[0].data) if annotation_files[0].endswith('.annot'): annot = nb.freesurfer.read_annot( annotation_files[hemi == "RIGHT"]) # remove medial wall medial = np.nonzero(annot[0] != annot[2].index(b'unknown'))[0] else: annot = nb.load(annotation_files[hemi == "RIGHT"]) medial = np.nonzero(annot.darrays[0].data)[0] # extract values across volumes ts = np.array([tsarr.data[medial] for tsarr in surf.darrays]) vert_idx = ci.Cifti2VertexIndices(medial) bm = ci.Cifti2BrainModel(index_offset=idx_offset, index_count=len(vert_idx), model_type=model_type, brain_structure=structure, vertex_indices=vert_idx, n_surface_vertices=surf_verts) idx_offset += len(vert_idx) bm_ts = np.column_stack((bm_ts, ts)) else: model_type = "CIFTI_MODEL_TYPE_VOXELS" vox = [] ts = None for label in labels: ijk = np.nonzero(label_data == label) if ijk[0].size == 0: # skip label if nothing matches continue ts = (bold_data[ijk] if ts is None else np.concatenate( (ts, bold_data[ijk]))) vox += [[ijk[0][ix], ijk[1][ix], ijk[2][ix]] for ix, row in enumerate(ts)] vox = ci.Cifti2VoxelIndicesIJK(vox) bm = ci.Cifti2BrainModel(index_offset=idx_offset, index_count=len(vox), model_type=model_type, brain_structure=structure, voxel_indices_ijk=vox) idx_offset += len(vox) bm_ts = np.column_stack((bm_ts, ts.T)) # add each brain structure to list brainmodels.append(bm) # add volume information brainmodels.append( ci.Cifti2Volume( bold_img.shape[:3], ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ( -3, bold_img.affine))) # generate Matrix information series_map = ci.Cifti2MatrixIndicesMap((0, ), 'CIFTI_INDEX_TYPE_SERIES', number_of_series_points=timepoints, series_exponent=0, series_start=0.0, series_step=tr, series_unit='SECOND') geometry_map = ci.Cifti2MatrixIndicesMap((1, ), 'CIFTI_INDEX_TYPE_BRAIN_MODELS', maps=brainmodels) # provide some metadata to CIFTI matrix meta = { "surface": targets[0], "volume": targets[1], } # generate and save CIFTI image matrix = ci.Cifti2Matrix() matrix.append(series_map) matrix.append(geometry_map) matrix.metadata = ci.Cifti2MetaData(meta) hdr = ci.Cifti2Header(matrix) img = ci.Cifti2Image(bm_ts, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES') out_file = "{}.dtseries.nii".format(split_filename(bold_file)[1]) ci.save(img, out_file) return os.path.join(os.getcwd(), out_file)
def _create_cifti_image(bold_file, label_file, annotation_files, gii_files, volume_target, surface_target, tr): """ Generate CIFTI image in target space Parameters bold_file : 4D BOLD timeseries label_file : label atlas annotation_files : FreeSurfer annotations gii_files : 4D BOLD surface timeseries in GIFTI format volume_target : label atlas space surface_target : gii_files space tr : repetition timeseries Returns out_file : BOLD data as CIFTI dtseries """ label_img = nb.load(label_file) bold_img = resample_to_img(bold_file, label_img) bold_data = bold_img.get_data() timepoints = bold_img.shape[3] label_data = label_img.get_data() # set up CIFTI information series_map = ci.Cifti2MatrixIndicesMap( (0, ), 'CIFTI_INDEX_TYPE_SERIES', number_of_series_points=timepoints, series_exponent=0, series_start=0.0, series_step=tr, series_unit='SECOND') # Create CIFTI brain models idx_offset = 0 brainmodels = [] bm_ts = np.empty((timepoints, 0)) for structure, labels in CIFTI_STRUCT_WITH_LABELS.items(): if labels is None: # surface model model_type = "CIFTI_MODEL_TYPE_SURFACE" # use the corresponding annotation hemi = structure.split('_')[-1] annot = nb.freesurfer.read_annot( annotation_files[hemi == "RIGHT"]) # currently only supports L/R cortex gii = nb.load(gii_files[hemi == "RIGHT"]) # calculate total number of vertices surf_verts = len(annot[0]) # remove medial wall for CIFTI format vert_idx = np.nonzero( annot[0] != annot[2].index(b'unknown'))[0] # extract values across volumes ts = np.array([tsarr.data[vert_idx] for tsarr in gii.darrays]) vert_idx = ci.Cifti2VertexIndices(vert_idx) bm = ci.Cifti2BrainModel(index_offset=idx_offset, index_count=len(vert_idx), model_type=model_type, brain_structure=structure, vertex_indices=vert_idx, n_surface_vertices=surf_verts) bm_ts = np.column_stack((bm_ts, ts)) idx_offset += len(vert_idx) brainmodels.append(bm) else: model_type = "CIFTI_MODEL_TYPE_VOXELS" vox = [] ts = None for label in labels: ijk = np.nonzero(label_data == label) ts = (bold_data[ijk] if ts is None else np.concatenate( (ts, bold_data[ijk]))) vox += [[ijk[0][ix], ijk[1][ix], ijk[2][ix]] for ix, row in enumerate(ts)] bm_ts = np.column_stack((bm_ts, ts.T)) vox = ci.Cifti2VoxelIndicesIJK(vox) bm = ci.Cifti2BrainModel(index_offset=idx_offset, index_count=len(vox), model_type=model_type, brain_structure=structure, voxel_indices_ijk=vox) idx_offset += len(vox) brainmodels.append(bm) volume = ci.Cifti2Volume( bold_img.shape[:3], ci.Cifti2TransformationMatrixVoxelIndicesIJKtoXYZ( -3, bold_img.affine)) brainmodels.append(volume) # create CIFTI geometry based on brainmodels geometry_map = ci.Cifti2MatrixIndicesMap( (1, ), 'CIFTI_INDEX_TYPE_BRAIN_MODELS', maps=brainmodels) # provide some metadata to CIFTI matrix meta = { "target_surface": surface_target, "target_volume": volume_target, } # generate and save CIFTI image matrix = ci.Cifti2Matrix() matrix.append(series_map) matrix.append(geometry_map) matrix.metadata = ci.Cifti2MetaData(meta) hdr = ci.Cifti2Header(matrix) img = ci.Cifti2Image(bm_ts, hdr) img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES') _, out_base, _ = split_filename(bold_file) out_file = "{}.dtseries.nii".format(out_base) ci.save(img, out_file) return os.path.join(os.getcwd(), out_file)