def get_smoothed_fieldmap(fm, fmmag, epi_qform, epi_shape): import pytave # FIXME: how do I automatically get the correct directory here? pytave.addpath('/home/bobd/git/nims/nimsutil') xform = np.dot(np.linalg.inv(fm.get_qform()), epi_qform) fm_pixdim = np.array(fm.get_header().get_zooms()[0:3]) fm_mag_data = fm_mag.get_data().mean(3).squeeze() # clean up with a little median filter and some greyscale open/close. # We'll use a structure element that is about 5mm (rounded up to the nearest pixdim) filter_size = 5.0/fm_pixdim fm_mag_data = ndimage.median_filter(fm_mag_data, filter_size.round().astype(int)) fm_mag_data = ndimage.morphology.grey_opening(fm_mag_data, filter_size.round().astype(int)) fm_mag_data = ndimage.morphology.grey_closing(fm_mag_data, filter_size.round().astype(int)) # Total image volume, in cc: fm_volume = np.prod(fm_pixdim) * np.prod(fm.get_shape()) / 1000 # typical human cranial volume is up to 1800cc. There's also some scalp and maybe neck, # so we'll say 2500cc of expected tissue volume. mag_thresh = np.percentile(fm_mag_data, max(0.0,100.0*(1.0-2500.0/fm_volume))) mask = ndimage.binary_opening(fm_mag_data>mag_thresh, iterations=2) # Now delete all the small objects, just keeping the largest (which should be the brain!) label_im,num_objects = ndimage.measurements.label(mask) h,b = np.histogram(label_im,num_objects) mask = label_im==b[h==max(h[1:-1])] mask_volume = np.prod(fm_pixdim) * max(h[1:-1]) / 1000.0 mask_sm = ndimage.gaussian_filter(mask.astype(np.float), filter_size) fm_Hz = fm.get_data().astype(np.float).squeeze() fm_Hz_sm = ndimage.gaussian_filter(fm_Hz * mask_sm, filter_size/2) fm_final = np.empty(epi_shape[0:3]) ndimage.affine_transform(fm_Hz_sm, xform[0:3,0:3], offset=xform[0:3,3], output_shape=epi_shape[0:3], output=fm_final) [xxBc,yyBc,zzBc] = np.mgrid[0:epi_shape[0],0:epi_shape[1],0:epi_shape[2]] # grid the epi, get location of each sampled voxel # Now apply the transform. The following is equivalent to dot(xform,coords), where "coords" is the # list of all the (homogeneous) coords. Writing out the dot product like this is just faster and easier. xxB = xxBc*xform[0,0] + yyBc*xform[0,1] + zzBc*xform[0,2] + xform[0,3] yyB = xxBc*xform[1,0] + yyBc*xform[1,1] + zzBc*xform[1,2] + xform[1,3] zzB = xxBc*xform[2,0] + yyBc*xform[2,1] + zzBc*xform[2,2] + xform[2,3] # use local linear regression to smooth and interpolate the fieldmaps. fm_smooth_param = 7.5/np.array(fm.get_header().get_zooms()[0:3]) # Want 7.5mm in voxels, so =7.5/mm_per_vox fm_smooth = pytave.feval(1,'localregression3d',fm.get_data(),xxB+1,yyB+1,zzB+1,np.array([]),np.array([]),fm_smooth_param,fm_mag.get_data())[0] return fm_smooth
import sys import csv import numpy import numpy.linalg import pylab # my library import reg # because i need pytave sys.path.insert(0,"./lib/") import pytave # because i use regtools pytave.addpath('./lib/regu/') N = 200 rel_err = 1e-2 def example(name,N,rel_err,eta=1): # select the problem if name in [ 'phillips','shaw' ]: (A,b,x) = pytave.feval(3,name,N) elif name=='ilaplace': (A,b,x,tLAP) = pytave.feval(4,'i_laplace',N,1) else: raise Exception("I don't know problem "+name) # 1 dimension arrays are 2dim in octave. Let's flat them! b = b.flatten()
""" Problem Set 4 specific code""" import os from os import path import pytave import scipy as sp from scipy import io from scipy import linalg as la from rpy2 import robjects import rpy2.robjects.numpy2ri from rpy2.robjects.packages import importr _MFILES = path.abspath(path.join(path.dirname(__file__), "..", "octave")) pytave.addpath(_MFILES) def _pp(i, a): """Column in Pp for ai""" return (i * 2) + a def _logit(y, x, offset): """ Wrapper for logit used in FinalModel.argmax_theta """ ## Uses R for the glm function. stats = importr("stats") fmla = robjects.Formula('y ~ x - 1') env = fmla.environment env['y'] = robjects.IntVector(y) env['x'] = robjects.r.matrix(robjects.FloatVector(x.flatten('F')), ncol=x.shape[1]) results = stats.glm(fmla, family="binomial", offset=robjects.FloatVector(offset)) return sp.asarray(results.rx2('coefficients'))