#NEWLINE# def save_xfm( self , subject , name , xfm , xfmtype = 'magnet' , reference = None ) : #NEWLINE# #INDENT# "\n        Load a transform into the surface database. If the transform exists already, update it\n        If it does not exist, copy the reference epi into the filestore and insert.\n\n        Parameters\n        ----------\n        subject : str\n            Name of the subject\n        name : str\n            Name to identify the transform\n        xfm : (4,4) array\n            The affine transformation matrix\n        xfmtype : str, optional\n            Type of the provided transform, either magnet space or coord space.\n            Defaults to 'magnet'.\n        reference : str, optional\n            The nibabel-compatible reference image associated with this transform.\n            Required if name not in database\n        " #NEWLINE# if ( xfmtype not in [ 'magnet' , 'coord' ] ) : #NEWLINE# #INDENT# raise TypeError ( 'Unknown transform type' ) #NEWLINE# #UNINDENT# import nibabel #NEWLINE# path = os . path . join ( self . filestore , subject , 'transforms' , name ) #NEWLINE# fname = os . path . join ( path , 'matrices.xfm' ) #NEWLINE# if os . path . exists ( fname ) : #NEWLINE# #INDENT# jsdict = json . load ( open ( fname ) ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# os . mkdir ( path ) #NEWLINE# if ( reference is None ) : #NEWLINE# #INDENT# raise ValueError ( 'Please specify a reference' ) #NEWLINE# #UNINDENT# fpath = os . path . join ( path , 'reference.nii.gz' ) #NEWLINE# nib = nibabel . load ( reference ) #NEWLINE# data = nib . get_data ( ) #NEWLINE# if ( len ( jsdict . shape ) > 3 ) : #NEWLINE# #INDENT# import warnings #NEWLINE# warnings . warn ( 'You are importing a 4D dataset, automatically selecting the first volume as reference' ) #NEWLINE# data = data [ ( ... , 0 ) ] #NEWLINE# #UNINDENT# out = nibabel . Nifti1Image ( data , nib . get_affine ( ) , header = nib . get_header ( ) ) #NEWLINE# nibabel . save ( out , fpath ) #NEWLINE# jsdict = dict ( ) #NEWLINE# #UNINDENT# nib = nibabel . load ( os . path . join ( path , 'reference.nii.gz' ) ) #NEWLINE# if ( xfmtype == 'magnet' ) : #NEWLINE# #INDENT# jsdict [ 'magnet' ] = xfm . tolist ( ) #NEWLINE# jsdict [ 'coord' ] = np . dot ( np . linalg . inv ( nib . get_affine ( ) ) , xfm ) . tolist ( ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( xfmtype == 'coord' ) : #NEWLINE# #INDENT# jsdict [ 'coord' ] = xfm . tolist ( ) #NEWLINE# jsdict [ 'magnet' ] = np . dot ( nib . get_affine ( ) , xfm ) . tolist ( ) #NEWLINE# #UNINDENT# #UNINDENT# files = self . get_paths ( subject ) #NEWLINE# if ( len ( glob . glob ( files [ 'masks' ] . format ( xfmname = name , type = '*' ) ) ) > 0 ) : #NEWLINE# #INDENT# raise ValueError ( 'Refusing to change a transform with masks' ) #NEWLINE# #UNINDENT# json . dump ( jsdict , open ( fname , 'w' ) , sort_keys = True , indent = 4 )