Example #1
0
def get_vox_dims(volume):
    if isinstance(volume, list):
        volume = volume[0]
    nii = ni.load(volume)
    hdr = nii.get_header()
    voxdims = hdr.get_zooms()
    return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])]
Example #2
0
 def _generate_clustered_design(self,infolist):
     """Generates condition information for sparse-clustered
     designs.
     
     """
     infoout = deepcopy(infolist)
     for i,info in enumerate(infolist):
         infoout[i].conditions = None
         infoout[i].onsets = None
         infoout[i].durations = None
         if info.conditions:
             img = load(self.inputs.functional_runs[i])
             nscans = img.get_shape()[3]
             reg,regnames = self._cond_to_regress(info,nscans)
             if not infoout[i].regressors:
                 infoout[i].regressors = []
                 infoout[i].regressor_names = []
             else:
                 if not infoout[i].regressor_names:
                     infoout[i].regressor_names = ['R%d'%j for j in range(len(infoout[i].regressors))] 
             for j,r in enumerate(reg):
                 regidx = len(infoout[i].regressors)
                 infoout[i].regressor_names.insert(regidx,regnames[j])
                 infoout[i].regressors.insert(regidx,r)
     return infoout
Example #3
0
def func_is_3d(in_file):
    """Checks if input functional files are 3d."""
    
    if isinstance(in_file, list):
        return func_is_3d(in_file[0])
    else:
        img = load(in_file)
        shape = img.get_shape() 
        if len(shape) == 3 or (len(shape)==4 and shape[3]==1):
            return True
        else:
            return False
Example #4
0
    def _run_interface(self, runtime):
        cwd = os.getcwd()
        fsf_header = load_template("feat_header_l1.tcl")
        fsf_postscript = load_template("feat_nongui.tcl")

        prewhiten = 0
        if isdefined(self.inputs.model_serial_correlations):
            prewhiten = int(self.inputs.model_serial_correlations == "AR(1)")
        usetd = 0
        basis_key = self.inputs.bases.keys()[0]
        if basis_key in ["dgamma", "gamma"]:
            usetd = int(self.inputs.bases[basis_key]["derivs"])
        session_info = self._get_session_info(self.inputs.session_info)
        func_files = self._get_func_files(session_info)

        n_tcon = 0
        n_fcon = 0
        for i, c in enumerate(self.inputs.contrasts):
            if c[1] == "T":
                n_tcon += 1
            elif c[1] == "F":
                n_fcon += 1
            else:
                print "unknown contrast type: %s" % str(c)

        for i, info in enumerate(session_info):
            num_evs, cond_txt = self._create_ev_files(cwd, info, i, usetd, self.inputs.contrasts)
            nim = load(func_files[i])
            (_, _, _, timepoints) = nim.get_shape()
            fsf_txt = fsf_header.substitute(
                run_num=i,
                interscan_interval=self.inputs.interscan_interval,
                num_vols=timepoints,
                prewhiten=prewhiten,
                num_evs=num_evs[0],
                num_evs_real=num_evs[1],
                num_tcon=n_tcon,
                num_fcon=n_fcon,
                high_pass_filter_cutoff=info["hpf"],
                func_file=func_files[i],
            )
            fsf_txt += cond_txt
            fsf_txt += fsf_postscript.substitute(overwrite=1)

            f = open(os.path.join(cwd, "run%d.fsf" % i), "w")
            f.write(fsf_txt)
            f.close()

        runtime.returncode = 0
        return runtime
