utils.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """
  2. Utility function: loading data from hdf5 files and loading mapper files to display data on the
  3. cortical surface.
  4. """
  5. import numpy as np
  6. import itertools as itools
  7. import scipy.sparse
  8. import h5py
  9. def load_data(fname, key=None):
  10. """Function to load data from an hdf file.
  11. Parameters
  12. ----------
  13. fname: string
  14. hdf5 file name
  15. key: string
  16. key name to load. If not provided, all keys will be loaded.
  17. Returns
  18. -------
  19. data : dictionary
  20. dictionary of arrays
  21. """
  22. data = dict()
  23. with h5py.File(fname) as hf:
  24. if key is None:
  25. for k in hf.keys():
  26. print("{} will be loaded".format(k))
  27. data[k] = hf[k][()]
  28. else:
  29. data[key] = hf[key][()]
  30. return data
  31. def load_sparse_array(fname, varname):
  32. """Load a numpy sparse array from an hdf file
  33. Parameters
  34. ----------
  35. fname: string
  36. file name containing array to be loaded
  37. varname: string
  38. name of variable to be loaded
  39. Notes
  40. -----
  41. This function relies on variables being stored with specific naming
  42. conventions, so cannot be used to load arbitrary sparse arrays.
  43. By Mark Lescroart
  44. """
  45. with h5py.File(fname) as hf:
  46. data = (hf['%s_data'%varname], hf['%s_indices'%varname], hf['%s_indptr'%varname])
  47. sparsemat = scipy.sparse.csr_matrix(data, shape=hf['%s_shape'%varname])
  48. return sparsemat
  49. def map_to_flat(voxels, mapper_file):
  50. """Generate flatmap image for an individual subject from voxel array
  51. This function maps a list of voxels into a flattened representation
  52. of an individual subject's brain.
  53. Parameters
  54. ----------
  55. voxels: array
  56. n x 1 array of voxel values to be mapped
  57. mapper_file: string
  58. file containing mapping arrays
  59. Returns
  60. -------
  61. image : array
  62. flatmap image, (n x 1024)
  63. By Mark Lescroart
  64. """
  65. pixmap = load_sparse_array(mapper_file, 'voxel_to_flatmap')
  66. with h5py.File(mapper_file, mode='r') as hf:
  67. pixmask = hf['flatmap_mask'][()]
  68. badmask = np.array(pixmap.sum(1) > 0).ravel()
  69. img = (np.nan * np.ones(pixmask.shape)).astype(voxels.dtype)
  70. mimg = (np.nan * np.ones(badmask.shape)).astype(voxels.dtype)
  71. mimg[badmask] = (pixmap * voxels.ravel())[badmask].astype(mimg.dtype)
  72. img[pixmask] = mimg
  73. return img.T[::-1]