for i in range(ndirs): im_dc[i, :, :] = tf.ifft2c(data_dc[i, :, :], ph_b1[i, :, :]) # A way to quickly plot the different direction cases if 0: for i in range(ndirs): ims = [ im_b0_avg, im_b1_full[i, :, :], im_b1_scan[i, :, :], im_dc[i, :, :] ] titles = [ 'b0 Average', 'im_full dir' + str(i), 'im_scan dir' + str(i), 'im_dc dir' + str(i) ] vis.figSubplots(ims, clim=(minval, maxval), titles=titles) saveFig.save( '/micehome/asalerno/Documents/pyDirectionCompSense/brainData/DTI/26apr16/33per/imdc/im_b1_comps_dir' + str(i)) im_sp = im_dc.copy().reshape(N) # Optimization algortihm -- this is where everything culminates together #M, dIM, Ause, inds = dirInfo for i in range(len(TV)): args = (N, TV[i], XFM[i], data_b1, k, strtag, ph_b1, dirWeight, dirs, dirInfo, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun,
def runCSAlgorithm(fromfid=False, filename='/home/asalerno/Documents/pyDirectionCompSense/brainData/P14/data/fullySampledBrain.npy', sliceChoice=150, strtag = ['','spatial', 'spatial'], xtol = [1e-2, 1e-3, 5e-4, 5e-4], TV = [0.01, 0.005, 0.002, 0.001], XFM = [0.01,.005, 0.002, 0.001], dirWeight=0, pctg=0.25, radius=0.2, P=2, pft=False, ext=0.5, wavelet='db4', mode='per', method='CG', ItnLim=30, lineSearchItnLim=30, alpha_0=0.6, c=0.6, a=10.0, kern = np.array([[[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]], [[ 0., 0., 0.], [ 0., -1., 0.], [ 0., 1., 0.]], [[ 0., 0., 0.], [ 0., -1., 1.], [ 0., 0., 0.]]]), dirFile = None, nmins = None, dirs = None, M = None, dirInfo = [None]*4, saveNpy=False, saveNpyFile=None, saveImsPng=False, saveImsPngFile=None, saveImDiffPng=False, saveImDiffPngFile=None, disp=False): ##import pdb; pdb.set_trace() if fromfid==True: inputdirectory=filename[0] petable=filename[1] fullImData = rff.getDataFromFID(petable,inputdirectory,2)[0,:,:,:] fullImData = fullImData/np.max(abs(fullImData)) im = fullImData[:,:,sliceChoice] else: im = np.load(filename)[sliceChoice,:,:] N = np.array(im.shape) # image Size pdf = samp.genPDF(N[-2:], P, pctg, radius=radius, cyl=np.hstack([1, N[-2:]]), style='mult', pft=pft, ext=ext) if pft: print('Partial Fourier sampling method used') k = samp.genSampling(pdf, 50, 2)[0].astype(int) if len(N) == 2: N = np.hstack([1, N]) k = k.reshape(N) im = im.reshape(N) elif (len(N) == 3) and ('dir' not in strtag): k = k.reshape(np.hstack([1,N[-2:]])).repeat(N[0],0) ph_ones = np.ones(N[-2:], complex) ph_scan = np.zeros(N, complex) data = np.zeros(N,complex) im_scan = np.zeros(N,complex) for i in range(N[0]): k[i,:,:] = np.fft.fftshift(k[i,:,:]) data[i,:,:] = k[i,:,:]*tf.fft2c(im[i,:,:], ph=ph_ones) # IMAGE from the "scanner data" im_scan_wph = tf.ifft2c(data[i,:,:], ph=ph_ones) ph_scan[i,:,:] = tf.matlab_style_gauss2D(im_scan_wph,shape=(5,5)) ph_scan[i,:,:] = np.exp(1j*ph_scan[i,:,:]) im_scan[i,:,:] = tf.ifft2c(data[i,:,:], ph=ph_scan[i,:,:]) #im_lr = samp.loRes(im,pctg) # ------------------------------------------------------------------ # # A quick way to look at the PSF of the sampling pattern that we use # delta = np.zeros(N[-2:]) delta[int(N[-2]/2),int(N[-1]/2)] = 1 psf = tf.ifft2c(tf.fft2c(delta,ph_ones)*k,ph_ones) # ------------------------------------------------------------------ # ## ------------------------------------------------------------------ # ## -- Currently broken - Need to figure out what's happening here. -- # ## ------------------------------------------------------------------ # #if pft: #for i in xrange(N[0]): #dataHold = np.fft.fftshift(data[i,:,:]) #kHold = np.fft.fftshift(k[i,:,:]) #loc = 98 #for ix in xrange(N[-2]): #for iy in xrange(loc,N[-1]): #dataHold[-ix,-iy] = dataHold[ix,iy].conj() #kHold[-ix,-iy] = kHold[ix,iy] ## ------------------------------------------------------------------ # pdfDiv = pdf.copy() pdfZeros = np.where(pdf==0) pdfDiv[pdfZeros] = 1 #im_scan_imag = im_scan.imag #im_scan = im_scan.real N_im = N.copy() hld, dims, dimOpt, dimLenOpt = tf.wt(im_scan[0].real,wavelet,mode) N = np.hstack([N_im[0], hld.shape]) w_scan = np.zeros(N) w_full = np.zeros(N) im_dc = np.zeros(N_im) w_dc = np.zeros(N) for i in xrange(N[0]): w_scan[i,:,:] = tf.wt(im_scan.real[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt)[0] w_full[i,:,:] = tf.wt(abs(im[i,:,:]),wavelet,mode,dims,dimOpt,dimLenOpt)[0] im_dc[i,:,:] = tf.ifft2c(data[i,:,:] / np.fft.ifftshift(pdfDiv), ph=ph_scan[i,:,:]).real.copy() w_dc[i,:,:] = tf.wt(im_dc,wavelet,mode,dims,dimOpt,dimLenOpt)[0] w_dc = w_dc.flatten() im_sp = im_dc.copy().reshape(N_im) minval = np.min(abs(im)) maxval = np.max(abs(im)) data = np.ascontiguousarray(data) imdcs = [im_dc,np.zeros(N_im),np.ones(N_im),np.random.randn(np.prod(N_im)).reshape(N_im)] imdcs[-1] = imdcs[-1] - np.min(imdcs[-1]) imdcs[-1] = imdcs[-1]/np.max(abs(imdcs[-1])) mets = ['Density Corrected','Zeros','1/2''s','Gaussian Random Shift (0,1)'] wdcs = [] for i in range(len(imdcs)): wdcs.append(tf.wt(imdcs[i][0],wavelet,mode,dims,dimOpt,dimLenOpt)[0].reshape(N)) ims = [] #print('Starting the CS Algorithm') for kk in range(len(wdcs)): w_dc = wdcs[kk] print(mets[kk]) for i in range(len(TV)): args = (N, N_im, dims, dimOpt, dimLenOpt, TV[i], XFM[i], data, k, strtag, ph_scan, kern, dirWeight, dirs, dirInfo, nmins, wavelet, mode, a) w_result = opt.minimize(f, w_dc, args=args, method=method, jac=df, options={'maxiter': ItnLim, 'lineSearchItnLim': lineSearchItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': alpha_0, 'c': c, 'xtol': xtol[i], 'TVWeight': TV[i], 'XFMWeight': XFM[i], 'N': N}) if np.any(np.isnan(w_result['x'])): print('Some nan''s found. Dropping TV and XFM values') elif w_result['status'] != 0: print('TV and XFM values too high -- no solution found. Dropping...') else: w_dc = w_result['x'] w_res = w_dc.reshape(N) im_res = np.zeros(N_im) for i in xrange(N[0]): im_res[i,:,:] = tf.iwt(w_res[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt) ims.append(im_res) if saveNpy: if saveNpyFile is None: np.save('./holdSave_im_res_' + str(int(pctg*100)) + 'p_all_SP',ims) else: np.save(saveNpyFile,ims) if saveImsPng: vis.figSubplots(ims,titles=mets,clims=(minval,maxval),colorbar=True) if not disp: if saveImsPngFile is None: saveFig.save('./holdSave_ims_' + str(int(pctg*100)) + 'p_all_SP') else: saveFig.save(saveImsPngFile) if saveImDiffPng: imdiffs, clims = vis.imDiff(ims) diffMets = ['DC-Zeros','DC-Ones','DC-Random','Zeros-Ones','Zeros-Random','Ones-Random'] vis.figSubplots(imdiffs,titles=diffMets,clims=clims,colorbar=True) if not disp: if saveImDiffPngFile is None: saveFig.save('./holdSave_im_diffs_' + str(int(pctg*100)) + 'p_all_SP') else: saveFig.save(saveImDiffPngFile) if disp: plt.show()
for i in range(4): clims.append([0, 1]) vis.figSubplots([ abs(im[0]), im_scan[0].real, im_scanComb[0].real, im_scanDir[0].real, im_scanDirComb[0].real, k[0], kDir[0], kComb[0], kDirComb[0] ], clims=clims, titles=[ 'Original', 'Var Dens', 'Var Dens Comb', 'Uni Samp', 'Uni Samp Comb', 'Var Dens k', 'Combo Dens k', 'Var Dens Shared k', 'Combo Dens Shared k' ], colorbar=False) #plt.show() saveFig.save('tests/directionTests/phantomSmoothed_teamWithVarDens') plt.figure(figsize=(24, 13.5)) plt.subplot(2, 2, 1) samp.radialHistogram(k[0], rmax=1) plt.title('Radial Histogram Var Dens') plt.subplot(2, 2, 2) samp.radialHistogram(kDir[0], rmax=1) plt.title('Radial Histogram Combo Dens') plt.subplot(2, 2, 3) samp.radialHistogram(kComb[0], rmax=1) plt.title('Radial Histogram Var Dens Shared') plt.subplot(2, 2, 4) samp.radialHistogram(kDirComb[0], rmax=1) plt.title('Radial Histogram Combo Dens Shared') saveFig.save('tests/directionTests/phantomSmoothed_radialHistograms')
# Now we add the k-space maps together in order to utilize the redundancies ot our advantage data_dc = np.fft.fftshift(d.dir_dataSharing(k, np.fft.fftshift(data_b1, axes=(-2,-1)), dirs=dirs, origDataSize=N[-2:]), axes=(-2,-1)) im_dc = np.zeros(data_dc.shape, dtype='complex') # And make the images for i in range(ndirs): im_dc[i,:,:] = tf.ifft2c(data_dc[i,:,:],ph_b1[i,:,:]) # A way to quickly plot the different direction cases if 0: for i in range(ndirs): ims = [im_b0_avg, im_b1_full[i,:,:], im_b1_scan[i,:,:], im_dc[i,:,:]] titles = ['b0 Average', 'im_full dir' + str(i), 'im_scan dir' + str(i), 'im_dc dir' + str(i)] vis.figSubplots(ims,clim=(minval,maxval),titles=titles) saveFig.save('/micehome/asalerno/Documents/pyDirectionCompSense/brainData/DTI/26apr16/33per/imdc/im_b1_comps_dir'+str(i)) im_sp = im_dc.copy().reshape(N) # Optimization algortihm -- this is where everything culminates together #M, dIM, Ause, inds = dirInfo for i in range(len(TV)): args = (N, TV[i], XFM[i], data_b1, k, strtag, ph_b1, dirWeight, dirs, dirInfo, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'lineSearchItnLim': lineSearchItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': alpha_0, 'c': c, 'xtol': xtol[i], 'TVWeight': TV[i], 'XFMWeight': XFM[i], 'N': N}) if np.any(np.isnan(im_result['x'])): print('Some nan''s found. Dropping TV and XFM values') else:
elif imdcs == 'densCorr_Completed': #im_dc = np.load('/home/asalerno/Documents/pyDirectionCompSense/brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/TV0.005_XFM0.005/0.25per_result_im_dc_densCorr.npy') im_dc = im_res TVWeight = 0.001 XFMWeight = 0.001 xtol = 1e-4 # Optimization algortihm -- this is where everything culminates together a = 10.0 args = (N, TVWeight, XFMWeight, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': alpha_0, 'c': 0.6, 'xtol': xtol, 'TVWeight': TVWeight, 'XFMWeight': XFMWeight, 'N': N}) im_res = im_result['x'].reshape(N) plt.imshow(im_res,clim=(minval,maxval),interpolation='bilinear') plt.title("Reconstructed Image with %d%% Sampling and im_dc==" % (pctg*100) + imdcs) plt.show() if imdcs == 'densCorr': saveFig.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_firstRun_im_dc_" % (pctg*100) + imdcs) np.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_firstRun_im_dc_" % (pctg*100) + imdcs,im_res) elif imdcs == 'densCorr_Completed': saveFig.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_secondRun_im_dc_TVXFM_0.001" % (pctg*100) + imdcs) np.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_secondRun_im_dc_TVXFM_0.001" % (pctg*100) + imdcs,im_res) #lrLoc = int(np.ceil((294-np.ceil(294/np.sqrt(1/pctg)))/2)) #im_lr = tf.fft2c(np.fft.fftshift(np.fft.fftshift(tf.ifft2c(im,np.ones(im.shape)))[lrLoc:-lrLoc,lrLoc:-lrLoc]),np.ones(im[lrLoc:-lrLoc,lrLoc:-lrLoc].shape)) #plt.imshow(abs(im_lr)) #plt.title('Low Resolution Equivalent with only %.2f%% of k-space Sampled' % pctg) #saveFig.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/TV%.2f_XFM%.2f/%.2fper_result_im_lr" % (TVWeight, XFMWeight, pctg))
minval = np.min(im) maxval = np.max(im) # Primary first guess. What we're using for now. Density corrected #im_dc = tf.ifft2c(data / np.fft.ifftshift(pdf), ph=ph).real.flatten().copy() for imdcs in ['zeros','ones','densCorr','imFull']: if imdcs == 'zeros': im_dc = np.zeros(data.shape) elif imdcs == 'ones': im_dc = np.ones(data.shape) elif imdcs == 'densCorr': im_dc = tf.ifft2c(data / np.fft.ifftshift(pdf), ph=ph).real.flatten().copy() elif imdcs == 'imFull': im_dc = im # Optimization algortihm -- this is where everything culminates together a = 10.0 args = (N, TVWeight, XFMWeight, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': 5e-3, 'TVWeight': TVWeight, 'XFMWeight': XFMWeight, 'N': N}) im_res = im_result['x'].reshape(N) plt.imshow(abs(im_res),clim=(minval,maxval)) plt.title("Reconstructed Image with %.2f%% Sampling and im_dc==" % pctg + imdcs) saveFig.save("sheppLoganData/TV%s_XFM%s/%.2fper_result_im_dc_" % (float('%.1g' % TVWeight), float('%.1g' % XFMWeight) , pctg) + imdcs) np.save("sheppLoganData/TV%s_XFM%s/%.2fper_result_im_dc_" % (float('%.1g' % TVWeight), float('%.1g' % XFMWeight) , pctg) + imdcs + ".npy" ,im_res) lrLoc = int(np.ceil((N[0]-np.ceil(N[0]/np.sqrt(1/pctg)))/2)) im_lr = tf.fft2c(np.fft.fftshift(np.fft.fftshift(tf.ifft2c(im,np.ones(im.shape)))[lrLoc:-lrLoc,lrLoc:-lrLoc]),np.ones(im[lrLoc:-lrLoc,lrLoc:-lrLoc].shape)) plt.imshow(abs(im_lr)) plt.title('Low Resolution Equivalent with only %.2f%% of k-space Sampled' % pctg) saveFig.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/TV%.2f_XFM%.2f/%.2fper_result_im_lr" % (TVWeight, XFMWeight, pctg)) np.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/TV%.2f_XFM%.2f/%.2fper_result_im_lr" % (TVWeight, XFMWeight, pctg) + ".npy", im_lr)
'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': 5e-3, 'TVWeight': TVWeight, 'XFMWeight': XFMWeight, 'N': N }) im_res = im_result['x'].reshape(N) plt.imshow(abs(im_res), clim=(minval, maxval)) plt.title( "Reconstructed Image with %.2f%% Sampling and im_dc==" % pctg + imdcs) saveFig.save( "sheppLoganData/TV%s_XFM%s/%.2fper_result_im_dc_" % (float('%.1g' % TVWeight), float('%.1g' % XFMWeight), pctg) + imdcs) np.save( "sheppLoganData/TV%s_XFM%s/%.2fper_result_im_dc_" % (float('%.1g' % TVWeight), float('%.1g' % XFMWeight), pctg) + imdcs + ".npy", im_res) lrLoc = int(np.ceil((N[0] - np.ceil(N[0] / np.sqrt(1 / pctg))) / 2)) im_lr = tf.fft2c( np.fft.fftshift( np.fft.fftshift(tf.ifft2c(im, np.ones(im.shape)))[lrLoc:-lrLoc, lrLoc:-lrLoc]), np.ones(im[lrLoc:-lrLoc, lrLoc:-lrLoc].shape)) plt.imshow(abs(im_lr)) plt.title('Low Resolution Equivalent with only %.2f%% of k-space Sampled' % pctg)
for i in range(4): clims.append([0,1]) vis.figSubplots([abs(im[0]), im_scan[0].real, im_scanComb[0].real, im_scanDir[0].real, im_scanDirComb[0].real, k[0], kDir[0], kComb[0], kDirComb[0]], clims=clims, titles=['Original','Var Dens','Var Dens Comb','Uni Samp','Uni Samp Comb','Var Dens k','Combo Dens k','Var Dens Shared k','Combo Dens Shared k'],colorbar=False) #plt.show() saveFig.save('tests/directionTests/phantomSmoothed_teamWithVarDens') plt.figure(figsize=(24,13.5)) plt.subplot(2,2,1) samp.radialHistogram(k[0],rmax=1) plt.title('Radial Histogram Var Dens') plt.subplot(2,2,2) samp.radialHistogram(kDir[0],rmax=1) plt.title('Radial Histogram Combo Dens') plt.subplot(2,2,3) samp.radialHistogram(kComb[0],rmax=1) plt.title('Radial Histogram Var Dens Shared') plt.subplot(2,2,4) samp.radialHistogram(kDirComb[0],rmax=1) plt.title('Radial Histogram Combo Dens Shared')
'c': 0.6, 'xtol': xtol, 'TVWeight': TVWeight, 'XFMWeight': XFMWeight, 'N': N }) im_res = im_result['x'].reshape(N) plt.imshow(im_res, clim=(minval, maxval), interpolation='bilinear') plt.title("Reconstructed Image with %d%% Sampling and im_dc==" % (pctg * 100) + imdcs) plt.show() if imdcs == 'densCorr': saveFig.save( "brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_firstRun_im_dc_" % (pctg * 100) + imdcs) np.save( "brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_firstRun_im_dc_" % (pctg * 100) + imdcs, im_res) elif imdcs == 'densCorr_Completed': saveFig.save( "brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_secondRun_im_dc_TVXFM_0.001" % (pctg * 100) + imdcs) np.save( "brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/replicate/seed1000_%.2fper_secondRun_im_dc_TVXFM_0.001" % (pctg * 100) + imdcs, im_res) #lrLoc = int(np.ceil((294-np.ceil(294/np.sqrt(1/pctg)))/2)) #im_lr = tf.fft2c(np.fft.fftshift(np.fft.fftshift(tf.ifft2c(im,np.ones(im.shape)))[lrLoc:-lrLoc,lrLoc:-lrLoc]),np.ones(im[lrLoc:-lrLoc,lrLoc:-lrLoc].shape)) #plt.imshow(abs(im_lr))
def runCSAlgorithm( fromfid=False, filename='/home/asalerno/Documents/pyDirectionCompSense/brainData/P14/data/fullySampledBrain.npy', sliceChoice=150, strtag=['', 'spatial', 'spatial'], xtol=[1e-2, 1e-3, 5e-4, 5e-4], TV=[0.01, 0.005, 0.002, 0.001], XFM=[0.01, .005, 0.002, 0.001], dirWeight=0, pctg=0.25, radius=0.2, P=2, pft=False, ext=0.5, wavelet='db4', mode='per', method='CG', ItnLim=30, lineSearchItnLim=30, alpha_0=0.6, c=0.6, a=10.0, kern=np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., -1., 0.], [0., 1., 0.]], [[0., 0., 0.], [0., -1., 1.], [0., 0., 0.]]]), dirFile=None, nmins=None, dirs=None, M=None, dirInfo=[None] * 4, saveNpy=False, saveNpyFile=None, saveImsPng=False, saveImsPngFile=None, saveImDiffPng=False, saveImDiffPngFile=None, disp=False): ##import pdb; pdb.set_trace() if fromfid == True: inputdirectory = filename[0] petable = filename[1] fullImData = rff.getDataFromFID(petable, inputdirectory, 2)[0, :, :, :] fullImData = fullImData / np.max(abs(fullImData)) im = fullImData[:, :, sliceChoice] else: im = np.load(filename)[sliceChoice, :, :] N = np.array(im.shape) # image Size pdf = samp.genPDF(N[-2:], P, pctg, radius=radius, cyl=np.hstack([1, N[-2:]]), style='mult', pft=pft, ext=ext) if pft: print('Partial Fourier sampling method used') k = samp.genSampling(pdf, 50, 2)[0].astype(int) if len(N) == 2: N = np.hstack([1, N]) k = k.reshape(N) im = im.reshape(N) elif (len(N) == 3) and ('dir' not in strtag): k = k.reshape(np.hstack([1, N[-2:]])).repeat(N[0], 0) ph_ones = np.ones(N[-2:], complex) ph_scan = np.zeros(N, complex) data = np.zeros(N, complex) im_scan = np.zeros(N, complex) for i in range(N[0]): k[i, :, :] = np.fft.fftshift(k[i, :, :]) data[i, :, :] = k[i, :, :] * tf.fft2c(im[i, :, :], ph=ph_ones) # IMAGE from the "scanner data" im_scan_wph = tf.ifft2c(data[i, :, :], ph=ph_ones) ph_scan[i, :, :] = tf.matlab_style_gauss2D(im_scan_wph, shape=(5, 5)) ph_scan[i, :, :] = np.exp(1j * ph_scan[i, :, :]) im_scan[i, :, :] = tf.ifft2c(data[i, :, :], ph=ph_scan[i, :, :]) #im_lr = samp.loRes(im,pctg) # ------------------------------------------------------------------ # # A quick way to look at the PSF of the sampling pattern that we use # delta = np.zeros(N[-2:]) delta[int(N[-2] / 2), int(N[-1] / 2)] = 1 psf = tf.ifft2c(tf.fft2c(delta, ph_ones) * k, ph_ones) # ------------------------------------------------------------------ # ## ------------------------------------------------------------------ # ## -- Currently broken - Need to figure out what's happening here. -- # ## ------------------------------------------------------------------ # #if pft: #for i in xrange(N[0]): #dataHold = np.fft.fftshift(data[i,:,:]) #kHold = np.fft.fftshift(k[i,:,:]) #loc = 98 #for ix in xrange(N[-2]): #for iy in xrange(loc,N[-1]): #dataHold[-ix,-iy] = dataHold[ix,iy].conj() #kHold[-ix,-iy] = kHold[ix,iy] ## ------------------------------------------------------------------ # pdfDiv = pdf.copy() pdfZeros = np.where(pdf == 0) pdfDiv[pdfZeros] = 1 #im_scan_imag = im_scan.imag #im_scan = im_scan.real N_im = N.copy() hld, dims, dimOpt, dimLenOpt = tf.wt(im_scan[0].real, wavelet, mode) N = np.hstack([N_im[0], hld.shape]) w_scan = np.zeros(N) w_full = np.zeros(N) im_dc = np.zeros(N_im) w_dc = np.zeros(N) for i in xrange(N[0]): w_scan[i, :, :] = tf.wt(im_scan.real[i, :, :], wavelet, mode, dims, dimOpt, dimLenOpt)[0] w_full[i, :, :] = tf.wt(abs(im[i, :, :]), wavelet, mode, dims, dimOpt, dimLenOpt)[0] im_dc[i, :, :] = tf.ifft2c(data[i, :, :] / np.fft.ifftshift(pdfDiv), ph=ph_scan[i, :, :]).real.copy() w_dc[i, :, :] = tf.wt(im_dc, wavelet, mode, dims, dimOpt, dimLenOpt)[0] w_dc = w_dc.flatten() im_sp = im_dc.copy().reshape(N_im) minval = np.min(abs(im)) maxval = np.max(abs(im)) data = np.ascontiguousarray(data) imdcs = [ im_dc, np.zeros(N_im), np.ones(N_im), np.random.randn(np.prod(N_im)).reshape(N_im) ] imdcs[-1] = imdcs[-1] - np.min(imdcs[-1]) imdcs[-1] = imdcs[-1] / np.max(abs(imdcs[-1])) mets = [ 'Density Corrected', 'Zeros', '1/2' 's', 'Gaussian Random Shift (0,1)' ] wdcs = [] for i in range(len(imdcs)): wdcs.append( tf.wt(imdcs[i][0], wavelet, mode, dims, dimOpt, dimLenOpt)[0].reshape(N)) ims = [] #print('Starting the CS Algorithm') for kk in range(len(wdcs)): w_dc = wdcs[kk] print(mets[kk]) for i in range(len(TV)): args = (N, N_im, dims, dimOpt, dimLenOpt, TV[i], XFM[i], data, k, strtag, ph_scan, kern, dirWeight, dirs, dirInfo, nmins, wavelet, mode, a) w_result = opt.minimize(f, w_dc, args=args, method=method, jac=df, options={ 'maxiter': ItnLim, 'lineSearchItnLim': lineSearchItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': alpha_0, 'c': c, 'xtol': xtol[i], 'TVWeight': TV[i], 'XFMWeight': XFM[i], 'N': N }) if np.any(np.isnan(w_result['x'])): print('Some nan' 's found. Dropping TV and XFM values') elif w_result['status'] != 0: print( 'TV and XFM values too high -- no solution found. Dropping...' ) else: w_dc = w_result['x'] w_res = w_dc.reshape(N) im_res = np.zeros(N_im) for i in xrange(N[0]): im_res[i, :, :] = tf.iwt(w_res[i, :, :], wavelet, mode, dims, dimOpt, dimLenOpt) ims.append(im_res) if saveNpy: if saveNpyFile is None: np.save('./holdSave_im_res_' + str(int(pctg * 100)) + 'p_all_SP', ims) else: np.save(saveNpyFile, ims) if saveImsPng: vis.figSubplots(ims, titles=mets, clims=(minval, maxval), colorbar=True) if not disp: if saveImsPngFile is None: saveFig.save('./holdSave_ims_' + str(int(pctg * 100)) + 'p_all_SP') else: saveFig.save(saveImsPngFile) if saveImDiffPng: imdiffs, clims = vis.imDiff(ims) diffMets = [ 'DC-Zeros', 'DC-Ones', 'DC-Random', 'Zeros-Ones', 'Zeros-Random', 'Ones-Random' ] vis.figSubplots(imdiffs, titles=diffMets, clims=clims, colorbar=True) if not disp: if saveImDiffPngFile is None: saveFig.save('./holdSave_im_diffs_' + str(int(pctg * 100)) + 'p_all_SP') else: saveFig.save(saveImDiffPngFile) if disp: plt.show()
clim.append(np.min(im),np.max(im)) for j in range(len(TV)): for k in range(len(XFM)): for m in range(len(lam_trust)): imRMSE[i,j,k,m,:,:] = np.load('temp/' + str(int(100*pctg)) + '_slice_' + str(SL[i]) + '_TV_' + str(TV[j]) + '_XFM_' + str(XFM[k]) + '_lamTrust_' + str(int(100*lam_trust[m])) + '.npy') rmses[i,j,k,m] = rmse(imRMSE[i,j,k,m,:,:],im) titles = [] for j in range(len(TV)): for k in range(len(XFM)): titles.append('TV = ' + str(TV[j]) + ' XFM = ' + str(XFM[k])) for i in range(len(SL)): for m in range(len(lam_trust)): labs = ['Slice ' + str(SL[i]) + ' with $\lambda_{trust}$ = ' + str(lam_trust[m]), 'TV', 'XFM'] vis.figSubplots(np.concatenate(imRMSE[i,:,:,m,:,:],axis=0),titles=titles,labs=labs) saveFig.save('/hpf/largeprojects/MICe/asalerno/pyDirectionCompSense/tests/rmseTests/ims_sl_' + str(SL[i]) + '_lamTrust_' + str(lam_trust[m]) + '_allTVXFM') fig, ax = plt.subplots() img = ax.imshow(rmses[i,:,:,m],cmap='jet',interpolation='None') ax.set_title('RMSE: Slice ' + str(SL[i]) + ' $\lambda_{trust}$ = ' + str(lam_trust[m])) strTV = [''] strXFM = [''] [strTV.append(TV[q]) for q in range(len(TV))] [strXFM.append(XFM[q]) for q in range(len(XFM))] ax.set_xticklabels(strTV) ax.set_yticklabels(strXFM) fig.colorbar(img) saveFig.save('/hpf/largeprojects/MICe/asalerno/pyDirectionCompSense/tests/rmseTests/rmses_sl_' + str(SL[i]) + '_lamTrust_' + str(lam_trust[m]) + '_allTVXFM')
tvStps.append(TV[i]) w_res = w_dc.reshape(N) im_res = np.zeros(N_im) for i in xrange(N[0]): im_res[i,:,:] = tf.iwt(w_res[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt) ims.append(im_res) data_res = tf.fft2c(im_res,ph_scan) data_diff = np.fft.fftshift(data_res-data)*k plt.imshow(abs(data_diff)[0]); plt.colorbar(); saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/phantomKernTests/noise_' + str(int(100*pctg)) + '_ksp_diff_abs') plt.imshow(data_diff.real[0]); plt.colorbar(); saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/phantomKernTests/noise_' + str(int(100*pctg)) + '_ksp_diff_real') plt.imshow(data_diff.imag[0]); plt.colorbar(); saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/phantomKernTests/noise_' + str(int(100*pctg)) + '_ksp_diff_imag') im_stps = np.zeros([len(stps), N_im[-2], N_im[-1]]) gtv = np.zeros([len(stps), N_im[-2], N_im[-1]]) gxfm = np.zeros([len(stps), N_im[-2], N_im[-1]]) gdc = np.zeros([len(stps), N_im[-2], N_im[-1]]) for jj in range(len(stps)): im_stps[jj,:,:] = tf.iwt(stps[jj].reshape(N[-2:]),wavelet,mode,dims,dimOpt,dimLenOpt) gtv[jj,:,:] = grads.gTV(im_stps[jj,:,:].reshape(N_im),N_im,strtag, kern, 0, a=a) gxfm[jj,:,:] = tf.iwt(grads.gXFM(stps[jj].reshape(N[-2:]),a=a),wavelet,mode,dims,dimOpt,dimLenOpt) gdc[jj,:,:] = grads.gDataCons(im_stps[jj,:,:], N_im, ph_scan, data, k)
plt.imshow(imgsData[pc,TV,XFM,0,:,:],clim=[minval,maxval]) ax2.set_title('Recon %.2f%% samp imdc=zeros' % (pctg*100)) ax3 = fig.add_subplot(2,3,3) plt.imshow(imgsData[pc,TV,XFM,1,:,:],clim=(minval,maxval)) ax3.set_title('Recon %.2f%% samp imdc=ones' % (pctg*100)) ax4 = fig.add_subplot(2,3,4) plt.imshow(abs(im_lr)) ax4.set_title('Low Res with %.2f%% of Data' % (pctg*100)) ax5 = fig.add_subplot(2,3,5) plt.imshow(imgsData[pc,TV,XFM,2,:,:],clim=(minval,maxval)) ax5.set_title('Recon %.2f%% samp imdc=densCorr' % (pctg*100)) ax6 = fig.add_subplot(2,3,6) plt.imshow(imgsData[pc,TV,XFM,3,:,:],clim=(minval,maxval)) ax6.set_title('Recon %.2f%% samp imdc=imFull' % (pctg*100)) saveFig.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/TV%s_XFM%s/%.2fper_im_lr_edit_comparison" % (float('%.1g' % TVWeight), float('%.1g' % XFMWeight), pctg)) XFM=-1 TV=-1 # Rerunning data comparison pctg = 0.25 im = np.load('/home/asalerno/Documents/pyDirectionCompSense/brainData/exercise_irradiation/bruker_data/running_C/P14/fullySampledBrain.npy') N = im.shape minval = np.min(im) maxval = np.max(im) lrLoc = int(np.ceil((N[0]-np.ceil(N[0]/np.sqrt(1/pctg)))/2)) im_lr = tf.fft2c(np.fft.fftshift(np.fft.fftshift(tf.ifft2c(im,np.ones(im.shape)))[lrLoc:-lrLoc,lrLoc:-lrLoc]),np.ones(im[lrLoc:-lrLoc,lrLoc:-lrLoc].shape))
#----------------# # Step 1 # #----------------# args = (N, TV1, XFM1, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': xtol1, 'TVWeight': TV1, 'XFMWeight': XFM1, 'N': N}) im_dc = im_result['x'].reshape(N) #----------------# # Step 2 # #----------------# args = (N, TV2, XFM2, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': xtol2, 'TVWeight': TV2, 'XFMWeight': XFM2, 'N': N}) im_dc = im_result['x'].reshape(N) #----------------# # Step 3 # #----------------# args = (N, TV3, XFM3, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': xtol3, 'TVWeight': TV3, 'XFMWeight': XFM3, 'N': N}) im_res = im_result['x'].reshape(N) plt.imshow(abs(im_res),clim=(minval,maxval),interpolation='bilinear') plt.title("25% Data -- P=" + str(P) + " -- 3 Rounds") plt.xlabel('TV1=XFM1=' + str(TV1) + ' TV2=XFM2=' + str(TV2) + ' TV3=XFM3=' + str(TV3)) saveFig.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/P_analysis/1_overr_p/seed" + str(int(seeds[sdcnt])) + '/3rounds_P_' + str(P) + '_ph_1') np.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/P_analysis/1_overr_p/seed" + str(int(seeds[sdcnt])) + "/3rounds_P_" + str(P) + '_ph_1.npy',im_res)
gtv[jj, :, :] = grads.gTV(im_stps[jj, :, :].reshape(N_im), N_im, strtag, kern, 0, a=a) gxfm[jj, :, :] = tf.iwt(grads.gXFM(stps[jj].reshape(N[-2:]), a=a), wavelet, mode, dims, dimOpt, dimLenOpt) gdc[jj, :, :] = grads.gDataCons(im_stps[jj, :, :], N_im, ph_scan, data, k) for i in xrange(len(stps)): plt.imshow(im_stps[i]) plt.colorbar() plt.title('Step with Negative Values') saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/gradTests/' + str(int(100 * pctg)) + '_TV_XFM_' + str(TV[i]) + '_0_a_' + str(int(a)) + '_negs') vis.figSubplots([im_stps[i], gtv[i], gxfm[i], gdc[i]], titles=['Step', 'gTV', 'gXFM', 'gDC'], clims=[(minval, maxval), (np.min(gtv[i]), np.max(gtv[i])), (np.min(gxfm[i]), np.max(gxfm[i])), (np.min(gdc[i]), np.max(gdc[i]))]) saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/gradTests/' + str(int(100 * pctg)) + '_TV_XFM_' + str(TV[i]) + '_0_a_' + str(int(a)) + '_grads') plt.imshow(TV[i] * gtv[i] + TV[i] * gxfm[i] + gdc[i]) plt.colorbar() plt.title('Total Gradient') saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/gradTests/' + str(int(100 * pctg)) + '_TV_XFM_' + str(TV[i]) + '_a_' + str(int(a)) + '_gradTotal')
im_dc, args=args, method=method, jac=derivative_fun, options={ 'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': xtol3, 'TVWeight': TV3, 'XFMWeight': XFM3, 'N': N }) im_res = im_result['x'].reshape(N) plt.imshow(abs(im_res), clim=(minval, maxval), interpolation='bilinear') plt.title("25% Data -- P=" + str(P) + " -- 3 Rounds") plt.xlabel('TV1=XFM1=' + str(TV1) + ' TV2=XFM2=' + str(TV2) + ' TV3=XFM3=' + str(TV3)) saveFig.save( "brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/P_analysis/1_overr_p/seed" + str(int(seeds[sdcnt])) + '/3rounds_P_' + str(P) + '_ph_1') np.save( "brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/P_analysis/1_overr_p/seed" + str(int(seeds[sdcnt])) + "/3rounds_P_" + str(P) + '_ph_1.npy', im_res)
cols = ('b','k','r','g','m','c','y','0.5','0.75',(0.25,0.25,0.75),(1,0.25,0.5)) fig=plt.figure() strPs = map(str,Ps) for P in Ps: print(P) cnt += 1 plt.plot(rads,pdfmult[cnt,147,:],color=cols[cnt]) #samp.pltSlice(pdfmult[cnt,:,:],sl=147,rads=rads,col=cols[cnt]) plt.legend(strPs) plt.xlim(-np.sqrt(2),np.sqrt(2)) plt.ylim(0,1.1) plt.xlabel('Radius') plt.ylabel('PDF') plt.title('PDF using 1/|r|^p') saveFig.save('/micehome/asalerno/Documents/pyDirectionCompSense/brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/pdf/r_-p_method_compared') cnt = -1 pleg=[] for P in Ps: print(P) cnt += 1 if P>2: pleg.append(str(P)) plt.plot(rads,pdfadd[cnt,147,:],color=cols[cnt]) #samp.pltSlice(pdfmult[cnt,:,:],sl=147,rads=rads,col=cols[cnt]) plt.legend(strPs) plt.xlim(-np.sqrt(2),np.sqrt(2)) plt.ylim(0,1.1) plt.xlabel('Radius') plt.ylabel('PDF')
w_dc = w_result['x'] stps.append(w_dc) tvStps.append(TV[i]) w_res = w_dc.reshape(N) im_res = np.zeros(N_im) for i in xrange(N[0]): im_res[i,:,:] = tf.iwt(w_res[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt) ims.append(im_res) im_stps = np.zeros([len(stps), N_im[-2], N_im[-1]]) gtv = np.zeros([len(stps), N_im[-2], N_im[-1]]) gxfm = np.zeros([len(stps), N_im[-2], N_im[-1]]) gdc = np.zeros([len(stps), N_im[-2], N_im[-1]]) for jj in range(len(stps)): im_stps[jj,:,:] = tf.iwt(stps[jj].reshape(N[-2:]),wavelet,mode,dims,dimOpt,dimLenOpt) gtv[jj,:,:] = grads.gTV(im_stps[jj,:,:].reshape(N_im),N_im,strtag, kern, 0, a=a) gxfm[jj,:,:] = tf.iwt(grads.gXFM(stps[jj].reshape(N[-2:]),a=a),wavelet,mode,dims,dimOpt,dimLenOpt) gdc[jj,:,:] = grads.gDataCons(im_stps[jj,:,:], N_im, ph_scan, data, k) for i in xrange(len(stps)): vis.figSubplots([im_stps[i],gtv[i],gxfm[i],gdc[i]],titles=['Step','gTV','gXFM','gDC']) saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/gradTests/'+ str(int(100*pctg)) + '_TV_XFM_'+ str(TV[i]) +'_grads') plt.imshow(TV[i]*gtv[i] + TV[i]*gxfm[i] + gdc[i]) plt.colorbar() plt.title('Total Gradient') saveFig.save('/home/asalerno/Documents/pyDirectionCompSense/gradTests/'+ str(int(100*pctg)) + '_TV_XFM_'+ str(TV[i]) +'_gradTotal')
#----------------# args = (N, TV3, XFM3, data, k, strtag, ph_scan, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': c*alpha_k, 'c': c, 'xtol': xtol3, 'TVWeight': TV3, 'XFMWeight': XFM3, 'N': N}) im_dc = im_result['x'].reshape(N) alpha_k = im_result['alpha_k'] #----------------# # Step 4 # #----------------# args = (N, TV4, XFM4, data, k, strtag, ph_scan, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': c*alpha_k, 'c': c, 'xtol': xtol4, 'TVWeight': TV4, 'XFMWeight': XFM4, 'N': N}) im_dc = im_result['x'].reshape(N) alpha_k = im_result['alpha_k'] #----------------# # Step 5 # #----------------# args = (N, TV5, XFM5, data, k, strtag, ph_scan, dirWeight, dirs, M, nmins, wavelet, mode, a) im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun, options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': c*alpha_k, 'c': c, 'xtol': xtol5, 'TVWeight': TV5, 'XFMWeight': XFM5, 'N': N}) im_res = im_result['x'].reshape(N) plt.imshow(abs(im_res),clim=(minval,maxval),interpolation='bilinear') plt.title("25% Data -- P=" + str(P) + " -- 5 Rounds") plt.xlabel('TV=XFM= [' + str(TV1) + ', ' + str(TV2) + ', ' + str(TV3) + ', ' + str(TV4) + ', ' + str(TV5) + ']') #plt.show() saveFig.save("brainData/P14/5rounds_P_" + str(P) + '_pctg_' + str(pctg) + '_sl_' + str(sliceChoice)) #np.save("brainData/exercise_irradiation/bruker_data/running_C/P14/rad_0.1/P_analysis/3rounds_P_" + str(P) + '.npy',im_res)