Example #5
0
 def _concatenate_info(self,infolist):
     nscans = []
     for i,f in enumerate(filename_to_list(self.inputs.functional_runs)):
         if isinstance(f,list):
             numscans = len(f)
         elif isinstance(f,str):
             img = load(f)
             numscans = img.get_shape()[3]
         else:
             raise Exception('Functional input not specified correctly')
         nscans.insert(i, numscans)
     # now combine all fields into 1
     # names,onsets,durations,amplitudes,pmod,tmod,regressor_names,regressors
     infoout = infolist[0]
     for i,info in enumerate(infolist[1:]):
             #info.[conditions,tmod] remain the same
         if info.onsets:
             for j,val in enumerate(info.onsets):
                 if self.inputs.input_units == 'secs':
                     infoout.onsets[j].extend((np.array(info.onsets[j])+
                                               self.inputs.time_repetition*sum(nscans[0:(i+1)])).tolist())
                 else:
                     infoout.onsets[j].extend((np.array(info.onsets[j])+sum(nscans[0:(i+1)])).tolist())
             for j,val in enumerate(info.durations):
                 if len(val) > 1:
                     infoout.durations[j].extend(info.durations[j])
             if info.pmod:
                 for j,val in enumerate(info.pmod):
                     if val:
                         for key,data in enumerate(val.param):
                             infoout.pmod[j].param[key].extend(data)
         if info.regressors:
             #assumes same ordering of regressors across different
             #runs and the same names for the regressors
             for j,v in enumerate(info.regressors):
                 infoout.regressors[j].extend(info.regressors[j])
         #insert session regressors
         if not infoout.regressors:
             infoout.regressors = []
         onelist = np.zeros((1,sum(nscans)))
         onelist[0,sum(nscans[0:(i)]):sum(nscans[0:(i+1)])] = 1
         infoout.regressors.insert(len(infoout.regressors),onelist.tolist()[0])
     return [infoout],nscans
Example #6
0
 def _list_outputs(self):
     outputs = self.output_spec().get()
     outfile = self._get_outfilename()
     if isdefined(self.inputs.out_type):
         if self.inputs.out_type in ['spm', 'analyze']:
             # generate all outputs
             size = load(self.inputs.in_file).get_shape()
             if len(size)==3:
                 tp = 1
             else:
                 tp = size[-1]
                 # have to take care of all the frame manipulations
                 raise Exception('Not taking frame manipulations into account- please warn the developers')
             outfiles = []
             for i in range(tp):
                 outfiles.append(fname_presuffix(outfile,
                                                 suffix='%03d'%(i+1)))
             outfile = outfiles
     outputs['out_file'] = outfile
     return outputs
Example #7
0
def scans_for_fname(fname):
    """Reads a nifti file and converts it to a numpy array storing
    individual nifti volumes.
    
    Opens images so will fail if they are not found.
    
    """
    if isinstance(fname,list):
        scans = np.zeros((len(fname),),dtype=object)
        for sno,f in enumerate(fname):
            scans[sno] = '%s,1'%f
        return scans
    img = load(fname)
    if len(img.get_shape()) == 3:
        return np.array(('%s,1'%fname,),dtype=object)
    else:
        n_scans = img.get_shape()[3]
        scans = np.zeros((n_scans,),dtype=object)
        for sno in range(n_scans):
            scans[sno] = '%s,%d'% (fname, sno+1)
        return scans
Example #8
0
 def load_image(self, filename):
     img = pynifti.load(filename)
     self.img = img
     self.filename = filename
     self.data = self.img.get_data()
Example #9
0
def getmiddlevolume(func):
    funcfile = func
    if isinstance(func, list):
        funcfile = func[0]
    _,_,_,timepoints = load(funcfile).get_shape()
    return (timepoints/2)-1
import nipype.externals.pynifti as nb
import numpy as np

image_filename2 = "/media/sdb2/laura_study/DATA_4_chis/SPGRs/AG_1247/T2.hdr"

nii2 = nb.load(image_filename2)

affine = nii2.get_affine()
flip_matrix = np.eye(4)
#flip_matrix[0,0] = -1
affine = np.dot(flip_matrix,affine)

data = nii2.get_data()

