def unwrap_freq(im): max_im = 0.8 * ut.scaling(np.absolute(im)) scaled_im = (im) / max_im * np.pi ut.plotim1(im, bar=1, pause_close=5) im = unwrap_phase(scaled_im) / np.pi * max_im ut.plotim1(im, bar=1, pause_close=5) return im
def unwrap_freq( im ): max_im = ut.scaling(np.absolute(im)) scaled_im = (im)/max_im*np.pi #ut.plotim1(im) im = unwrap_phase(scaled_im.astype(np.float))/np.pi*max_im ut.plotim1(np.real(im),bar=1) return im
def test(): # simulated image mat_contents = sio.loadmat('data/brain_32ch.mat'); x = mat_contents["DATA"] #mask = mat_contents["mask_randm_x3"].astype(np.float) nx,ny,nc = x.shape #crop k-space xcrop = ut.crop2d( x, 16 ) if 0:#do espirit Vim, sim = espirit_2d(xcrop, x.shape,\ nsingularv = 150, hkwin_shape = (16,16,16), pad_before_espirit = 0, pad_fact = 2 ) #coil map ut.plotim3(np.absolute(Vim),[4,-1],bar = 1) ut.plotim1(np.absolute(sim),bar = 1) #create espirit operator esp = opts.espirit(Vim) esp.save('../save_data/espirit_data_2d.mat') #esp.save('/working/larson/UTE_GRE_shuffling_recon/python_test/save_data/espirit_data_2d.mat') else: esp = opts.espirit() esp.restore('../save_data/espirit_data_2d.mat') #esp.restore('/working/larson/UTE_GRE_shuffling_recon/python_test/save_data/espirit_data_2d.mat') #create mask mask = ut.mask2d( nx, ny, center_r = 15, undersampling = 0.25 ) #FTm = opts.FFT2d_kmask(mask) FTm = opts.FFTW2d_kmask(mask) #ut.plotim1(np.absolute(mask))#plot the mask Aopt = opts.joint2operators(esp, FTm) #create image im = FTm.backward(x) #ut.plotim3(np.absolute(im[:,:,:])) #wavelet operator dwt = opts.DWT2d(wavelet = 'haar', level=4) # undersampling in k-space b = FTm.forward(im) scaling = ut.optscaling(FTm,b) b = b/scaling ut.plotim1(np.absolute(Aopt.backward(b))) #undersampled imag #do cs mri recon Nite = 40 #number of iterations step = 0.5 #step size tv_r = 0.002 # regularization term for tv term rho = 1.0 #th = 1 #threshold #xopt = solvers.IST_2(FTm.forward,FTm.backward,b, Nite, step,th) #soft thresholding xopt = solvers.ADMM_l2Afxnb_tvx( Aopt.forward, Aopt.backward, b, Nite, step, tv_r, rho) #xopt = solvers.ADMM_l2Afxnb_l1x_2( FTm.forward, FTm.backward, b, Nite, step, 100, 1 ) ut.plotim3(np.absolute(xopt))
def time_nufft2d1( nufft_func, ms=1000, mt=1000, mc=1000, Reptime=5 ): rng = np.random.RandomState(0) # Time the nufft function x = 100 * rng.rand(mc) y = 100 * rng.rand(mc) #c = np.sin(x) #two peaks in transformed space along x c = np.sin(y) #two peaks in transformed space along y #c = np.ones(x.shape) #one peak in the center of transformed space times = [] for i in range(Reptime): t0 = time() F = nufft_func(x, y, c, ms, mt) t1 = time() times.append(t1 - t0) ut.plotim1(np.absolute(F), colormap = None, title = None, bar = True) print("- Execution time (M={0}): {1:.2g} sec".format(mc, np.median(times)))
def test(): ft = opts.FFT2d() # simulated image mat_contents = sio.loadmat('data/brain_32ch.mat'); x = mat_contents["DATA"] #ut.plotim1(np.absolute(x[:,:,0])) im = ft.backward(x[:,:,:]) ut.plotim3(np.absolute(im[:,:,:])) #crop k-space xcrop = ut.crop2d( x, 16 ) #do espirit2d Vim, sim = espirit_2d(xcrop, x.shape,\ nsingularv = 150, hkwin_shape = (16,16,16), pad_before_espirit = 0, pad_fact = 2 ) ut.plotim3(np.absolute(Vim)) esp = opts.espirit(Vim) esp_im = esp.backward(im) ut.plotim1(np.absolute(esp_im)) im_recon = esp.forward(esp_im) ut.plotim3(np.absolute(im_recon[:,:,:]))
def test(): cam = pywt.data.camera() ut.plotim1(cam) arr, coeff_slices = dwt2d(cam) ut.plotim1(arr) cam_recon = idwt2d(arr, coeff_slices) ut.plotim1(cam_recon)
def test(): # simulated image mat_contents = sio.loadmat('data/sim_2dmri.mat') im = mat_contents["sim_2dmri"] #im = spimg.zoom(xorig, 0.4) #plotim2(im) #dwt = opts.DWTnd( wavelet = 'haar', level = 2, axes = (0, 1)) dwt = opts.DWT2d(wavelet='haar', level=4) nx, ny = im.shape mask = ut.mask2d(nx, ny, center_r=15) FTm = opts.FFT2d_kmask(mask) ut.plotim1(np.absolute(mask)) #plot the mask # undersampling in k-space b = FTm.forward(im) scaling = ut.optscaling(FTm, b) b = b / scaling ut.plotim1(np.absolute(FTm.backward(b))) #undersampled imag #do soft thresholding Nite = 100 #number of iterations step = 1 #step size th = 1.5 # theshold level #xopt = solvers.IST_2(FTm.forward, FTm.backward, b, Nite, step,th) xopt = solvers.IST_3(FTm.forward, FTm.backward, dwt.backward, dwt.forward, b, Nite, step, th) ut.plotim1(np.absolute(xopt))
def test1(): N = 20 k1, k2 = nufftfreqs2d(N, N) k_c = np.cos(np.multiply(5, k1)) + 1j * np.sin(np.multiply(5, k2)) # #k_c = np.ones((N,N))# hwin = hamming2d(N, N) #ut.plotgray(np.absolute(hwin)) # apply hamming window k_c = np.multiply(k_c, hwin) im = dft2d_warp(N, N, k_c) ut.plotim1(np.absolute(im), bar=True) #use std fft lib ft = opts.FFT2d() npim = ft.backward(k_c) ut.plotim1(np.absolute(npim), bar=True) ut.plotim1(np.absolute(im - npim), bar=True) #interpolatation im_int = dft2d_warp(5 * N, 5 * N, k_c) ut.plotim1(np.absolute(im_int), bar=True)
def compare_nufft2d21( nufft_func1, nufft_func2, ms=1000, mt=1000, mc=100000, Reptime=5 ): rng = np.random.RandomState(0) # Time the nufft function x = 100 * rng.rand(mc) y = 100 * rng.rand(mc) c0 = np.sin(x) F1 = nufft_func1(x, y, c0, ms, mt) times = [] for i in range(Reptime): t0 = time() F2 = nufft_func2(x, y, F1, ms, mt) t1 = time() times.append(t1 - t0) ut.plotim1(np.absolute(F1), colormap = None, title = None, bar = True) ut.plotim1(np.absolute(F2), colormap = None, title = None, bar = True) ut.plotim1(np.absolute(F1-F2), colormap = None, title = None, bar = True) print("- Execution time (M={0}): {1:.2g} sec".format(mc, np.median(times)))
def compare_nufft2d1( nufft_func1, nufft_func2, ms=1000, mt=1000, mc=100000 ): # Test vs the direct method print(30 * '-') rng = np.random.RandomState(0) x = 100 * rng.rand(mc) y = 100 * rng.rand(mc) c = np.sin(2*x) + 1j*np.cos(2*y)#np.ones(x.shape)# for df in [1.0, 2.0]: for iflag in [1, -1]: print ("testing 2d df=%f, iflag=%f"% (df,iflag)) F1 = nufft_func1(x, y, c, ms, mt, df=df, iflag=iflag) F2 = nufft_func2(x, y, c, ms, mt, df=df, iflag=iflag) ut.plotim1(np.absolute(F1), colormap = None, title = None, bar = True) ut.plotim1(np.absolute(F2), colormap = None, title = None, bar = True) ut.plotim1(np.absolute(F1-F2), colormap = None, title = None, bar = True) assert np.allclose(F1, F2, rtol=1e-02, atol=1e-02) print("- Results match the 2d DFT")
def compare_nufft3d1( nufft_func1, nufft_func2, ms=1000, mt=1000, mu=1000, mc=100000 ): # Test vs the direct method print(30 * '-') rng = np.random.RandomState(0) x = 100 * rng.rand(mc) y = 100 * rng.rand(mc) z = 100 * rng.rand(mc) c = np.sin(2*x) + 1j*np.cos(2*y) for df in [1]: for iflag in [1, -1]: print ("testing 3d df=%f, iflag=%f"% (df,iflag)) F1 = nufft_func1(x, y, z, c, ms, mt, mu, df=df, iflag=iflag) F2 = nufft_func2(x, y, z, c, ms, mt, mu, df=df, iflag=iflag) ut.plotim1(np.absolute(F1[:,:,mu//2]), colormap = None, title = None, bar = True) ut.plotim1(np.absolute(F2[:,:,mu//2]), colormap = None, title = None, bar = True) ut.plotim1(np.absolute(F1[:,:,mu//2]-F2[:,:,mu//2]), colormap = None, title = None, bar = True) assert np.allclose(F1, F2, rtol=1e-02, atol=1e-02) print("- Results match the 3d DFT")
def test(): # simulated image mat_contents = sio.loadmat('data/brain_32ch.mat') x = mat_contents["DATA"] #mask = mat_contents["mask_randm_x3"].astype(np.float) nx, ny, nc = x.shape #crop k-space xcrop = ut.crop2d(x, 16) if 0: #do espirit Vim, sim = espirit_2d(xcrop, x.shape,\ nsingularv = 150, hkwin_shape = (16,16,16), pad_before_espirit = 0, pad_fact = 2 ) #coil map ut.plotim3(np.absolute(Vim), [4, -1], bar=1) ut.plotim1(np.absolute(sim), bar=1) #create espirit operator esp = opts.espirit(Vim) esp.save('../save_data/espirit_data_2d.mat') else: esp = opts.espirit() esp.restore('../save_data/espirit_data_2d.mat') #create mask mask = ut.mask2d(nx, ny, center_r=15, undersampling=0.25) FTm = opts.FFT2d_kmask(mask) ut.plotim1(np.absolute(mask)) #plot the mask Aopt = opts.joint2operators(esp, FTm) #create image im = FTm.backward(x) #ut.plotim3(np.absolute(im[:,:,:])) #wavelet operator dwt = opts.DWT2d(wavelet='haar', level=4) # undersampling in k-space b = FTm.forward(im) scaling = ut.optscaling(FTm, b) b = b / scaling ut.plotim1(np.absolute(Aopt.backward(b))) #undersampled imag #do soft thresholding Nite = 50 #number of iterations step = 1 #step size th = 0.1 # theshold level #xopt = solvers.IST_2(FTm.forward, FTm.backward, b, Nite, step,th) xopt = solvers.FIST_3(Aopt.forward, Aopt.backward, dwt.backward, dwt.forward, b, Nite, step, th) ut.plotim3(np.absolute(xopt))
def test(): # simulated image mat_contents = sio.loadmat('data/sim_2dmri.mat') x = mat_contents["sim_2dmri"] nx, ny = x.shape mask = ut.mask2d(nx, ny, center_r=15) FTm = opts.FFT2d_kmask(mask) ut.plotim1(np.absolute(mask)) #plot the mask # undersampling in k-space b = FTm.forward(x) ut.plotim1(np.absolute(FTm.backward(b))) #undersampled imag #do cs mri recon Nite = 20 #number of iterations step = 0.5 #step size #th = 1 #threshold #xopt = solvers.IST_2(FTm.forward,FTm.backward,b, Nite, step,th) #soft thresholding xopt = solvers.ADMM_l2Afxnb_tvx(FTm.forward, FTm.backward, b, Nite, step, 10, 1) #xopt = solvers.ADMM_l2Afxnb_l1x_2( FTm.forward, FTm.backward, b, Nite, step, 100, 1 ) ut.plotim1(np.absolute(xopt))
def espirit_3d( xcrop, x_shape, nsingularv = 150, hkwin_shape = (16,16,16),\ pad_before_espirit = 0, pad_fact = 1, sigv_th = 0.01, nsigv_th = 0.2 ): #ft = op.FFTnd((0,1,2))#3d fft operator ft = op.FFTWnd((0, 1, 2)) #3d fft operator timing = utc.timing() #multidimention tensor as the block hankel matrix #first 2 are x, y dims with rolling window size of hkwin_shape #last 1 is coil dimension, with stride of 1 # output dims are : (3_hankel_dims + 1_coil_dim)_win_size + (3_hankel_dims + 1_coil_dim)_rolling_times timing.start() h = hk.hankelnd_r(xcrop, (hkwin_shape[0], hkwin_shape[1], hkwin_shape[2], 1)) timing.stop().display('Create Hankel ').start() dimh = h.shape #flatten the tensor to create a matrix= [flatten(fist4 dims), flatten(last4 dims)] #the second dim of hmtx contain coil information, i.e. dimh[3]=1, dimh[7]=N_coils hmtx = h.reshape(( dimh[0]* dimh[1]* dimh[2]* dimh[3], dimh[4], dimh[5], dimh[6], dimh[7])).\ reshape((dimh[0]* dimh[1]* dimh[2]* dimh[3], dimh[4]* dimh[5]* dimh[6]* dimh[7])) timing.stop().display('Reshape Hankel ').start() #svd, could try other approaches # V has the coil information since the second dim of hmtx has coil data U, s, V = np.linalg.svd(hmtx, full_matrices=False) #U, s, V = randomized_svd(hmtx, n_components=nsingularv,n_iter=5,random_state=None) #U, s, V = scipy.sparse.linalg.svds(hmtx, nsingularv ) timing.stop().display('SVD ').start() #S = np.diag(s) #ut.plotim1(np.absolute(V[:,0:150]).T)#plot V singular vectors ut.plot(s.T) #plot singular values for k in range(len(s)): if s[k] > s[0] * nsigv_th: nsingularv = k print('extract %g out of %g singular vectors' % (nsingularv, len(s))) #invh = np.zeros(x.shape,complex) #print h.shape #hk.invhankelnd(h,invh,(2,3,1)) #reshape vn to generate k-space vn tensor #first dim is singular vector, which is transposed to the second last dimension vn = V[0:nsingularv, :].reshape( (nsingularv, dimh[4], dimh[5], dimh[6], dimh[7])).transpose( (1, 2, 3, 0, 4)) #zero pad vn, vn matrix of reshaped singular vectors, #dims of vn: nx,ny,nsingularv,ncoil #do pading before espirit, reduce the memory requirement if pad_before_espirit is 0: nx = min(pad_fact * xcrop.shape[0], x_shape[0]) ny = min(pad_fact * xcrop.shape[1], x_shape[1]) nz = min(pad_fact * xcrop.shape[2], x_shape[2]) else: nx = x_shape[0] ny = x_shape[1] nz = x_shape[2] #coil dim nc = x_shape[3] #create hamming window hwin = hamming3d(vn.shape[0], vn.shape[1], vn.shape[2]) # apply hamming window vn = np.multiply(vn, hwin[:, :, :, np.newaxis, np.newaxis]) #zero pad vn = ut.pad3d(vn, nx, ny, nz) #plot first singular vecctor Vn[0] imvn = ft.backward(vn) #ut.plotim3(np.absolute(imvn[:,:,0,:].squeeze()))#spatial feature of V[:,1] singular vector sim = np.zeros((nx, ny, nz), dtype=vn.dtype) Vim = np.zeros((nx, ny, nz, nc), dtype=vn.dtype) #espirit loop, Vim eigen vector, Sim eigen value, this is a pixel wise PCA on vn for ix in range(nx): for iy in range(ny): for iz in range(nz): vpix = imvn[ix, iy, iz, :, :].squeeze() vpix = np.matrix(vpix).transpose() vvH = vpix.dot(vpix.getH()) U, s, V = np.linalg.svd(vvH, full_matrices=False) #s, V = numpy.linalg.eig(vvH) #U, s, V = randomized_svd(vvH, n_components=2,n_iter=5,random_state=None) sim[ix, iy, iz] = s[0] Vim[ix, iy, iz, :] = V[0, :].squeeze() Vim = np.conj(Vim) timing.stop().display('ESPIRIT ') #pad the image after espirit if pad_before_espirit is 0: Vim = ft.backward( ut.pad3d(ft.forward(Vim), x_shape[0], x_shape[1], x_shape[2])) sim = ft.backward( ut.pad3d(ft.forward(sim), x_shape[0], x_shape[1], x_shape[2])) #plot first eigen vector, which is coil sensitvity map, and eigen value ut.plotim3(np.absolute(Vim[Vim.shape[0] // 2, :, :, :].squeeze())) ut.plotim1(np.absolute(sim[Vim.shape[0] // 2, :, :].squeeze())) #Vim_dims_name = ['x', 'y', 'z', 'coil'] #sim_dims_name = ['x', 'y', 'z'] Vimnorm = np.linalg.norm(Vim, axis=3) Vim = np.divide(Vim, 1e-6 + Vimnorm[:, :, :, np.newaxis]) sim = sim / np.max(sim.flatten()) for ix in range(x_shape[0]): for iy in range(x_shape[1]): for iz in range(x_shape[2]): if sim[ix, iy, iz] < sigv_th: Vim[ix, iy, iz, :] = np.zeros(nc) return Vim, np.absolute(sim) #, Vim_dims_name, sim_dims_name
def test(): # simulated image mat_contents = sio.loadmat('data/sim_2dmri.mat') im = mat_contents["sim_2dmri"] #im = spimg.zoom(xorig, 0.4) #plotim2(im) #dwt = opts.DWTnd( wavelet = 'haar', level = 2, axes = (0, 1)) dwt = opts.DWT2d(wavelet='haar', level=4) nx, ny = im.shape mask = ut.mask2d(nx, ny, center_r=15) FTm = opts.FFT2d_kmask(mask) #FTm = opts.FFT2d() #ut.plotim1(np.absolute(mask))#plot the mask # undersampling in k-space b = FTm.forward(im) scaling = ut.optscaling(FTm, b) b = b / scaling #ut.plotim1(np.absolute(FTm.backward(b))) #undersampled imag tvop = tvopc.TV2d() #CGD Nite = 20 l1_r = 0.01 tv_r = 0.2 #def f(xi): #ut.plotim1(np.absolute(FTm.backward(FTm.forward(xi)-b)),bar=1) # return alg.obj_fidelity(FTm, xi, b) \ # + l1_r * alg.obj_sparsity(dwt, xi) \ # + tv_r * alg.obj_sparsity(tvop, xi) #def df(xi): #gradall = np.zeros(xi.shape) # gradall = alg.grad_fidelity(FTm, xi, b) # gradall += l1_r * alg.grad_sparsity(dwt, xi) # gradall += tv_r * alg.grad_sparsity(tvop, xi) # return gradall def h(xi): #ut.plotim1(np.absolute(FTm.backward(FTm.forward(xi)-b)),bar=1) return tv_r * alg.obj_sparsity(tvop, xi) + l1_r * alg.obj_sparsity( dwt, xi) # + def dh(xi): gradall = np.zeros(xi.shape, np.complex128) gradall += l1_r * alg.grad_sparsity(dwt, xi) gradall += tv_r * alg.grad_sparsity(tvop, xi) return gradall #xopt = alg.conjugate_gradient(f, df, FTm.backward(b), Nite ) #xopt = pf.prox_l2_Afxnb_CGD2( FTm.forward, FTm.backward, b, Nite ) xopt = FTm.backward(b) for _ in range(100): xopt = pf.prox_l2_Afxnb_CGD3(FTm.forward, FTm.backward, xopt, b, h, dh, Nite, 3) #ut.plotim1(np.absolute(xopt)) #do soft thresholding #Nite = 100 #number of iterations #step = 1 #step size #th = 1.5 # theshold level #xopt = solvers.IST_2(FTm.forward, FTm.backward, b, Nite, step,th) #xopt = solvers.IST_3( FTm.forward, FTm.backward, dwt.backward, dwt.forward, b, Nite, step, th ) ut.plotim1(np.absolute(xopt))
def test(): ft = opt.FFT2d() # simulated image mat_contents = sio.loadmat('data/brain_8ch.mat') x = mat_contents["DATA"] #ut.plotim1(np.absolute(x[:,:,0])) im = ft.backward(x[:, :, :]) ut.plotim3(np.absolute(im[:, :, :])) #shape of x nx, ny, nc = x.shape xcrop = ut.crop2d(x, 30) #ksp = ft.forward(im) #ut.plotim1(np.absolute(ksp[:,:])) #multidimention tensor as the block hankel matrix h = hk.hankelnd_r(xcrop, (16, 16, 1)) dimh = h.shape #flatten the tensor to create a matrix hmtx = h.reshape( (dimh[0] * dimh[1] * dimh[2], dimh[3], dimh[4], dimh[5])).reshape( (dimh[0] * dimh[1] * dimh[2], dimh[3] * dimh[4] * dimh[5])) #svd, could try other approaches U, s, V = np.linalg.svd(hmtx, full_matrices=False) #S = np.diag(s) #ut.plotim1(np.absolute(V[:,0:150]).T)#plot V singular vectors ut.plot(s) #plot sigular values #invh = np.zeros(x.shape,complex) #print h.shape #hk.invhankelnd(h,invh,(2,3,1)) #reshape vn to generate k-space vn tensor nsingular = 150 #number of truncated sigular vectors vn = V[0:nsingular, :].reshape( (nsingular, dimh[3], dimh[4], dimh[5])).transpose((1, 2, 0, 3)) #zero pad vn, vn matrix of reshaped singular vectors, #dims of vn: nx,ny,nsingular,ncoil vn = ut.pad2d(vn, nx, ny) #plot first singular vecctor Vn[0] imvn = ft.forward(vn) #ut.plotim3(np.absolute(imvn[:,:,0,:].squeeze()))#spatial feature of V[:,1] singular vector sim = 1j * np.zeros((nx, ny)) Vim = 1j * np.zeros((nx, ny, nc)) #Uim = 1j*np.zeros((nx,ny,nc)) for ix in range(nx): for iy in range(ny): vpix = imvn[ix, iy, :, :].squeeze() vpix = np.matrix(vpix).transpose() vvH = vpix.dot(vpix.getH()) U, s, V = np.linalg.svd(vvH, full_matrices=False) sim[ix, iy] = s[0] Vim[ix, iy, :] = V[0, :].squeeze() #Uim[ix,iy,:] = U[:,0].squeeze() #plot first eigen vector, eigen value ut.plotim3(np.absolute(Vim)) #ut.plotim3(np.absolute(Uim)) ut.plotim1(np.absolute(sim))