def write_mesh(cor, tri, filename): from nibabel.gifti import GiftiImage, GiftiDataArray nimg = GiftiImage() intent = 'NIFTI_INTENT_POINTSET' nimg.add_gifti_data_array(GiftiDataArray.from_array(cor, intent)) intent = 'NIFTI_INTENT_TRIANGLE' nimg.add_gifti_data_array(GiftiDataArray.from_array(tri, intent)) gifti.write(nimg, filename)
def write_mesh(cor, tri, filename): from nibabel.gifti import GiftiImage, GiftiDataArray nimg = GiftiImage() intent = 'NIFTI_INTENT_POINTSET' nimg.add_gifti_data_array(GiftiDataArray.from_array(cor,intent)) intent = 'NIFTI_INTENT_TRIANGLE' nimg.add_gifti_data_array(GiftiDataArray.from_array(tri,intent)) gifti.write(nimg, filename)
def test_to_xml_open_close_deprecations(): # Smoke test on deprecated functions da = GiftiDataArray(np.ones((1,)), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) assert_true(isinstance(da.to_xml_open(), string_types)) assert_equal(len(w), 1) with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) assert_true(isinstance(da.to_xml_close(), string_types)) assert_equal(len(w), 1)
def test_num_dim_deprecation(): da = GiftiDataArray(np.ones((2, 3, 4))) # num_dim is property, set automatically from len(da.dims) assert_equal(da.num_dim, 3) with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) # OK setting num_dim to correct value, but raises DeprecationWarning da.num_dim = 3 assert_equal(len(w), 1) # Any other value gives a ValueError assert_raises(ValueError, setattr, da, 'num_dim', 4)
def test_to_xml_open_close_deprecations(): # Smoke test on deprecated functions da = GiftiDataArray(np.ones((1, )), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) assert_true(isinstance(da.to_xml_open(), str)) assert_equal(len(w), 1) with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) assert_true(isinstance(da.to_xml_close(), str)) assert_equal(len(w), 1)
def mesh_from_arrays(coord, triangles, path=None): """ Create a mesh object from two arrays fixme: intent should be set ! """ carray = GiftiDataArray().from_array(coord.astype(np.float32), "NIFTI_INTENT_POINTSET") tarray = GiftiDataArray().from_array(triangles, "NIFTI_INTENT_TRIANGLE") img = GiftiImage(darrays=[carray, tarray]) if path is not None: write(img, path) return img
def write(self, surface_obj, file_path): image_metadata = GiftiMetaData().from_dict( surface_obj.generic_metadata) vertices_metadata = GiftiMetaData().from_dict( surface_obj.vertices_metadata) triangles_metadata = GiftiMetaData().from_dict( surface_obj.triangles_metadata) gifti_image = GiftiImage() gifti_image.set_metadata(image_metadata) data = GiftiDataArray(surface_obj.vertices, datatype='NIFTI_TYPE_FLOAT32', intent='NIFTI_INTENT_POINTSET') data.meta = vertices_metadata data.coordsys = surface_obj.vertices_coord_system gifti_image.add_gifti_data_array(data) data = GiftiDataArray(surface_obj.triangles, datatype='NIFTI_TYPE_INT32', intent='NIFTI_INTENT_TRIANGLE') data.meta = triangles_metadata data.coordsys = None gifti_image.add_gifti_data_array(data) nibabel.save(gifti_image, file_path)
def test_dataarray_from_array(): with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) da = GiftiDataArray.from_array(np.ones((3, 4))) assert_equal(len(w), 1) for dt_code in data_type_codes.value_set(): data_type = data_type_codes.type[dt_code] if data_type is np.void: # not supported continue arr = np.zeros((10, 3), dtype=data_type) da = GiftiDataArray.from_array(arr, 'triangle') assert_equal(da.datatype, data_type_codes[arr.dtype]) bs_arr = arr.byteswap().newbyteorder() da = GiftiDataArray.from_array(bs_arr, 'triangle') assert_equal(da.datatype, data_type_codes[arr.dtype])
def ply2gii(in_file, metadata, out_file=None): """Convert from ply to GIfTI""" from pathlib import Path from numpy import eye from nibabel.gifti import ( GiftiMetaData, GiftiCoordSystem, GiftiImage, GiftiDataArray, ) from pyntcloud import PyntCloud in_file = Path(in_file) surf = PyntCloud.from_file(str(in_file)) # Update centroid metadata metadata.update( zip( ("SurfaceCenterX", "SurfaceCenterY", "SurfaceCenterZ"), ["%.4f" % c for c in surf.centroid], )) # Prepare data arrays da = ( GiftiDataArray( data=surf.xyz.astype("float32"), datatype="NIFTI_TYPE_FLOAT32", intent="NIFTI_INTENT_POINTSET", meta=GiftiMetaData.from_dict(metadata), coordsys=GiftiCoordSystem(xform=eye(4), xformspace=3), ), GiftiDataArray( data=surf.mesh.values, datatype="NIFTI_TYPE_INT32", intent="NIFTI_INTENT_TRIANGLE", coordsys=None, ), ) surfgii = GiftiImage(darrays=da) if out_file is None: out_file = fname_presuffix(in_file.name, suffix=".gii", use_ext=False, newpath=str(Path.cwd())) surfgii.to_filename(str(out_file)) return out_file
def elementary_contrasts_surf(con_imgs, var_imgs): """ """ from nibabel.gifti import GiftiDataArray, GiftiImage outputs = [] n_contrasts = 4 for i in range(n_contrasts): con = nib.load(con_imgs[i]).darrays[0].data var = nib.load(var_imgs[i]).darrays[0].data effects = [ con - nib.load(con_imgs[j]).darrays[0].data for j in range(n_contrasts) if j != i ] variance = [ var + nib.load(var_imgs[j]).darrays[0].data for j in range(n_contrasts) if j != i ] fixed_con = np.array(effects).sum(0) fixed_var = np.array(variance).sum(0) stat = fixed_con / np.sqrt(fixed_var) output = [] intents = ['NIFTI_INTENT_ESTIMATE', 'NIFTI_INTENT_ESTIMATE', 't test'] arrays = [fixed_con, fixed_var, stat] for array, intent in zip(arrays, intents): gii = GiftiImage( darrays=[GiftiDataArray().from_array(array, intent)]) output.append(gii) outputs.append(output) return (outputs)
def run_surface_glm(dmtx, contrasts, fmri_path, subject_session_output_dir): """ """ from nibabel.gifti import read, write, GiftiDataArray, GiftiImage from nilearn.glm.first_level import run_glm as run_glm_nl from nilearn.glm import compute_contrast Y = np.array([darrays.data for darrays in read(fmri_path).darrays]) labels, res = run_glm_nl(Y, dmtx.values) # Estimate the contrasts print('Computing contrasts...') side = fmri_path[-6:-4] for index, contrast_id in enumerate(contrasts): print(' Contrast % i out of %i: %s' % (index + 1, len(contrasts), contrast_id)) # compute contrasts con_ = contrasts[contrast_id] contrast_ = compute_contrast(labels, res, con_) stats = [ contrast_.z_score(), contrast_.stat_, contrast_.effect, contrast_.variance ] for map_type, out_map in zip(['z', 't', 'effects', 'variance'], stats): map_dir = os.path.join(subject_session_output_dir, '%s_surf' % map_type) if not os.path.exists(map_dir): os.makedirs(map_dir) map_path = os.path.join(map_dir, '%s_%s.gii' % (contrast_id, side)) print("\t\tWriting %s ..." % map_path) tex = GiftiImage(darrays=[ GiftiDataArray().from_array(out_map, intent='t test') ]) write(tex, map_path)
def test_metadata(): nvpair = GiftiNVPairs('key', 'value') da = GiftiMetaData(nvpair=nvpair) assert_equal(da.data[0].name, 'key') assert_equal(da.data[0].value, 'value') # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) assert_equal(len(GiftiDataArray().get_metadata()), 0) assert_equal(len(w), 1)
def test_metadata(): # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) assert_equal(len(GiftiDataArray().get_metadata()), 0) # Test deprecation with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) assert_equal(len(GiftiMetaData().get_metadata()), 0)
def test_gifti_image(): # Check that we're not modifying the default empty list in the default # arguments. gi = GiftiImage() assert_equal(gi.darrays, []) assert_equal(gi.meta.metadata, {}) assert_equal(gi.labeltable.labels, []) arr = np.zeros((2, 3)) gi.darrays.append(arr) # Now check we didn't overwrite the default arg gi = GiftiImage() assert_equal(gi.darrays, []) # Test darrays / numDA gi = GiftiImage() assert_equal(gi.numDA, 0) # Test from numpy numeric array data = np.random.random((5, )) da = GiftiDataArray(data) gi.add_gifti_data_array(da) assert_equal(gi.numDA, 1) assert_array_equal(gi.darrays[0].data, data) # Test removing gi.remove_gifti_data_array(0) assert_equal(gi.numDA, 0) # Remove from empty gi = GiftiImage() gi.remove_gifti_data_array_by_intent(0) assert_equal(gi.numDA, 0) # Remove one gi = GiftiImage() da = GiftiDataArray(np.zeros((5, )), intent=0) gi.add_gifti_data_array(da) gi.remove_gifti_data_array_by_intent(3) assert_equal(gi.numDA, 1, "data array should exist on 'missed' remove") gi.remove_gifti_data_array_by_intent(da.intent) assert_equal(gi.numDA, 0)
def extract_sub_mesh_with_files(input_mesh, center_node, radius, output_mesh=None): from nibabel import gifti from nibabel.gifti import GiftiImage, GiftiDataArray from pyhrf.tools._io import read_mesh cor, tri, coord_sys = read_mesh(input_mesh) sub_cor, sub_tri = extract_sub_mesh(cor, tri, center_node, radius) #nimg = GiftiImage_fromTriangles(sub_cor, sub_tri) nimg = GiftiImage() intent = 'NIFTI_INTENT_POINTSET' nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_cor,intent)) intent = 'NIFTI_INTENT_TRIANGLE' nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_tri,intent)) if output_mesh is None: output_mesh = non_existent_file(add_suffix(input_mesh, '_sub')) pyhrf.verbose(1, 'Saving extracted mesh to %s' %output_mesh) gifti.write(nimg, output_mesh) return sub_cor, sub_tri, coord_sys
def test_dataarray(): for dt_code in data_type_codes.value_set(): data_type = data_type_codes.type[dt_code] if data_type is np.void: # not supported continue arr = np.zeros((10, 3), dtype=data_type) da = GiftiDataArray.from_array(arr, 'triangle') assert_equal(da.datatype, data_type_codes[arr.dtype]) bs_arr = arr.byteswap().newbyteorder() da = GiftiDataArray.from_array(bs_arr, 'triangle') assert_equal(da.datatype, data_type_codes[arr.dtype]) # Smoke test on deprecated functions da = GiftiDataArray.from_array(np.ones((1,)), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) assert_true(isinstance(da.to_xml_open(), string_types)) assert_equal(len(w), 1) with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) assert_true(isinstance(da.to_xml_close(), string_types)) assert_equal(len(w), 1)
def test_gifti_image(): # Check that we're not modifying the default empty list in the default # arguments. gi = GiftiImage() assert_equal(gi.darrays, []) arr = np.zeros((2, 3)) gi.darrays.append(arr) # Now check we didn't overwrite the default arg gi = GiftiImage() assert_equal(gi.darrays, []) # Test darrays / numDA gi = GiftiImage() assert_equal(gi.numDA, 0) da = GiftiDataArray(data='data') gi.add_gifti_data_array(da) assert_equal(gi.numDA, 1) assert_equal(gi.darrays[0].data, 'data') gi.remove_gifti_data_array(0) assert_equal(gi.numDA, 0) # Remove from empty gi = GiftiImage() gi.remove_gifti_data_array_by_intent(0) assert_equal(gi.numDA, 0) # Remove one gi = GiftiImage() da = GiftiDataArray(data='data') gi.add_gifti_data_array(da) gi.remove_gifti_data_array_by_intent(0) assert_equal(gi.numDA, 1) gi.darrays[0].intent = 0 gi.remove_gifti_data_array_by_intent(0) assert_equal(gi.numDA, 0)
def test_dataarray(): for dt_code in data_type_codes.value_set(): data_type = data_type_codes.type[dt_code] if data_type is np.void: # not supported continue arr = np.zeros((10, 3), dtype=data_type) da = GiftiDataArray.from_array(arr, 'triangle') assert_equal(da.datatype, data_type_codes[arr.dtype]) bs_arr = arr.byteswap().newbyteorder() da = GiftiDataArray.from_array(bs_arr, 'triangle') assert_equal(da.datatype, data_type_codes[arr.dtype]) # Smoke test on deprecated functions da = GiftiDataArray.from_array(np.ones((1, )), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) assert_true(isinstance(da.to_xml_open(), string_types)) assert_equal(len(w), 1) with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) assert_true(isinstance(da.to_xml_close(), string_types)) assert_equal(len(w), 1)
def extract_sub_mesh_with_files(input_mesh, center_node, radius, output_mesh=None): from nibabel import gifti from nibabel.gifti import GiftiImage, GiftiDataArray from pyhrf.tools._io import read_mesh cor, tri, coord_sys = read_mesh(input_mesh) sub_cor, sub_tri = extract_sub_mesh(cor, tri, center_node, radius) #nimg = GiftiImage_fromTriangles(sub_cor, sub_tri) nimg = GiftiImage() intent = 'NIFTI_INTENT_POINTSET' nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_cor, intent)) intent = 'NIFTI_INTENT_TRIANGLE' nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_tri, intent)) if output_mesh is None: output_mesh = non_existent_file(add_suffix(input_mesh, '_sub')) logger.info('Saving extracted mesh to %s', output_mesh) gifti.write(nimg, output_mesh) return sub_cor, sub_tri, coord_sys
def test_darray_dtype_coercion_failures(): dtypes = (np.uint8, np.int32, np.int64, np.float32, np.float64) encodings = ('ASCII', 'B64BIN', 'B64GZ') for data_dtype, darray_dtype, encoding in itertools.product( dtypes, dtypes, encodings): da = GiftiDataArray(np.arange(10).astype(data_dtype), encoding=encoding, intent='NIFTI_INTENT_NODE_INDEX', datatype=darray_dtype) gii = GiftiImage(darrays=[da]) gii_copy = GiftiImage.from_bytes(gii.to_bytes()) da_copy = gii_copy.darrays[0] assert_equal(np.dtype(da_copy.data.dtype), np.dtype(darray_dtype)) assert_array_equal(da_copy.data, da.data)
def test_dataarray_empty(): # Test default initialization of DataArray null_da = GiftiDataArray() assert_equal(null_da.data, None) assert_equal(null_da.intent, 0) assert_equal(null_da.datatype, 0) assert_equal(null_da.encoding, 3) assert_equal(null_da.endian, 2 if sys.byteorder == 'little' else 1) assert_equal(null_da.coordsys.dataspace, 0) assert_equal(null_da.coordsys.xformspace, 0) assert_array_equal(null_da.coordsys.xform, np.eye(4)) assert_equal(null_da.ind_ord, 1) assert_equal(null_da.meta.metadata, {}) assert_equal(null_da.ext_fname, '') assert_equal(null_da.ext_offset, 0)
def fixed_effects_surf(con_imgs, var_imgs): """Idem fixed_effects_img but for surfaces""" from nibabel import load from nibabel.gifti import GiftiDataArray, GiftiImage con, var = [], [] for (con_img, var_img) in zip(con_imgs, var_imgs): con.append(np.ravel([darrays.data for darrays in load(con_img).darrays])) var.append(np.ravel([darrays.data for darrays in load(var_img).darrays])) outputs = [] intents = ['NIFTI_INTENT_ESTIMATE', 'NIFTI_INTENT_ESTIMATE', 't test'] arrays = fixed_effects(con, var) for array, intent in zip(arrays, intents): gii = GiftiImage( darrays=[GiftiDataArray().from_array(array, intent)]) outputs.append(gii) return outputs
def test_data_array_round_trip(): # Test valid XML generated from new in-memory array # See: https://github.com/nipy/nibabel/issues/469 verts = np.zeros((4, 3), np.float32) verts[0, 0] = 10.5 verts[1, 1] = 20.5 verts[2, 2] = 30.5 vertices = GiftiDataArray(verts) img = GiftiImage() img.add_gifti_data_array(vertices) bio = BytesIO() fmap = dict(image=FileHolder(fileobj=bio)) bio.write(img.to_xml()) bio.seek(0) gio = GiftiImage.from_file_map(fmap) vertices = gio.darrays[0].data assert_array_equal(vertices, verts)
def write_gifti(self, surface, surface_path): gifti_image = GiftiImage() data_array = [0 for _ in xrange(2)] data_array[0] = surface.vertices data_array[1] = surface.triangles image_metadata = GiftiMetaData().from_dict(surface.image_metadata) vertices_metadata = GiftiMetaData().from_dict(surface.vertices_metadata) triangles_metadata = GiftiMetaData().from_dict(surface.triangles_metadata) # TODO We currently write metadata of the old surface gifti_image.set_metadata(image_metadata) data = GiftiDataArray(data_array[0], datatype='NIFTI_TYPE_FLOAT32', intent='NIFTI_INTENT_POINTSET') data.meta = vertices_metadata data.coordsys = surface.vertices_coord_system gifti_image.add_gifti_data_array(data) data = GiftiDataArray(data_array[1], datatype='NIFTI_TYPE_INT32', intent='NIFTI_INTENT_TRIANGLE') data.meta = triangles_metadata data.coordsys = None gifti_image.add_gifti_data_array(data) nibabel.save(gifti_image, surface_path)
def save_texture(path, data, intent='none', verbose=False): """ volume saving utility for textures Parameters ---------- path, string, output image path data, array of shape (nnode) data to be put in the volume intent: string, optional intent Fixme ----- Missing checks Handle the case where data is multi-dimensional ? """ from nibabel.gifti import write, GiftiDataArray, GiftiImage if verbose: print 'Warning: assuming a float32 gifti file' darray = GiftiDataArray().from_array(data.astype(np.float32), intent) img = GiftiImage(darrays=[darray]) write(img, path)
def write(self, surface_obj, file_path): image_metadata = GiftiMetaData().from_dict(surface_obj.generic_metadata) vertices_metadata = GiftiMetaData().from_dict(surface_obj.vertices_metadata) triangles_metadata = GiftiMetaData().from_dict(surface_obj.triangles_metadata) gifti_image = GiftiImage() gifti_image.set_metadata(image_metadata) data = GiftiDataArray( surface_obj.vertices, datatype='NIFTI_TYPE_FLOAT32', intent='NIFTI_INTENT_POINTSET') data.meta = vertices_metadata data.coordsys = surface_obj.vertices_coord_system gifti_image.add_gifti_data_array(data) data = GiftiDataArray( surface_obj.triangles, datatype='NIFTI_TYPE_INT32', intent='NIFTI_INTENT_TRIANGLE') data.meta = triangles_metadata data.coordsys = None gifti_image.add_gifti_data_array(data) nibabel.save(gifti_image, file_path)
# quick and dirty approach: sum z maps if do_surface: for hemi in ['lh', 'rh']: z_maps = [ pjoin(work_dir, acq, 'z_surf', 'effects_interest_%s.gii' % hemi) for acq in acqs ] mean_z = np.mean([ np.ravel([darrays.data for darrays in load(z_map).darrays]) for z_map in z_maps ], 0) n_maps = len(z_maps) fixed_effects = mean_z * np.sqrt(n_maps) gii = GiftiImage( darrays=[GiftiDataArray().from_array(fixed_effects, 't test')]) gii.to_filename(pjoin(write_dir, 'retinotopicity_%s.gii' % hemi)) fixed_effects[np.isnan(fixed_effects)] = 0 bh = fdr_threshold(fixed_effects, alpha) print(bh) mask = fixed_effects > bh # todo: plot on a surface """ output_file = pjoin(write_dir, 'retinotopicity_%s.png' % hemi) if hemi == 'lh': plot_surf_stat_map( lh_inflated, fixed_effects, bg_map=sulc_left, output_file=output_file, hemi='left', view='medial', bg_on_data=True, darkness=1, alpha=1, threshold=THRESHOLD) else:
def smooth_texture(mesh, input_texture, output_texture=None, sigma=1, lsigma=1., mask=None): """ Smooth a texture along some mesh parameters ---------- mesh: string, path to gii mesh input_texture: string, texture path ouput_texture: string, smooth texture path sigma: float, desired amount of smoothing lsigma: float, approximate smoothing in one iteration mask: string, path of a mask texture """ import nipy.algorithms.graph.field as ff G = mesh_to_graph(mesh) if mask is not None: mask = read(mask).darrays[0].data > 0 G = G.subgraph(mask) add_edges = np.vstack((np.arange(G.V), np.arange(G.V))).T edges = np.vstack((G.edges, add_edges)) weights = np.concatenate((G.weights, np.zeros(G.V))) weights = np.maximum(np.exp(-weights**2 / (2 * lsigma**2)), 1.e-15) f = ff.Field(G.V, edges, weights) # need to re-order the edges order = np.argsort(f.edges.T[0] * f.V + f.edges.T[1]) f.edges, f.weights = f.edges[order], f.weights[order] f.normalize(0) niter = (sigma * 1. / lsigma)**2 if input_texture[-4:] == '.tex': import tio as tio data = tio.Texture("").read(input_texture).data else: data = read(input_texture).darrays[0].data if mask is not None: data = data[mask] dtype = data.dtype data[np.isnan(data)] = 0 f.set_field(data.T) f.diffusion(niter) data = f.get_field().astype(dtype) if output_texture is not None: if output_texture[-4:] == '.tex': import tio as tio tio.Texture("", data=data.T).write(output_texture) print 'tex' else: intent = 0 wdata = data if mask is not None: wdata = mask.astype(np.float) wdata[mask > 0] = data darray = GiftiDataArray().from_array(wdata.astype(np.float32), intent) img = GiftiImage(darrays=[darray]) write(img, output_texture) return data