nb.save(nb.Nifti1Image(data, affine, nii2.get_header()), "new_T2.nii")
Example #11
0
image_filename2 = "/media/sdb2/laura_study/workdir/compare_pipeline/_subject_id_AG_1247/expert_fix_affine/fAG_1247_LHclench_t10_transformed.nii"

def findBorder(data):
    eroded = binary_erosion(data)
    border = np.logical_and(data, np.logical_not(eroded))
    return border

def getCoordinates(data, affine):
    if len(data.shape) == 4:
        data = data[:,:,:,0]
    indices = np.vstack(np.nonzero(data))
    indices = np.vstack((indices, np.ones(indices.shape[1])))
    coordinates = np.dot(affine,indices)
    return coordinates[:3,:]

nii1 = nb.load(image_filename1)
origdata1 = nii1.get_data().astype(np.bool)

#cog_t = np.array(center_of_mass(origdata1)).reshape(-1,1)
#cog_t = np.vstack((cog_t, np.array([1])))
#
#print cog_t.shape
#
#cog_t_coor = np.dot(nii1.get_affine(),cog_t)[:3,:]
#
#nii2 = nb.load(image_filename2)
#origdata2 = nii2.get_data().astype(np.bool)
#(labeled_data, n_labels) = label(origdata2)
#
#cogs = np.ones((4,n_labels))
#
Example #12
0
    def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None):
        """
        Core routine for detecting outliers
        """
        if not cwd:
            cwd = os.getcwd()
        # read in motion parameters
        mc_in = np.loadtxt(motionfile)
        mc = deepcopy(mc_in)
        if self.inputs.parameter_source == 'SPM':
            pass
        elif self.inputs.parameter_source == 'FSL':
            mc = mc[:,[3,4,5,0,1,2]]
        elif self.inputs.parameter_source == 'Siemens':
            Exception("Siemens PACE format not implemented yet")
        else:
            Exception("Unknown source for movement parameters")
            
        if self.inputs.use_norm:
            # calculate the norm of the motion parameters
            normval = self._calc_norm(mc,self.inputs.use_differences[0])
            tidx = find_indices(normval>self.inputs.norm_threshold)
            ridx = find_indices(normval<0)
        else:
            if self.inputs.use_differences[0]:
                mc = np.concatenate( (np.zeros((1,6)),np.diff(mc_in,n=1,axis=0)) , axis=0)
            traval = mc[:,0:3]  # translation parameters (mm)
            rotval = mc[:,3:6]  # rotation parameters (rad)
            tidx = find_indices(np.sum(abs(traval)>self.inputs.translation_threshold,1)>0)
            ridx = find_indices(np.sum(abs(rotval)>self.inputs.rotation_threshold,1)>0)

        # read in functional image
        if isinstance(imgfile,str):
            nim = load(imgfile)
        elif isinstance(imgfile,list):
            if len(imgfile) == 1:
                nim = load(imgfile[0])
            else:
                images = [load(f) for f in imgfile]
                nim = funcs.concat_images(images)

        # compute global intensity signal
        (x,y,z,timepoints) = nim.get_shape()

        data = nim.get_data()
        g = np.zeros((timepoints,1))
        masktype = self.inputs.mask_type
        if  masktype == 'spm_global':  # spm_global like calculation
            intersect_mask = self.inputs.intersect_mask
            if intersect_mask:
                mask = np.ones((x,y,z),dtype=bool)
                for t0 in range(timepoints):
                    vol   = data[:,:,:,t0]
                    mask  = mask*(vol>(self._nanmean(vol)/8))
                for t0 in range(timepoints):
                    vol   = data[:,:,:,t0]                    
                    g[t0] = self._nanmean(vol[mask])
                if len(find_indices(mask))<(np.prod((x,y,z))/10):
                    intersect_mask = False
                    g = np.zeros((timepoints,1))
            if not intersect_mask:
                for t0 in range(timepoints):
                    vol   = data[:,:,:,t0]
                    mask  = vol>(self._nanmean(vol)/8)
                    g[t0] = self._nanmean(vol[mask])
        elif masktype == 'file': # uses a mask image to determine intensity
            mask = load(self.inputs.mask_file).get_data()
            mask = mask>0.5
            for t0 in range(timepoints):
                vol = data[:,:,:,t0]
                g[t0] = self._nanmean(vol[mask])
        elif masktype == 'thresh': # uses a fixed signal threshold
            for t0 in range(timepoints):
                vol   = data[:,:,:,t0]
                mask  = vol>self.inputs.mask_threshold
                g[t0] = self._nanmean(vol[mask])
        else:
            mask = np.ones((x,y,z))
            g = self._nanmean(data[mask>0,:],1)

        # compute normalized intensity values
        gz = signal.detrend(g,axis=0)       # detrend the signal
        if self.inputs.use_differences[1]:
            gz = np.concatenate( (np.zeros((1,1)),np.diff(gz,n=1,axis=0)) , axis=0)
        gz = (gz-np.mean(gz))/np.std(gz)    # normalize the detrended signal
        iidx = find_indices(abs(gz)>self.inputs.zintensity_threshold)

        outliers = np.unique(np.union1d(iidx,np.union1d(tidx,ridx)))
        artifactfile,intensityfile,statsfile,normfile = self._get_output_filenames(imgfile,cwd)
        
        # write output to outputfile
        np.savetxt(artifactfile, outliers, fmt='%d', delimiter=' ')
        np.savetxt(intensityfile, g, fmt='%.2f', delimiter=' ')
        if self.inputs.use_norm:
            np.savetxt(normfile, normval, fmt='%.4f', delimiter=' ')

        file = open(statsfile,'w')
        file.write("Stats for:\n")
        file.write("Motion file: %s\n" % motionfile)
        file.write("Functional file: %s\n" % imgfile)
        file.write("Motion:\n")
        file.write("Number of Motion Outliers: %d\n"%len(np.union1d(tidx,ridx)))
        file.write("Motion (original):\n")
        file.write( ''.join(('mean: ',str(np.mean(mc_in,axis=0)),'\n')))
        file.write( ''.join(('min: ',str(np.min(mc_in,axis=0)),'\n')))
        file.write( ''.join(('max: ',str(np.max(mc_in,axis=0)),'\n')))
        file.write( ''.join(('std: ',str(np.std(mc_in,axis=0)),'\n')))
        if self.inputs.use_norm:
            if self.inputs.use_differences[0]:
                file.write("Motion (norm-differences):\n")
            else:
                file.write("Motion (norm):\n")
            file.write( ''.join(('mean: ',str(np.mean(normval,axis=0)),'\n')))
            file.write( ''.join(('min: ',str(np.min(normval,axis=0)),'\n')))
            file.write( ''.join(('max: ',str(np.max(normval,axis=0)),'\n')))
            file.write( ''.join(('std: ',str(np.std(normval,axis=0)),'\n')))
        elif self.inputs.use_differences[0]:
            file.write("Motion (differences):\n")
            file.write( ''.join(('mean: ',str(np.mean(mc,axis=0)),'\n')))
            file.write( ''.join(('min: ',str(np.min(mc,axis=0)),'\n')))
            file.write( ''.join(('max: ',str(np.max(mc,axis=0)),'\n')))
            file.write( ''.join(('std: ',str(np.std(mc,axis=0)),'\n')))
        if self.inputs.use_differences[1]:
            file.write("Normalized intensity:\n")
        else:
            file.write("Intensity:\n")
        file.write("Number of Intensity Outliers: %d\n"%len(iidx))
        file.write( ''.join(('min: ',str(np.min(gz,axis=0)),'\n')))
        file.write( ''.join(('max: ',str(np.max(gz,axis=0)),'\n')))
        file.write( ''.join(('mean: ',str(np.mean(gz,axis=0)),'\n')))
        file.write( ''.join(('std: ',str(np.std(gz,axis=0)),'\n')))
        file.close()