예제 #1
0
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()
예제 #2
0
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()
예제 #3
0
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
예제 #4
0
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
예제 #5
0
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()
예제 #6
0
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
예제 #7
0
Jd = (6,6) # interpolator size

NufftObj.plan(om, Nd, Kd, Jd) 


# load image from scipy.misc.face()
import scipy.misc
import matplotlib.cm as cm
image = scipy.misc.face(gray=True)
image = scipy.misc.imresize(image, (256,256))
image=image.astype(numpy.float)/numpy.max(image[...])
pyplot.imshow(image, cmap=cm.gray)
pyplot.show()


# Forward NUFFT transform
y = NufftObj.forward(image)

# Adjoint NUFFT
k =   NufftObj.y2k(y)
import matplotlib.colors
k_show = numpy.fft.fftshift(k)
pyplot.imshow(numpy.abs(k_show), cmap=cm.gray, norm=matplotlib.colors.Normalize(0, 1e+3))
pyplot.show()

# Inverse transform using density compensation inverse_DC()
x3 = NufftObj.inverse_DC(y)
x3_display = x3*1.0/numpy.max(x3[...].real)
pyplot.imshow(x3_display.real,cmap=cm.gray)
pyplot.show()
예제 #8
0
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)

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')
예제 #9
0
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))

예제 #10
0
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)
예제 #11
0
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)
pyplot.title('L1TVLAD')

pyplot.subplot(2, 2, 3)
pyplot.imshow(numpy.real(restore_image2[:, :, 32]), label='L1TVOLS', cmap=gray)
예제 #12
0
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)
# matplotlib.pyplot.show()
# H = H*numpy.reshape(M0, Nd+(1,))*(1.0+0.0j)/256

NufftObj_coil.plan1(om2, Nd, (512, 512), (5, 5), ft_axes=(0, 1), coil_sense=H)

y = NufftObj.forward(M0)

y2 = numpy.fft.fftshift(
    numpy.fft.ifft2(numpy.fft.fftshift(y.reshape(Nd, order='C'))))
y3 = NufftObj_coil.forward((M0) * (1.0 + 0.0j))
print(y3.shape, y3)
# y3 = y3.reshape((Nc, 256, 256), order='C')
# y4 =  numpy.einsum('ijk -> jki', y3)
y4 = y3.reshape((256, 256, Nc), order='C')

# y4 =  numpy.fft.fftshift(numpy.fft.ifftn(numpy.fft.fftshift(y3, axes = (1,2)), axes = (1,2)), axes = (1,2))
y4 = numpy.fft.fftshift(numpy.fft.ifftn(numpy.fft.fftshift(y4, axes=(0, 1)),
                                        axes=(0, 1)),
                        axes=(0, 1))
# y2 = NufftObj.adjoint(y) / 512
예제 #13
0
파일: test_init.py 프로젝트: suiy02/pynufft
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")
예제 #14
0
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
pyplot.plot(om, y.real, '.', label='real')
pyplot.plot(om, y.imag, 'r.', label='imag')
pyplot.legend()
pyplot.show()

# Adjoint NUFFT
x2 = NufftObj.adjoint(y)
pyplot.plot(x2.real, '.-', label='real')
pyplot.plot(x2.imag, 'r.-', label='imag')
pyplot.plot(time_data, 'k', label='original signal')
pyplot.ylim(-1, 2)
pyplot.legend()
pyplot.show()
예제 #15
0
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()
예제 #16
0
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...')

matplotlib.pyplot.imshow(image.real, cmap=matplotlib.cm.gray)
matplotlib.pyplot.show()

y = NufftObj.forward(image)
print('setting non-uniform data')
print('y is an (M,) list', type(y), y.shape)

matplotlib.pyplot.subplot(2, 2, 1)
image0 = NufftObj.solve(y, solver='cg', maxiter=50)
matplotlib.pyplot.title('Restored image (cg)')
matplotlib.pyplot.imshow(image0.real,
                         cmap=matplotlib.cm.gray,
                         norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1))

matplotlib.pyplot.subplot(2, 2, 2)
image2 = NufftObj.adjoint(y)
matplotlib.pyplot.imshow(image2.real,
                         cmap=matplotlib.cm.gray,
                         norm=matplotlib.colors.Normalize(vmin=0.0, vmax=5))
예제 #17
0
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()