1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- """
- Utility function: loading data from hdf5 files and loading mapper files to display data on the
- cortical surface.
- """
- import numpy as np
- import itertools as itools
- import scipy.sparse
- import h5py
- def load_data(fname, key=None):
- """Function to load data from an hdf file.
- Parameters
- ----------
- fname: string
- hdf5 file name
- key: string
- key name to load. If not provided, all keys will be loaded.
- Returns
- -------
- data : dictionary
- dictionary of arrays
- """
- data = dict()
- with h5py.File(fname) as hf:
- if key is None:
- for k in hf.keys():
- print("{} will be loaded".format(k))
- data[k] = hf[k][()]
- else:
- data[key] = hf[key][()]
- return data
- def load_sparse_array(fname, varname):
- """Load a numpy sparse array from an hdf file
- Parameters
- ----------
- fname: string
- file name containing array to be loaded
- varname: string
- name of variable to be loaded
- Notes
- -----
- This function relies on variables being stored with specific naming
- conventions, so cannot be used to load arbitrary sparse arrays.
- By Mark Lescroart
- """
- with h5py.File(fname) as hf:
- data = (hf['%s_data'%varname], hf['%s_indices'%varname], hf['%s_indptr'%varname])
- sparsemat = scipy.sparse.csr_matrix(data, shape=hf['%s_shape'%varname])
- return sparsemat
- def map_to_flat(voxels, mapper_file):
- """Generate flatmap image for an individual subject from voxel array
- This function maps a list of voxels into a flattened representation
- of an individual subject's brain.
- Parameters
- ----------
- voxels: array
- n x 1 array of voxel values to be mapped
- mapper_file: string
- file containing mapping arrays
- Returns
- -------
- image : array
- flatmap image, (n x 1024)
- By Mark Lescroart
- """
- pixmap = load_sparse_array(mapper_file, 'voxel_to_flatmap')
- with h5py.File(mapper_file, mode='r') as hf:
- pixmask = hf['flatmap_mask'][()]
- badmask = np.array(pixmap.sum(1) > 0).ravel()
- img = (np.nan * np.ones(pixmask.shape)).astype(voxels.dtype)
- mimg = (np.nan * np.ones(badmask.shape)).astype(voxels.dtype)
- mimg[badmask] = (pixmap * voxels.ravel())[badmask].astype(mimg.dtype)
- img[pixmask] = mimg
- return img.T[::-1]
|