Пример #1
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()
Пример #2
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
Пример #3
0
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))
matplotlib.pyplot.title('Adjoint transform')

matplotlib.pyplot.subplot(2, 2, 3)
image3 = NufftObj.solve(y, solver='L1TVOLS', maxiter=50, rho=0.1)
matplotlib.pyplot.title('L1TV OLS')
matplotlib.pyplot.imshow(image3.real,
                         cmap=matplotlib.cm.gray,
                         norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1))

matplotlib.pyplot.subplot(2, 2, 4)
image4 = NufftObj.solve(y, solver='L1TVLAD', maxiter=50, rho=0.1)
matplotlib.pyplot.title('L1TV LAD')
Пример #4
0
    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)))

Пример #5
0
    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,
           norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1))
plt.show()
Пример #6
0
# -*- 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]))
Пример #7
0
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))
matplotlib.pyplot.title('Adjoint transform')

matplotlib.pyplot.subplot(2, 2, 3)
image3 = NufftObj.solve(y, solver='L1TVOLS', maxiter=50, rho=0.1)
matplotlib.pyplot.title('L1TV OLS')
matplotlib.pyplot.imshow(image3.real,
                         cmap=matplotlib.cm.gray,
                         norm=matplotlib.colors.Normalize(vmin=0.0, vmax=1))

matplotlib.pyplot.subplot(2, 2, 4)
image4 = NufftObj.solve(y, solver='L1TVLAD', maxiter=50, rho=0.1)
matplotlib.pyplot.title('L1TV LAD')
Пример #8
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()

    image = scipy.misc.imresize(image, (256, 256))

    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)

    W = numpy.ones(Kd, dtype=numpy.complex64)
    for pp in range(0, 200):
        W2 = NufftObj.xx2k(NufftObj.adjoint(NufftObj.forward(
            NufftObj.k2xx(W))))
        W2 = W2 * W2.conj()
        W2 = W2**0.5
        W = (W + 0.9) / (W2 + 0.9)

    matplotlib.pyplot.subplot(1, 2, 1)
    matplotlib.pyplot.imshow(W2.real)

    matplotlib.pyplot.subplot(1, 2, 2)
    matplotlib.pyplot.imshow((W / W2).real)
    matplotlib.pyplot.show()

    #     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()
    image2 = NufftObj.solve(y, 'dc', maxiter=25)
    #     image3 = NufftObj.solve(y, 'L1TVLAD',maxiter=100, rho= 1)
    image3 = NufftObj.k2xx(NufftObj.xx2k(NufftObj.adjoint(y)) * W)
    print(image3.shape)
    image4 = NufftObj.solve(y, 'L1TVOLS', maxiter=100, rho=1)
    matplotlib.pyplot.subplot(1, 3, 1)
    matplotlib.pyplot.imshow(image,
                             cmap=matplotlib.cm.gray,
                             norm=matplotlib.colors.Normalize(vmin=0.0,
                                                              vmax=1))
    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.subplot(1, 3, 3)
    matplotlib.pyplot.imshow(image4.real,
                             cmap=matplotlib.cm.gray,
                             norm=matplotlib.colors.Normalize(vmin=0.0,
                                                              vmax=1))
    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', 'lsmr',
                   '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()
Пример #9
0
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")
Пример #10
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()

# Test inverse method using density compensation (inverse DC)
x3 = NufftObj.inverse_DC(y)
pyplot.plot(x3.real, '.-', label='real')
pyplot.plot(x3.imag, 'r.-', label='imag')
pyplot.plot(time_data, 'k', label='original signal')
pyplot.ylim(-1, 2)
pyplot.legend()
pyplot.show()