def create_nufft_list(radial_traj, max_spokes, nx, ny, ns): """Creates a list of PyNUFFT operators. For transforming k-spaces with a large number of spokes (~2000+). Divides the transformation into multiple operators to prevent memory overload. Args: radial_traj: The coordinates of the golden-angle radial k-space trajectory. Shape [ns, spokes, 2]. max_spokes: Maximum number of spokes in an NUFFT operator. Returns: nufft_list: List of planned PyNUFFT objects. Each object performs the transform for a subset of spokes. E.g. first operator is for spokes 1-500, second operator for spokes 501-1000, etc. nop: Number of operators. """ print('Creating PyNUFFT operators...', end=' ') spokes = radial_traj.shape[1] nop = math.ceil(spokes / max_spokes) # Divide into this many operators nufft_list = [] for i in range(nop): traj = radial_traj[:, i * max_spokes:(i + 1) * max_spokes, :] n_spokes = traj.shape[1] # Number of spokes in the subset traj = np.reshape(traj, (ns * n_spokes, 2)) # Reshape nufft_obj = NUFFT_cpu() # Create NUFFT object nufft_obj.plan(traj, (nx, ny), (ns, ns), (6, 6)) # Plan nufft_list.append(nufft_obj) print('Created %d operators for a total of %d spokes.\n' % (nop, spokes)) return nufft_list, nop
def spiral_recon(data_path, ktraj, N, plot=0): ## # Load the raw data ## dat = sio.loadmat(data_path + 'rawdata_spiral')['dat'] ## # Acq parameters ## Npoints = ktraj.shape[0] Nshots = ktraj.shape[1] Nchannels = dat.shape[-1] if len(dat.shape) < 4: Nslices = 1 dat = dat.reshape(Npoints, Nshots, 1, Nchannels) else: Nslices = dat.shape[-2] if dat.shape[0] != ktraj.shape[0] or dat.shape[1] != ktraj.shape[1]: raise ValueError('Raw data and k-space trajectory do not match!') ## # Arrange data for pyNUFFT ## om = np.zeros((Npoints * Nshots, 2)) om[:, 0] = np.real(ktraj).flatten() om[:, 1] = np.imag(ktraj).flatten() NufftObj = NUFFT_cpu() # Create a pynufft object Nd = (N, N) # image size Kd = (2 * N, 2 * N) # k-space size Jd = (6, 6) # interpolation size NufftObj.plan(om, Nd, Kd, Jd) ## # Recon ## im = np.zeros((N, N, Nslices, Nchannels), dtype=complex) for ch in range(Nchannels): for sl in range(Nslices): im[:, :, sl, ch] = NufftObj.solve(dat[:, :, sl, ch].flatten(), solver='cg', maxiter=50) sos = np.sum(np.abs(im), 2) sos = np.divide(sos, np.max(sos)) if plot: plt.imshow(np.rot90(np.abs(sos[:, :, 0]), -1), cmap='gray') plt.axis('off') plt.title('Uncorrected Image') plt.show() return
def example_3D(): import pkg_resources DATA_PATH = pkg_resources.resource_filename('pynufft', './src/data/') image = numpy.load(DATA_PATH + 'phantom_3D_128_128_128.npz')['arr_0'][0::2, 0::2, 0::2] pyplot.imshow(numpy.abs(image[:, :, 32]), label='original signal', cmap=gray) pyplot.show() Nd = (64, 64, 64) # time grid, tuple Kd = (64, 64, 64) # frequency grid, tuple Jd = (1, 1, 1) # interpolator # om= numpy.load(DATA_PATH+'om3D.npz')['arr_0'] om = numpy.random.randn(15120, 3) print(om.shape) from pynufft import NUFFT_cpu, NUFFT_hsa NufftObj = NUFFT_cpu() NufftObj.plan(om, Nd, Kd, Jd) kspace = NufftObj.forward(image) restore_image = NufftObj.solve(kspace, 'cg', maxiter=200) # restore_image1 = NufftObj.solve(kspace,'L1TVLAD', maxiter=200,rho=0.1) # restore_image2 = NufftObj.solve(kspace, 'L1TVOLS', maxiter=200, rho=0.1) pyplot.subplot(2, 2, 1) pyplot.imshow(numpy.abs(image[:, :, 32]), label='original signal', cmap=gray) pyplot.title('original') # pyplot.subplot(2,2,2) # pyplot.imshow(numpy.abs(restore_image1[:,:,32]), label='L1TVLAD',cmap=gray) # pyplot.title('L1TVLAD') pyplot.subplot(2, 2, 3) pyplot.imshow(numpy.abs(restore_image2[:, :, 32]), label='L1TVOLS', cmap=gray) pyplot.title('L1TVOLS') pyplot.subplot(2, 2, 4) pyplot.imshow(numpy.abs(restore_image[:, :, 32]), label='CG', cmap=gray) pyplot.title('CG') # pyplot.legend([im1, im im4]) pyplot.show()
def example_1D(): om = numpy.random.randn(1512, 1) # print(om) # print(om.shape) # pyplot.hist(om) # pyplot.show() Nd = (256, ) # time grid, tuple Kd = (512, ) # frequency grid, tuple Jd = (7, ) # interpolator from pynufft import NUFFT_cpu, NUFFT_hsa NufftObj = NUFFT_cpu() batch = 4 NufftObj.plan(om, Nd, Kd, Jd, batch=batch) time_data = numpy.zeros((256, batch)) time_data[64:192, :] = 1.0 pyplot.plot(time_data) pyplot.ylim(-1, 2) pyplot.show() nufft_freq_data = NufftObj.forward(time_data) print('shape of y = ', nufft_freq_data.shape) x2 = NufftObj.adjoint(nufft_freq_data) restore_time = NufftObj.solve(nufft_freq_data, 'cg', maxiter=30) restore_time1 = NufftObj.solve(nufft_freq_data, 'L1TVOLS', maxiter=30, rho=1) # # restore_time2 = NufftObj.solve(nufft_freq_data,'L1TVOLS', maxiter=30,rho=1) # # im1,=pyplot.plot(numpy.abs(time_data),'r',label='original signal') # im3,=pyplot.plot(numpy.abs(restore_time2),'k--',label='L1TVOLS') # im4,=pyplot.plot(numpy.abs(restore_time),'r:',label='conjugate_gradient_method') # pyplot.legend([im1, im2, im3,im4]) for slice in range(0, batch): pyplot.plot(numpy.abs(x2[:, slice])) pyplot.plot(numpy.abs(restore_time[:, slice])) pyplot.show()
def example_1D(): om = numpy.random.randn(1512,1) # print(om) # print(om.shape) # pyplot.hist(om) # pyplot.show() Nd = (256,) # time grid, tuple Kd = (512,) # frequency grid, tuple Jd = (7,) # interpolator from pynufft import NUFFT_cpu, NUFFT_hsa NufftObj = NUFFT_cpu() NufftObj.plan(om, Nd, Kd, Jd) time_data = numpy.zeros(256, ) time_data[64:192] = 1.0 pyplot.plot(time_data) pyplot.ylim(-1,2) pyplot.show() nufft_freq_data =NufftObj.forward(time_data) restore_time = NufftObj.solve(nufft_freq_data,'cg', maxiter=30) restore_time2 = NufftObj.solve(nufft_freq_data,'L1TVOLS', maxiter=30,rho=1) im1,=pyplot.plot(numpy.abs(time_data),'r',label='original signal') # im2,=pyplot.plot(numpy.abs(restore_time1),'b:',label='L1TVLAD') im3,=pyplot.plot(numpy.abs(restore_time2),'k--',label='L1TVOLS') im4,=pyplot.plot(numpy.abs(restore_time),'r:',label='conjugate_gradient_method') pyplot.legend([im1, im3,im4]) pyplot.show()
def performUndersampling(fullImgVol, om=None, dcf=None, interpolationSize4NUFFT=6, complex2real=np.abs, ommatpath=None): #Either send om and dcf, or ommatpath. #path will only be used in om not supplied if om is None: temp_mat = sio.loadmat(ommatpath) om = temp_mat['om'] dcf = temp_mat['dcf'].squeeze() imageSize = fullImgVol.shape[0] baseresolution = imageSize * 2 NufftObj = NUFFT_cpu() Nd = (baseresolution, baseresolution) # image size Kd = (baseresolution * 2, baseresolution * 2) # k-space size Jd = (interpolationSize4NUFFT, interpolationSize4NUFFT ) # interpolation size NufftObj.plan(om, Nd, Kd, Jd) underImgVol = np.zeros(fullImgVol.shape, dtype=fullImgVol.dtype) for i in range(fullImgVol.shape[-1]): oversam_fully = np.zeros((baseresolution, baseresolution), dtype=fullImgVol.dtype) oversam_fully[imageSize // 2:imageSize + imageSize // 2, imageSize // 2:imageSize + imageSize // 2] = fullImgVol[..., i] y = NufftObj.forward(oversam_fully) y = np.multiply(dcf, y) oversam_under = NufftObj.adjoint(y) underImgVol[..., i] = complex2real( oversam_under[imageSize // 2:imageSize + imageSize // 2, imageSize // 2:imageSize + imageSize // 2]) return underImgVol
def non_uniform_fft(pos_stack,pos_wavefun,solver,interp_size): assert len(pos_wavefun.shape) == 2 NufftObj = NUFFT_cpu() om = pos_stack Nd = (len(pos_stack[0]),len(pos_stack[1])) Kd = Nd Jd = (interp_size,interp_size) NufftObj.plan(om,Nd,Kd,Jd) y = NufftObj.forward(pos_wavefun) mom_wavefun_1 = NufftObj.solve(y,solver=solver ) #mom_wavefun_2 = NufftObj.adjoint(y) return mom_wavefun_1 #, mom_wavefun_2
Nd = (128, 128, 128) # time grid, tuple Kd = (256, 256, 256) # frequency grid, tuple Jd = (6, 6, 6) # interpolator # om= numpy.load(DATA_PATH+'om3D.npz')['arr_0'] # om = numpy.random.randn(10000,3)*2 # for m in (1e+5, 2e+5, 3e+5, 4e+5, 5e+5, 6e+5, 7e+5, 8e+5, 9e+5, 1e+6, 2e+6, 3e+6, 4e+6, 5e+6, # 6e+6, 7e+6, 8e+6, 9e+6, 10e+6, 11e+6, 12e+6, 13e+6, 14e+6, 15e+6, # 16e+6, 17e+6, 18e+6, 19e+6, 20e+6, 30e+6, 40e+6, 50e+6, 60e+6, 70e+6, 80e+6, 90e+6, 100e+6): for m in (1e+4, ): om = numpy.random.randn(int(m), 3) * 2 # om = numpy.load('/home/sram/UCL/DATA/G/3D_Angio/greg_3D.npz')['arr_0'][0:int(m), :] print(om.shape) from pynufft import NUFFT_cpu, NUFFT_hsa #, NUFFT_memsave # from pynufft import NUFFT_memsave NufftObj_cpu = NUFFT_cpu() # NufftObj_hsa = NUFFT_hsa() NufftObj_hsa = NUFFT_hsa('cuda', 0, 0) import time t0 = time.time() NufftObj_cpu.plan(om, Nd, Kd, Jd) t1 = time.time() # NufftObj_hsa.plan(om, Nd, Kd, Jd) t12 = time.time() RADIX = 1 NufftObj_hsa.plan(om, Nd, Kd, Jd, radix=RADIX) t2 = time.time() # proc = 0 # GPU # proc = 1 # gpu # NufftObj_hsa.offload(API = 'ocl', platform_number = proc, device_number = 0)
import numpy import matplotlib.pyplot as pyplot from pynufft import NUFFT_cpu, NUFFT_hsa om = numpy.random.randn(1512, 1) Nd = (256, ) # time grid, tuple Kd = (512, ) # frequency grid, tuple Jd = (7, ) # interpolator NufftObj = NUFFT_cpu() NufftObj.plan(om, Nd, Kd, Jd) time_data = numpy.zeros(256, ) time_data[64:192] = 1.0 pyplot.plot(time_data) pyplot.ylim(-1, 2) pyplot.show() nufft_freq_data = NufftObj.forward(time_data) pyplot.plot(om, nufft_freq_data.real, '.', label='real') pyplot.plot(om, nufft_freq_data.imag, 'r.', label='imag') pyplot.legend() pyplot.show() restore_time = NufftObj.solve(nufft_freq_data, 'cg', maxiter=30) restore_time1 = NufftObj.solve(nufft_freq_data, 'L1TVLAD', maxiter=30, rho=1) restore_time2 = NufftObj.solve(nufft_freq_data, 'L1TVOLS', maxiter=30, rho=1)
spoke_y = spoke_range * np.sin(radian) om[512 * index:512 * (index + 1), 0] = spoke_x om[512 * index:512 * (index + 1), 1] = spoke_y #plt.plot(om[:,0], om[:,1],'.') #plt.title("Radial Kspace Trajectory") #plt.show() numProjections = kspace.shape[1] numReadouts = kspace.shape[0] print('Number of Projections = ', numProjections) print('Number of Readout Values = ', numReadouts) myNufft = NUFFT_cpu() myNufft.plan(om=om, Nd=(256, 256), Kd=(numReadouts, numReadouts), Jd=(2, 2)) y = kspace.flatten(order='C') image = myNufft.adjoint(y) #y = myNufft.forward(image) #ipdb.set_trace() plt.subplot(2, 2, 1) image0 = myNufft.solve(y, solver='cg', maxiter=50) #img = image0.real/image0.real.max() plt.title('Restored image (cg)') plt.imshow(image0.real, cmap=matplotlib.cm.gray,
# NufftObj.offload('cuda') # for GPU computation NufftObj.offload('ocl') # for multi-CPU computation time_4 = time.clock() dtype = np.complex64 time_5 = time.clock() print("send image to device") NufftObj.x_Nd = NufftObj.thr.to_device(image.astype(dtype)) print("copy image to gx") time_6 = time.clock() gx = NufftObj.thr.copy_array(NufftObj.x_Nd) time_7 = time.clock() print('total:', time_7 - time_1, '/Decl obj: ', time_2 - time_1, '/plan: ', \ time_3 - time_2, '/offload: ', time_4 - time_3, '/to_device: ', time_6 - time_5, '\copy_array: ', time_7 - time_6) else: NufftObj = NUFFT_cpu() # mem_usage = memory_usage((NufftObj.plan,(om, Nd, Kd, Jd))) # print(mem_usage) NufftObj.plan(om, Nd, Kd, Jd) # Compute F_hat if gpu == True: time_comp = time.clock() gy = NufftObj.forward(gx) # print(type(gy)) # gy = np.array(gy) # print(type(gy)) # print(gy) # exit(0) y_pynufft = gy.get() time_end = time.clock()
import numpy import pynufft.NUFFT_cpu as NUFFT_cpu NufftObj = NUFFT_cpu() om = numpy.random.randn(1512, 1) om = numpy.random.randn(1512, 1) # om is an M x 1 ndarray: locations of M points. *om* is normalized between [-pi, pi] # Here M = 1512 Nd = (256, ) Kd = (512, ) Jd = (6, ) NufftObj.plan(om, Nd, Kd, Jd) # Now test 1D case import matplotlib.pyplot as pyplot # Now build a box function time_data = numpy.zeros(256, ) time_data[96:128 + 32] = 1.0 # Now display the function pyplot.plot(time_data) pyplot.ylim(-1, 2) pyplot.show() # Forward NUFFT y = NufftObj.forward(time_data) # Display the nonuniform spectrum
results.append(result) # Now enter the second process # This is the standard multiprocessing Pool D = atomic_NUFFT(om2, Nd, Kd, Jd, 'cuda', 0) # Non-obstructive result = pool.apply_async(D.run, args = (x, 1)) results.append(result) # closing the pool pool.close() pool.join() # results are appended # Now print the outputs result1 = results[0].get() result2 = results[1].get() # check CPU results NUFFT_cpu1 = NUFFT_cpu() NUFFT_cpu1.plan(om1, Nd, Kd, Jd) y1 = NUFFT_cpu1.forward(x) print('norm = ', numpy.linalg.norm(y1 - result1) / numpy.linalg.norm(y1)) NUFFT_cpu2 = NUFFT_cpu() NUFFT_cpu2.plan(om2, Nd, Kd, Jd) y2 = NUFFT_cpu2.forward(x) print('norm = ', numpy.linalg.norm(y2 - result2) / numpy.linalg.norm(y2))
def test_init(): # cm = matplotlib.cm.gray # load example image import pkg_resources DATA_PATH = pkg_resources.resource_filename('pynufft', 'src/data/') # PHANTOM_FILE = pkg_resources.resource_filename('pynufft', 'data/phantom_256_256.txt') import numpy # import matplotlib.pyplot import scipy image = scipy.misc.ascent()[::2,::2] image=image.astype(numpy.float)/numpy.max(image[...]) Nd = (256, 256) # image space size Kd = (512, 512) # k-space size Jd = (6,6) # interpolation size # load k-space points om = numpy.load(DATA_PATH+'om2D.npz')['arr_0'] nfft = NUFFT_cpu() # CPU nfft.plan(om, Nd, Kd, Jd) try: NufftObj = NUFFT_hsa('cuda',0,0) except: NufftObj = NUFFT_hsa('ocl',0,0) # NufftObj2 = NUFFT_hsa('cuda',0,0) NufftObj.debug = 1 NufftObj.plan(om, Nd, Kd, Jd, radix=2) # NufftObj2.plan(om, Nd, Kd, Jd) # NufftObj.offload(API = 'cuda', platform_number = 0, device_number = 0) # NufftObj2.offload(API = 'cuda', platform_number = 0, device_number = 0) # NufftObj2.offload('cuda') # NufftObj.offload(API = 'cuda', platform_number = 0, device_number = 0) # print('api=', NufftObj.thr.api_name()) # NufftObj.offload(API = 'ocl', platform_number = 0, device_number = 0) y = nfft.k2y(nfft.xx2k(nfft.x2xx(image))) NufftObj.x_Nd = NufftObj.thr.to_device( image.astype(dtype)) gx = NufftObj.thr.copy_array(NufftObj.x_Nd) print('x close? = ', numpy.allclose(image, gx.get() , atol=1e-4)) gxx = NufftObj.x2xx(gx) print('xx close? = ', numpy.allclose(nfft.x2xx(image), gxx.get() , atol=1e-4)) gk = NufftObj.xx2k(gxx) k = nfft.xx2k(nfft.x2xx(image)) print('k close? = ', numpy.allclose(nfft.xx2k(nfft.x2xx(image)), gk.get(), atol=1e-3*numpy.linalg.norm(k))) gy = NufftObj.k2y(gk) k2 = NufftObj.y2k(gy) print('y close? = ', numpy.allclose(y, gy.get() , atol=1e-3*numpy.linalg.norm(y)), numpy.linalg.norm((y - gy.get())/numpy.linalg.norm(y))) y2 = y print('k2 close? = ', numpy.allclose(nfft.y2k(y2), k2.get(), atol=1e-3*numpy.linalg.norm(nfft.y2k(y2)) ), numpy.linalg.norm(( nfft.y2k(y2)- k2.get())/numpy.linalg.norm(nfft.y2k(y2)))) gxx2 = NufftObj.k2xx(k2) # print('xx close? = ', numpy.allclose(nfft.k2xx(nfft.y2k(y2)), NufftObj.xx_Nd.get(queue=NufftObj.queue, async=False) , atol=0.1)) gx2 = NufftObj.xx2x(gxx2) print('x close? = ', numpy.allclose(nfft.adjoint(y2), gx2.get() , atol=1e-3*numpy.linalg.norm(nfft.adjoint(y2)))) image3 = gx2.get() import time t0 = time.time() # k = nfft.xx2k(nfft.x2xx(image)) for pp in range(0,50): # y = nfft.k2y(nfft.xx2k(nfft.x2xx(image))) y = nfft.forward(image) # y = nfft.k2y(k) # k = nfft.y2k(y) # x = nfft.adjoint(y) # y = nfft.forward(image) # y2 = NufftObj.y.get( NufftObj.queue, async=False) t_cpu = (time.time() - t0)/50.0 print(t_cpu) # del nfft gy2=NufftObj.forward(gx) # gk = NufftObj.xx2k(NufftObj.x2xx(gx)) t0= time.time() for pp in range(0,20): # pass gy2 = NufftObj.forward(gx) # gy2 = NufftObj.k2y(gk) # gx2 = NufftObj.adjoint(gy2) # gk2 = NufftObj.y2k(gy2) # del gy2 # c = gx2.get() # gy=NufftObj.forward(gx) NufftObj.thr.synchronize() t_cl = (time.time() - t0)/20 print(t_cl) print('gy close? = ', numpy.allclose(y, gy.get(), atol=numpy.linalg.norm(y)*1e-3)) print("acceleration=", t_cpu/t_cl) maxiter =100 import time t0= time.time() # x2 = nfft.solve(y2, 'cg',maxiter=maxiter) x2 = nfft.solve(y2, 'L1TVOLS',maxiter=maxiter, rho = 2) t1 = time.time()-t0 # gy=NufftObj.thr.copy_array(NufftObj.thr.to_device(y2)) t0= time.time() # x = NufftObj.solve(gy,'cg', maxiter=maxiter) x = NufftObj.solve(gy,'L1TVOLS', maxiter=maxiter, rho=2) t2 = time.time() - t0 print(t1, t2) print('acceleration=', t1/t2 ) # k = x.get() # x = nfft.k2xx(k)/nfft.st['sn'] # return try: import matplotlib.pyplot matplotlib.pyplot.subplot(1, 2, 1) matplotlib.pyplot.imshow( x.get().real, cmap= matplotlib.cm.gray, vmin = 0, vmax = 1) matplotlib.pyplot.title("HSA reconstruction") matplotlib.pyplot.subplot(1, 2,2) matplotlib.pyplot.imshow(x2.real, cmap= matplotlib.cm.gray) matplotlib.pyplot.title("CPU reconstruction") matplotlib.pyplot.show(block = False) matplotlib.pyplot.pause(3) matplotlib.pyplot.close() # del NufftObj.thr # del NufftObj except: print("no graphics")
def test_cuda(): import numpy import matplotlib.pyplot # load example image import pkg_resources ## Define the source of data DATA_PATH = pkg_resources.resource_filename('pynufft', 'src/data/') # PHANTOM_FILE = pkg_resources.resource_filename('pynufft', 'data/phantom_256_256.txt') import scipy image = scipy.misc.ascent() image = scipy.misc.imresize(image, (256, 256)) image = image.astype(numpy.float) / numpy.max(image[...]) Nd = (256, 256) # image space size Kd = (512, 512) # k-space size Jd = (6, 6) # interpolation size # load k-space points as M * 2 array om = numpy.load(DATA_PATH + 'om2D.npz')['arr_0'] # Show the shape of om print('the shape of om = ', om.shape) # initiating NUFFT_cpu object nfft = NUFFT_cpu() # CPU NUFFT class # Plan the nfft object nfft.plan(om, Nd, Kd, Jd) # initiating NUFFT_hsa object NufftObj = NUFFT_hsa('cuda', 0, 0) # Plan the NufftObj (similar to NUFFT_cpu) NufftObj.plan(om, Nd, Kd, Jd) import time t0 = time.time() for pp in range(0, 10): y = nfft.forward(image) t_cpu = (time.time() - t0) / 10.0 ## Moving image to gpu ## gx is an gpu array, dtype = complex64 gx = NufftObj.to_device(image) t0 = time.time() for pp in range(0, 100): gy = NufftObj.forward(gx) t_cu = (time.time() - t0) / 100 print('t_cpu = ', t_cpu) print('t_cuda =, ', t_cu) print('gy close? = ', numpy.allclose(y, gy.get(), atol=numpy.linalg.norm(y) * 1e-3)) print("acceleration=", t_cpu / t_cu) maxiter = 100 import time t0 = time.time() x_cpu_cg = nfft.solve(y, 'cg', maxiter=maxiter) # x2 = nfft.solve(y2, 'L1TVLAD',maxiter=maxiter, rho = 2) t1 = time.time() - t0 # gy=NufftObj.thr.copy_array(NufftObj.thr.to_device(y2)) t0 = time.time() x_cuda_cg = NufftObj.solve(gy, 'cg', maxiter=maxiter) # x = NufftObj.solve(gy,'L1TVLAD', maxiter=maxiter, rho=2) t2 = time.time() - t0 print(t1, t2) print('acceleration of cg=', t1 / t2) t0 = time.time() x_cpu_TV = nfft.solve(y, 'L1TVOLS', maxiter=maxiter, rho=2) t1 = time.time() - t0 t0 = time.time() x_cuda_TV = NufftObj.solve(gy, 'L1TVOLS', maxiter=maxiter, rho=2) t2 = time.time() - t0 print(t1, t2) print('acceleration of TV=', t1 / t2) matplotlib.pyplot.subplot(2, 2, 1) matplotlib.pyplot.imshow(x_cpu_cg.real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('CG_cpu') matplotlib.pyplot.subplot(2, 2, 2) matplotlib.pyplot.imshow(x_cuda_cg.get().real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('CG_cuda') matplotlib.pyplot.subplot(2, 2, 3) matplotlib.pyplot.imshow(x_cpu_TV.real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('TV_cpu') matplotlib.pyplot.subplot(2, 2, 4) matplotlib.pyplot.imshow(x_cuda_TV.get().real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('TV_cuda') matplotlib.pyplot.show() NufftObj.release() del NufftObj
def test_2D(): import pkg_resources DATA_PATH = pkg_resources.resource_filename('pynufft', 'src/data/') # PHANTOM_FILE = pkg_resources.resource_filename('pynufft', 'data/phantom_256_256.txt') import numpy import matplotlib.pyplot from pynufft import NUFFT_cpu # load example image # image = numpy.loadtxt(DATA_PATH +'phantom_256_256.txt') image = scipy.misc.ascent()[::2, ::2] image = image.astype(numpy.float) / numpy.max(image[...]) #numpy.save('phantom_256_256',image) matplotlib.pyplot.imshow(image, cmap=matplotlib.cm.gray) matplotlib.pyplot.show() print('loading image...') Nd = (256, 256) # image size print('setting image dimension Nd...', Nd) Kd = (512, 512) # k-space size print('setting spectrum dimension Kd...', Kd) Jd = (6, 6) # interpolation size print('setting interpolation size Jd...', Jd) # load k-space points # om = numpy.loadtxt(DATA_PATH+'om.txt') om = numpy.load(DATA_PATH + 'om2D.npz')['arr_0'] print('setting non-uniform coordinates...') matplotlib.pyplot.plot(om[::10, 0], om[::10, 1], 'o') matplotlib.pyplot.title('non-uniform coordinates') matplotlib.pyplot.xlabel('axis 0') matplotlib.pyplot.ylabel('axis 1') matplotlib.pyplot.show() NufftObj = NUFFT_cpu() NufftObj.plan(om, Nd, Kd, Jd) y = NufftObj.forward(image) print('setting non-uniform data') print('y is an (M,) list', type(y), y.shape) # kspectrum = NufftObj.xx2k( NufftObj.solve(y,solver='bicgstab',maxiter = 100)) image_restore = NufftObj.solve(y, solver='cg', maxiter=10) shifted_kspectrum = numpy.fft.fftshift( numpy.fft.fftn(numpy.fft.fftshift(image_restore))) print('getting the k-space spectrum, shape =', shifted_kspectrum.shape) print('Showing the shifted k-space spectrum') matplotlib.pyplot.imshow(shifted_kspectrum.real, cmap=matplotlib.cm.gray, norm=matplotlib.colors.Normalize(vmin=-100, vmax=100)) matplotlib.pyplot.title('shifted k-space spectrum') matplotlib.pyplot.show() image4 = NufftObj.solve(y, 'L1TVOLS', maxiter=100, rho=1) image2 = NufftObj.solve(y, 'dc', maxiter=25) image3 = NufftObj.solve(y, 'cg', maxiter=25) matplotlib.pyplot.subplot(1, 3, 1) matplotlib.pyplot.imshow(image2.real, cmap=matplotlib.cm.gray, norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1)) matplotlib.pyplot.title('dc') matplotlib.pyplot.subplot(1, 3, 2) matplotlib.pyplot.imshow(image3.real, cmap=matplotlib.cm.gray, norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1)) matplotlib.pyplot.title('cg') matplotlib.pyplot.subplot(1, 3, 3) matplotlib.pyplot.imshow(image4.real, cmap=matplotlib.cm.gray, norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1)) matplotlib.pyplot.title('L1TVOLS') matplotlib.pyplot.show() # matplotlib.pyplot.imshow(image2.real, cmap=matplotlib.cm.gray, norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1)) # matplotlib.pyplot.show() maxiter = 25 counter = 1 for solver in ('dc', 'bicg', 'bicgstab', 'cg', 'gmres', 'lgmres', 'lsqr'): print(counter, solver) if 'lsqr' == solver: image2 = NufftObj.solve(y, solver, iter_lim=maxiter) else: image2 = NufftObj.solve(y, solver, maxiter=maxiter) # image2 = NufftObj.solve(y, solver='bicgstab',maxiter=30) matplotlib.pyplot.subplot(2, 4, counter) matplotlib.pyplot.imshow(image2.real, cmap=matplotlib.cm.gray, norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1)) matplotlib.pyplot.title(solver) # print(counter, solver) counter += 1 matplotlib.pyplot.show()
for x in range (-N, N): for y in range(-N, N): img[x-N, y-N] = img[x-N,y-N] + X * cmath.exp(-2j*math.pi * (u*x + v*y)) u0 = 0.05 v0 = 0.013 u1 = 0.0018 v1 = 0.046 img = np.zeros([32,32], dtype=np.complex128) expectedIFT(img, 3, u0, v0) expectedIFT(img, 2.5, u1, v1) plt.imshow(np.real(img)) print(np.max(np.real(img))) NufftObj = NUFFT_cpu() Nd = (32, 32) # image size Kd = (64, 64) # k-space size Jd = (2, 2) # interpolation size om = [ [u0, v0], [u1,v1]] NufftObj.plan(np.asarray(om), Nd, Kd, Jd) img2 = NufftObj.adjoint([3, 2.5]) plt.imshow(np.real(img2)) print(np.max(np.real(img2)))
import numpy from pynufft import NUFFT_cpu import scipy.misc import matplotlib Nd = (256, 256) Kd = (512, 512) Jd = (6, 6) om = numpy.random.randn(65536, 2) x = scipy.misc.imresize(scipy.misc.ascent(), Nd) om1 = om[om[:, 0] > 0, :] om2 = om[om[:, 0] <= 0, :] NufftObj1 = NUFFT_cpu() NufftObj1.plan(om1, Nd, Kd, Jd) NufftObj2 = NUFFT_cpu() NufftObj2.plan(om2, Nd, Kd, Jd) y1 = NufftObj1.forward(x) y2 = NufftObj2.forward(x)
image = numpy.load(DATA_PATH + 'phantom_3D_128_128_128.npz')['arr_0'][0::2, 0::2, 0::2] print(special_license) pyplot.imshow(numpy.abs(image[:, :, 32]), label='original signal', cmap=gray) pyplot.show() Nd = (64, 64, 64) # time grid, tuple Kd = (64, 64, 64) # frequency grid, tuple Jd = (1, 1, 1) # interpolator # om= numpy.load(DATA_PATH+'om3D.npz')['arr_0'] om = numpy.random.randn(151200, 3) * 2 print(om.shape) from pynufft import NUFFT_cpu, NUFFT_hsa NufftObj = NUFFT_cpu() NufftObj.plan(om, Nd, Kd, Jd) kspace = NufftObj.forward(image) restore_image = NufftObj.solve(kspace, 'cg', maxiter=500) restore_image1 = NufftObj.solve(kspace, 'L1TVLAD', maxiter=500, rho=0.1) # restore_image2 = NufftObj.solve(kspace, 'L1TVOLS', maxiter=500, rho=0.1) pyplot.subplot(2, 2, 1) pyplot.imshow(numpy.real(image[:, :, 32]), label='original signal', cmap=gray) pyplot.title('original') pyplot.subplot(2, 2, 2) pyplot.imshow(numpy.real(restore_image1[:, :, 32]), label='L1TVLAD', cmap=gray)
def test_opencl_multicoils(): import numpy import matplotlib.pyplot # load example image import pkg_resources ## Define the source of data DATA_PATH = pkg_resources.resource_filename('pynufft', 'src/data/') # PHANTOM_FILE = pkg_resources.resource_filename('pynufft', 'data/phantom_256_256.txt') import scipy image = scipy.misc.ascent()[::2, ::2] image = image.astype(numpy.float) / numpy.max(image[...]) Nd = (256, 256) # image space size Kd = (512, 512) # k-space size Jd = (6, 6) # interpolation size # load k-space points as M * 2 array om = numpy.load(DATA_PATH + 'om2D.npz')['arr_0'] # Show the shape of om print('the shape of om = ', om.shape) batch = 8 # initiating NUFFT_cpu object nfft = NUFFT_cpu() # CPU NUFFT class # Plan the nfft object nfft.plan(om, Nd, Kd, Jd, batch=batch) # initiating NUFFT_hsa object try: NufftObj = NUFFT_hsa('cuda', 0, 0) except: try: NufftObj = NUFFT_hsa('ocl', 1, 0) except: NufftObj = NUFFT_hsa('ocl', 0, 0) # Plan the NufftObj (similar to NUFFT_cpu) NufftObj.plan(om, Nd, Kd, Jd, batch=batch, radix=2) coil_sense = numpy.ones(Nd + (batch, ), dtype=numpy.complex64) for cc in range(0, batch, 2): coil_sense[int(256 / batch) * cc:int(256 / batch) * (cc + 1), :, cc].real *= 0.1 coil_sense[:, int(256 / batch) * cc:int(256 / batch) * (cc + 1), cc].imag *= -0.1 NufftObj.set_sense(coil_sense) nfft.set_sense(coil_sense) y = nfft.forward_one2many(image) import time t0 = time.time() for pp in range(0, 2): xx = nfft.adjoint_many2one(y) t_cpu = (time.time() - t0) / 2 ## Moving image to gpu ## gx is an gpu array, dtype = complex64 gx = NufftObj.to_device(image) gy = NufftObj.forward_one2many(gx) t0 = time.time() for pp in range(0, 10): gxx = NufftObj.adjoint_many2one(gy) t_cu = (time.time() - t0) / 10 print(y.shape, gy.get().shape) print('t_cpu = ', t_cpu) print('t_cuda =, ', t_cu) print('gy close? = ', numpy.allclose(y, gy.get(), atol=numpy.linalg.norm(y) * 1e-6)) print('gy error = ', numpy.linalg.norm(y - gy.get()) / numpy.linalg.norm(y)) print('gxx close? = ', numpy.allclose(xx, gxx.get(), atol=numpy.linalg.norm(xx) * 1e-6)) print('gxx error = ', numpy.linalg.norm(xx - gxx.get()) / numpy.linalg.norm(xx)) # for bb in range(0, batch): matplotlib.pyplot.subplot(1, 2, 1) matplotlib.pyplot.imshow(xx[...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('Adjoint_cpu_coil') matplotlib.pyplot.subplot(1, 2, 2) matplotlib.pyplot.imshow(gxx.get()[...].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('Adjoint_hsa_coil') # matplotlib.pyplot.subplot(2, 2, 3) # matplotlib.pyplot.imshow( x_cpu_TV.real, cmap= matplotlib.cm.gray) # matplotlib.pyplot.title('TV_cpu')# x_cuda_TV = NufftObj.solve(gy,'L1TVOLS', maxiter=maxiter, rho=2) # matplotlib.pyplot.subplot(2, 2, 4) # matplotlib.pyplot.imshow(x_cuda_TV.get().real, cmap= matplotlib.cm.gray) # matplotlib.pyplot.title('TV_cuda') matplotlib.pyplot.show(block=False) matplotlib.pyplot.pause(1) matplotlib.pyplot.close() print("acceleration=", t_cpu / t_cu) maxiter = 100 import time t0 = time.time() x_cpu_cg = nfft.solve(y, 'cg', maxiter=maxiter) # x2 = nfft.solve(y2, 'L1TVLAD',maxiter=maxiter, rho = 2) t1 = time.time() - t0 # gy=NufftObj.thr.copy_array(NufftObj.thr.to_device(y2)) t0 = time.time() x_cuda_cg = NufftObj.solve(gy, 'cg', maxiter=maxiter) # x = NufftObj.solve(gy,'L1TVLAD', maxiter=maxiter, rho=2) print('shape of cg = ', x_cuda_cg.get().shape, x_cpu_cg.shape) t2 = time.time() - t0 print(t1, t2) print('acceleration of cg=', t1 / t2) t0 = time.time() # x_cpu_TV = nfft.solve(y, 'L1TVOLS',maxiter=maxiter, rho = 2) t1 = time.time() - t0 t0 = time.time() # x_cuda_TV = NufftObj.solve(gy,'L1TVOLS', maxiter=maxiter, rho=2) t2 = time.time() - t0 print(t1, t2) # print('acceleration of TV=', t1/t2 ) # try: for bb in range(0, batch): matplotlib.pyplot.subplot(2, batch, 1 + bb) matplotlib.pyplot.imshow(x_cpu_cg[..., bb].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('CG_cpu_coil_' + str(bb)) matplotlib.pyplot.subplot(2, batch, 1 + batch + bb) matplotlib.pyplot.imshow(x_cuda_cg.get()[..., bb].real, cmap=matplotlib.cm.gray) matplotlib.pyplot.title('CG_hsa_coil_' + str(bb)) # matplotlib.pyplot.subplot(2, 2, 3) # matplotlib.pyplot.imshow( x_cpu_TV.real, cmap= matplotlib.cm.gray) # matplotlib.pyplot.title('TV_cpu')# x_cuda_TV = NufftObj.solve(gy,'L1TVOLS', maxiter=maxiter, rho=2) # matplotlib.pyplot.subplot(2, 2, 4) # matplotlib.pyplot.imshow(x_cuda_TV.get().real, cmap= matplotlib.cm.gray) # matplotlib.pyplot.title('TV_cuda') matplotlib.pyplot.show() # except: # print('no matplotlib') NufftObj.release() del NufftObj
Nc = 8 filename = '/home/sram/Cambridge_2012/WORD_PPTS/multicoil_NUFFT/simulation/pMRI/coils_12.mat' K0 = scipy.io.loadmat(filename)['K0'][:, :, 0:Nc] Kn = scipy.io.loadmat(filename)['Kn'][:, :, 0:Nc] M0 = scipy.io.loadmat(filename)['M0'] Nd = M0.shape multi_image = numpy.fft.ifftn(numpy.fft.fftshift(K0, axes=(0, 1)), axes=(0, 1)) multi_image_noisy = numpy.fft.ifftn(numpy.fft.fftshift(Kn, axes=(0, 1)), axes=(0, 1)) # H, mu0, mu = Nd_sense(multi_image_noisy, maxiter = 10, sigma = 2) om2 = fake_Cartesian(Nd) from pynufft import NUFFT_cpu, NUFFT_excalibur NufftObj = NUFFT_cpu() NufftObj_coil = NUFFT_excalibur() NufftObj.plan(om2, Nd, (512, 512), (6, 6)) # import multicoil_solver fake_coil = create_fake_coils(Nd[0], Nc) H = numpy.ones(Nd + (Nc, ), dtype=numpy.complex) for pp in range(0, Nc): H[..., pp] = fake_coil[pp] H2 = H * numpy.reshape(M0, (256, 256, 1)) H = Nd_sense(H2, maxiter=20, sigma=100) H = H - numpy.min(abs(H.ravel())) # matplotlib.pyplot.imshow(H[:,:,0].real)
import numpy import pynufft.NUFFT_cpu as NUFFT_cpu NufftObj = NUFFT_cpu() # load the data folder import pkg_resources # find the relative path of data folder DATA_PATH = pkg_resources.resource_filename('pynufft', 'data/') # now load the om locations om = numpy.load(DATA_PATH+'om2D.npz')['arr_0'] # om is an Mx2 numpy.ndarray print(om) # display om import matplotlib.pyplot as pyplot pyplot.plot(om[:,0], om[:,1]) pyplot.title('2D trajectory of M points') pyplot.xlabel('X') pyplot.ylabel('Y') pyplot.show() Nd = (256,256) # image dimension Kd = (512,512) # k-spectrum dimension Jd = (6,6) # interpolator size NufftObj.plan(om, Nd, Kd, Jd) # load image from scipy.misc.face()
from pynufft import NUFFT_cpu # load k-space points import pkg_resources DATA_PATH = pkg_resources.resource_filename('pynufft', './src/data/') om = numpy.load(DATA_PATH + 'om2D.npz')['arr_0'] print(om) print('setting non-uniform coordinates...') matplotlib.pyplot.plot(om[::10, 0], om[::10, 1], 'o') matplotlib.pyplot.title('non-uniform coordinates') matplotlib.pyplot.xlabel('axis 0') matplotlib.pyplot.ylabel('axis 1') matplotlib.pyplot.show() NufftObj = NUFFT_cpu() Nd = (256, 256) # image size print('setting image dimension Nd...', Nd) Kd = (512, 512) # k-space size print('setting spectrum dimension Kd...', Kd) Jd = (6, 6) # interpolation size print('setting interpolation size Jd...', Jd) NufftObj.plan(om, Nd, Kd, Jd) image = scipy.misc.ascent() image = scipy.misc.imresize(image, (256, 256)) image = image / numpy.max(image[...]) print('loading image...')
def test_mCoil(sense_number): image = scipy.misc.ascent() Nd = (64, 64, 64) # time grid, tuple # image = scipy.misc.imresize(image, Nd)*(1.0 + 0.0j) image = numpy.random.randn(64, 64, 64) * (1.0 + 0.0j) Kd = (128, 128, 128) # frequency grid, tuple Jd = (6, 6, 6) # interpolator # om= numpy.load(DATA_PATH+'om3D.npz')['arr_0'] # om = numpy.random.randn(10000,3)*2 # om = numpy.load('/home/sram/Cambridge_2012/DATA_MATLAB/Ciuciu/Trajectories_and_data_sparkling_radial/radial/')['arr_0'] # om = scipy.io.loadmat('/home/sram/Cambridge_2012/DATA_MATLAB/Ciuciu/Trajectories_and_data_sparkling_radial/sparkling/samples_sparkling_x8_64x3072.mat')['samples_sparkling'] # om = scipy.io.loadmat('/home/sram/Cambridge_2012/DATA_MATLAB/Ciuciu/Trajectories_and_data_sparkling_radial/radial/samples_radial_x8_64x3072.mat')['samples_radial'] # om = om/numpy.max(om.real.ravel()) * numpy.pi om = numpy.random.randn(int((128**3) / 32), 3) * 1.5 print('om.shape, ', om.shape) # sense_number = 16 # sense = numpy.ones(Nd + (sense_number,), dtype=numpy.complex64) m = om.shape[0] print(om.shape) from pynufft import NUFFT_cpu, NUFFT_hsa, NUFFT_hsa_legacy # from pynufft import NUFFT_memsave NufftObj_cpu = NUFFT_cpu() api = 'ocl' proc = 0 NufftObj_radix1 = NUFFT_hsa(api, proc, 0) NufftObj_radix2 = NUFFT_hsa(api, proc, 0) NufftObj_radix3 = NUFFT_hsa(api, proc, 0) import time # t0=time.time() NufftObj_cpu.plan(om, Nd, Kd, Jd, batch=sense_number) # t1 = time.time() # t12 = time.time() # t2 = time.time() # tc = time.time() # proc = 0 # GPU # proc = 1 # gpu # NufftObj_radix1.offload(API = 'ocl', platform_number = proc, device_number = 0) # t22 = time.time() # NufftObj_radix2.offload(API = 'ocl', platform_number = proc, device_number = 0) # NufftObj_radix2.offload(API = 'cuda', platform_number = 0, device_number = 0) # t3 = time.time() # NufftObj_radix3.offload(API = 'ocl', platform_number = proc, device_number = 0) # tp = time.time() # if proc is 0: # print('CPU') # else: # print('GPU') # print('Number of samples = ', om.shape[0]) # print('planning time of CPU = ', t1 - t0) # print('planning time of HSA = ', t12 - t1) # print('planning time of MEM = ', t2 - t12) # print('planning time of mCoil = ', tc - t2) # print('loading time of HSA = ', t22 - tc) # print('loading time of MEM = ', t3 - t22) # print('loading time of mCoil = ', tp - t3) maxiter = 1 tcpu_forward, tcpu_adjoint, ycpu, xcpu = benchmark(NufftObj_cpu, image, maxiter) print('CPU', int(m), tcpu_forward, tcpu_adjoint) maxiter = 20 NufftObj_radix1.plan(om, Nd, Kd, Jd, batch=sense_number, radix=1) gx_hsa = NufftObj_radix1.thr.to_device(image.astype(numpy.complex64)) # gx_hsa = NufftObj_radix1.s2x(gx_hsa0) thsa_forward, thsa_adjoint, yradix1, xradix1 = benchmark( NufftObj_radix1, gx_hsa, maxiter) print( 'radix-1', int(m), thsa_forward, thsa_adjoint, ) #numpy.linalg.norm(yradix1.get() - ycpu)/ numpy.linalg.norm( ycpu)) # for ss in range(0, sense_number): erry = numpy.linalg.norm(yradix1.get() - ycpu) / numpy.linalg.norm(ycpu) errx = numpy.linalg.norm(xradix1.get() - xcpu) / numpy.linalg.norm(xcpu) if erry > 1e-6 or errx > 1e-6: print("degraded accuracy:", sense_number, erry, errx) else: print("Pass test for coil: ", sense_number, erry, errx) print("Pass test for coil: ", sense_number, erry, errx) NufftObj_radix1.release() NufftObj_radix2.plan(om, Nd, Kd, Jd, batch=sense_number, radix=2) gx_memsave = NufftObj_radix2.thr.to_device(image.astype(numpy.complex64)) # gx_memsave = NufftObj_radix2.s2x(gx_memsave0) tmem_forward, tmem_adjoint, yradix2, xradix2 = benchmark( NufftObj_radix2, gx_memsave, maxiter) #, sense_number) print('radix-2', int(m), tmem_forward, tmem_adjoint) # for ss in range(0, sense_number): erry = numpy.linalg.norm(yradix2.get() - ycpu) / numpy.linalg.norm(ycpu) errx = numpy.linalg.norm(xradix2.get() - xcpu) / numpy.linalg.norm(xcpu) if erry > 1e-6 or errx > 1e-6: print("degraded accuracy:", sense_number, erry, errx) else: print("Pass test for coil: ", sense_number, erry, errx) print("Pass test for coil: ", sense_number, erry, errx) NufftObj_radix2.release() NufftObj_radix3.plan(om, Nd, Kd, Jd, batch=sense_number, radix=3) gx_mCoil = NufftObj_radix3.thr.to_device(image.astype(numpy.complex64)) # gx_mCoil = NufftObj_radix3.s2x(gx_mCoil0) tmCoil_forward, tmCoil_adjoint, yradix3, xradix3 = benchmark( NufftObj_radix3, gx_mCoil, maxiter) print('radix-3', int(m), tmCoil_forward, tmCoil_adjoint) # for ss in range(0, sense_number): erry = numpy.linalg.norm(yradix3.get() - ycpu) / numpy.linalg.norm(ycpu) errx = numpy.linalg.norm(xradix3.get() - xcpu) / numpy.linalg.norm(xcpu) if erry > 1e-6 or errx > 1e-6: print("degraded accuracy:", sense_number, erry, errx) else: print("Pass test for coil: ", sense_number, erry, errx) print("Pass test for coil: ", sense_number, erry, errx) # print("Pass test for coil: ", ss) NufftObj_radix3.release() del NufftObj_radix2, NufftObj_radix1, NufftObj_radix3, NufftObj_cpu return tcpu_forward, tcpu_adjoint, thsa_forward, thsa_adjoint, tmem_forward, tmem_adjoint, tmCoil_forward, tmCoil_adjoint
# -*- coding: utf-8 -*- """ Created on Mon Oct 29 08:39:01 2018 @author: jon """ import cmath import math import numpy as np import matplotlib.pyplot as plt from pynufft import NUFFT_cpu import scipy.io as sio y = sio.loadmat("/home/jon/Desktop/export_mat/y.mat")['y'][0,0].reshape(307780) p = np.asarray(sio.loadmat("/home/jon/Desktop/export_mat/p.mat")["p"]) dirty = np.asarray(sio.loadmat("/home/jon/Desktop/export_mat/dirty.mat")["dirty"]) NufftObj = NUFFT_cpu() Nd = (512, 512) # image size Kd = (2048, 2048) # k-space size Jd = (8, 8) # interpolation size NufftObj.plan(p, Nd, Kd, Jd) res = NufftObj.adjoint(y) #res = NufftObj.solve(y, solver='cg',maxiter=1000) plt.imshow(np.real(res[256:640,256:640]))
# load k-space points import pkg_resources DATA_PATH = pkg_resources.resource_filename('pynufft', './src/data/') om = numpy.load(DATA_PATH + 'om2D.npz')['arr_0'] # om = numpy.random.randn(120000, 2) print(om) print('setting non-uniform coordinates...') matplotlib.pyplot.plot(om[::10, 0], om[::10, 1], 'o') matplotlib.pyplot.title('non-uniform coordinates') matplotlib.pyplot.xlabel('axis 0') matplotlib.pyplot.ylabel('axis 1') matplotlib.pyplot.show() NufftObj = NUFFT_cpu() Nd = (256, 256) # image size print('setting image dimension Nd...', Nd) Kd = (512, 512) # k-space size print('setting spectrum dimension Kd...', Kd) Jd = (6, 6) # interpolation size print('setting interpolation size Jd...', Jd) NufftObj.plan(om, Nd, Kd, Jd) image = scipy.misc.ascent() image = scipy.misc.imresize(image, (256, 256)) image = image * 1.0 / numpy.max(image[...]) print('loading image...')
def FFTgridDSGfile(netCDFfiles): ds = Dataset(netCDFfiles[1], 'a') vs = ds.get_variables_by_attributes(standard_name='sea_water_pressure_due_to_sea_water') vs = ds.get_variables_by_attributes(long_name='actual depth') pres_var = vs[0] pres = pres_var[:] #plt.plot(pres) #plt.show() temp_var = ds.variables["TEMP"] print("Read and convert time") time_var = ds.variables["TIME"] #time = num2date(time_var[:], units=time_var.units, calendar=time_var.calendar) #first_hour = time[0].replace(minute=0, second=0, microsecond=0) t = time_var[:] * 24 hours = t # scale time to -pi to pi hours_min = np.min(hours) hours_max = np.max(hours) mid_hours = (hours_max + hours_min)/2 print("time min, max", hours_min, hours_max, num2date(hours_max/24, units=time_var.units, calendar=time_var.calendar), num2date(hours_min/24, units=time_var.units, calendar=time_var.calendar), num2date(mid_hours/24, units=time_var.units, calendar=time_var.calendar)) t2pi = 2*np.pi * (hours - mid_hours) / (hours_max - hours_min) # scale pressure to -pi to pi pres_min = np.min(pres) pres_max = np.max(pres) pres_mid = (pres_max + pres_min)/2 print("pres min, max", pres_min, pres_max, pres_mid) d2pi = 2*np.pi * (pres - pres_mid) / (pres_max - pres_min) #plt.plot(t2pi) #plt.show() nt_points = int(hours_max - hours_min) nd_points = 20 print(nt_points, nd_points) print("Calc FFT") x = t2pi y = d2pi c = np.array(temp_var[:]) #c.real = temp_var[:] #c.imag = 0 print(c) print("size ", len(x), len(y), len(c)) # Provided om, the size of time series (Nd), oversampled grid (Kd), and interpolatro size (Jd) om = [x, y] Nd = (256, 256) # image size Kd = (512, 512) # k-space size Jd = (6, 6) # interpolation size NufftObj = NUFFT_cpu() NufftObj.plan(om, Nd, Kd, Jd) fft = NufftObj.forward(c) print("fft ") print(fft) for x in range(0, nd_points): plt.plot(10*np.log10(abs(fft[:,x]))) plt.grid(True) plt.show() F1 = np.fft.ifft2(fft) f2 = np.fft.fftshift(F1) print("inverted ", f2.shape, len(hours)) first_hour = num2date(hours_min/24, units=time_var.units, calendar=time_var.calendar).replace(minute=0, second=0, microsecond=0) td = [first_hour + timedelta(hours=x) for x in range(nt_points)] for x in range(0, nd_points): plt.plot(td, abs(f2[:,x])/(len(hours)/(nt_points))) plt.grid(True) plt.xticks(fontsize=6) plt.show() index_var = ds.variables["instrument_index"] idx = index_var[:] instrument_id_var = ds.variables["instrument_id"] #time = num2date(time_var[:], units=time_var.units, calendar=time_var.calendar) #print(idx) i = 0 for x in chartostring(instrument_id_var[:]): #print (i, x, time[idx == 1], pres[idx == i]) #plt.plot(time[idx == i], pres[idx == i]) # , marker='.' i += 1 #plt.gca().invert_yaxis() #plt.grid(True) # close the netCDF file ds.close() plt.show() ncOut = Dataset("fft-bin.nc", 'w', format='NETCDF4') # add time tDim = ncOut.createDimension("TIME", nt_points) ncTimesOut = ncOut.createVariable("TIME", "d", ("TIME",), zlib=True) ncTimesOut.long_name = "time" ncTimesOut.units = "days since 1950-01-01 00:00:00 UTC" ncTimesOut.calendar = "gregorian" ncTimesOut.axis = "T" ncTimesOut[:] = hours_min / 24 bin_dim = ncOut.createDimension("BIN", nd_points) bin_var = ncOut.createVariable("BIN", "d", ("BIN",), zlib=True) bin_var[:] = range(0, nd_points) # add variables nc_var_out = ncOut.createVariable("TEMP", "f4", ("TIME", "BIN"), fill_value=np.nan, zlib=True) print("shape ", f2.shape, nc_var_out.shape) nc_var_out[:] = abs(f2) # add some summary metadata ncTimeFormat = "%Y-%m-%dT%H:%M:%SZ" # add creating and history entry ncOut.setncattr("date_created", datetime.utcnow().strftime(ncTimeFormat)) ncOut.setncattr("history", datetime.utcnow().strftime("%Y-%m-%d") + " created from file " + netCDFfiles[1]) ncOut.close()