Beispiel #1
0
def NFFTspect(nodes, values, N, M):
    nfft = NFFT( N=[N, N], M=M )
    nfft.x = np.c_[ nodes, np.zeros_like(nodes) ]
    nfft.precompute()

    #f     = np.empty( M,       dtype=np.complex128)
    #f_hat = np.empty( (N, N), dtype=np.complex128)

    infft = Solver(nfft)
    infft.y = values         # '''right hand side, samples.'''

    #infft.f_hat_iter = initial_f_hat # assign arbitrary initial solution guess, default is 0
    #print( infft.r_iter )# etc...all internals should still be uninitialized

    infft.before_loop()       # initialize solver internals
    #print( 'infft.r_iter', infft.r_iter ) # etc...all internals should be initialized

    nIter = 0
    maxIter = 50                    # completely arbitrary
    threshold = 1e-6
    while (infft.r_iter.sum() > threshold):
        if nIter > maxIter:
            raise RuntimeError( 'Solver did not converge, aborting' )
        infft.loop_one_step()
        nIter += 1
    
    return infft.f_hat_iter[:,0]
Beispiel #2
0
 def __init__(self, data):
     self.normFactor = data.vis.size #SORT OF normalization. Weights are currently ignored.
     
     #create two pynfft objects, one for fft and one for ifft.
     #in theory one object should suffice, but the implementation tends to crash
     ifft_obj = NFFT(data.imsize, data.uv.shape[0])
     ifft_obj.x = data.uv.flatten()
     ifft_obj.precompute()
     self.ifft_obj = ifft_obj
     fft_obj = NFFT(data.imsize, data.uv.shape[0])
     fft_obj.x = data.uv.flatten()
     fft_obj.precompute()
     self.fft_obj = fft_obj
Beispiel #3
0
def series_nfft(series,
                oversample=4):
    """
    note that output period units are [days] (so is frequency)
    """
    M = len(series)
    if not is_power_of_2(M):
        raise ValueError('series length {} is not a power of 2'.format(len(series)))
    N = M
    if N % 2 == 1:
        # number of frequency samples must be even
        N += 1
    N *= oversample
    # re-grid time the interval [-1/2, 1/2) as required by nfft
    time = series.index.astype(NP.int64) / 1e9
    time -= time[0]
    b = -0.5
    a = (M - 1) / (M * time[-1])
    x = a * time + b
    # setup for nfft computation
    plan = NFFT(N, M)
    plan.x = x
    plan.f = series.values
    plan.precompute()
    # compute nfft (note that conjugation is necessary because of the
    # difference in transform sign convention)
    x_nfft = NP.conj(plan.adjoint())
    # calculate frequencies and periods
    dt = ((series.index[-1] - series.index[0]) / M).total_seconds() / DAYS_TO_SECONDS
    f_range = NP.fft.fftshift(NP.fft.fftfreq(N, dt))
    T_range = 1 / f_range
    return x_nfft, f_range, T_range
Beispiel #4
0
def fourier(event, fit, fignum, savefile):
    x = fit.timeunit
    y = fit.residuals

    shift1 = x[0]
    newx = x - shift1

    stretch1 = 1 / x[-1]
    newx *= stretch1

    shift2 = 0.5
    newx -= shift2

    M = len(y)
    N = M // 2

    nfft_obj = NFFT(N, M=M)
    nfft_obj.x = newx
    nfft_obj.precompute()

    nfft_obj.f = y

    nfft_obj.adjoint()

    power = np.zeros(len(nfft_obj.f_hat))
    for i in range(len(nfft_obj.f_hat)):
        power[i] = np.abs(nfft_obj.f_hat[i])**2

    k = np.arange(-N // 2, N // 2, 1)

    plt.clf()
    plt.plot(k, power)
    plt.xlabel('Frequency (periods/dataset)')
    plt.ylabel('Power')
    plt.title('Power spectrum of Fourier transform of residuals')
    plt.xlim((0, M // 500))
    #plt.ylim((0,max(power[N/2:N/2+M/500])))
    if savefile != None:
        plt.savefig(savefile)
    return
Beispiel #5
0
def autocorrelation_dfft(times, trajs):
    """
    This function never worked... need to download correct packages
    """

    # for now do the first trajectory
    nodes = times; values = trajs[0]

    from pynfft import NFFT, Solver
    M = len(times)
    N = 128
    f     = np.empty(M,     dtype=np.complex128)
    f_hat = np.empty([N,N], dtype=np.complex128)

    this_nfft = NFFT(N=[N,N], M=M)
    this_nfft.x = np.array([[node_i,0.] for node_i in nodes])
    this_nfft.precompute()

    this_nfft.f = f
    ret2=this_nfft.adjoint()

    #print this_nfft.x # nodes in [-0.5, 0.5), float typed

    this_solver = Solver(this_nfft)
    this_solver.y = values          # '''right hand side, samples.'''

    #this_solver.f_hat_iter = f_hat # assign arbitrary init sol guess, default 0

    this_solver.before_loop()       # initialize solver internals

    while not np.all(this_solver.r_iter < 1e-2):
        this_solver.loop_one_step()

    # plotting
    fig=plt.figure(1,(20,5))
    ax =fig.add_subplot(111)

    foo=[ np.abs( this_solver.f_hat_iter[i][0])**2\
                                for i in range(len(this_solver.f_hat_iter) ) ]

    ax.plot( np.abs(np.arange(-N/2,+N/2,1)) )
    plt.show()

    return autocor, spectrum
def singleFrequency():
    imsize = (256, 256)
    cell = np.asarray(
        [0.5, -0.5]
    ) / 3600.0  # #arcseconds. revert v axis because it is empirically right. the axes in the ms are not really standardized
    cell = np.radians(cell)
    ms = MS_jon()
    ms.read_ms("simkat64-default.ms")
    # 4 polarizations are XX, XY, YX and YY
    #Intensity image should be XX + YY

    wavelengths = ms.freq_array[0, 0] / constants.c
    uvw_wavelengths = np.dot(ms.uvw_array, np.diag(np.repeat(wavelengths, 3)))
    uv = np.multiply(uvw_wavelengths[:, 0:2], cell)

    plan = NFFT(imsize, uv.shape[0])
    plan.x = uv.flatten()
    plan.precompute()

    plan.f = ms.data_array[:, :, 0, 0]
    dirty = plan.adjoint() / uv.shape[0]
    plt.imshow(np.flipud(np.transpose(np.real(dirty))))
def allFrequencies():
    imsize = (256, 256)
    cell = np.asarray(
        [0.5, -0.5]
    ) / 3600.0  # #arcseconds. revert v axis because it is empirically right. the axes in the ms are not really standardized
    cell = np.radians(cell)
    ms = MS_jon()
    ms.read_ms("simkat64-default.ms")

    wavelengths = ms.freq_array[0] / constants.c

    offset = ms.uvw_array.shape[0]
    start = 0
    end = offset
    uv = np.zeros((ms.uvw_array.shape[0] * wavelengths.size, 2))
    vis = np.zeros(ms.uvw_array.shape[0] * wavelengths.size,
                   dtype=np.complex128)
    for i in range(0, wavelengths.size):
        uvw_wavelengths = np.dot(ms.uvw_array,
                                 np.diag(np.repeat(wavelengths[i], 3)))
        #skip w component
        uv[start:end] = uvw_wavelengths[:, 0:2]
        #add the XX and YY Polarization to get an intensity
        vis[start:end] = ms.data_array[:, 0, i, 0] + ms.data_array[:, 0, i, 3]
        start += offset
        end += offset
    uv = np.multiply(uv, cell)

    plan = NFFT(imsize, uv.shape[0])
    plan.x = uv.flatten()
    plan.precompute()

    plan.f = vis
    dirty = plan.adjoint() / uv.shape[0] / 2
    plt.imshow(np.real(dirty))
    print(np.max(np.real(dirty)))

    return 0
def compute_nfft_potts(images, fast_model, start, finish):
    x = fast_model.us_fft_pts
    n = fast_model.size_x
    points_inside_circle = fast_model.points_inside_circle
    num_images = finish - start

    # pynufft
    # m = x.shape[0]
    # nufft_obj = NUFFT_cpu()
    # nufft_obj.plan(x, (n, n), (2*n, 2*n), (10, 10))
    # shift = np.exp(x * fast_model.resolution * 1j)
    # shift = np.sum(shift, axis=1)

    # gal nufft
    # m = x.shape[1]
    # nufft_obj = py_nufft.factory('nufft')

    # pynfft
    m = x.shape[0]
    plan = NFFT(N=[n, n], M=m)
    plan.x = x
    plan.precompute()

    images_nufft = np.zeros((m, num_images), dtype='complex128')
    current_image = np.zeros((n, n))
    for i in range(start, finish):

        current_image[points_inside_circle] = images[:, i]

        # images_nufft[:, i - start] = nufft_obj.forward(current_image) * shift

        plan.f_hat = current_image
        images_nufft[:, i - start] = plan.trafo()

        # images_nufft[:, i - start] = nufft_obj.forward2d(current_image.T, x, iflag=-1)[0]

    return images_nufft
Beispiel #9
0
import matplotlib.pyplot as plt
import scipy.io as sio

from pynfft import NFFT, Solver

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"])

#p_shaped = np.reshape( (1/6.0)*p, (p.shape[0]*p.shape[1]))
#dim= (1024,1024)
p_shaped = np.reshape((1 / 4.0) * p, (p.shape[0] * p.shape[1]))
dim = (256, 256)
plan = NFFT(dim, y.size)

plan.x = p_shaped
plan.precompute()

infft = Solver(plan)
infft.w = np.ones(y.shape)
infft.y = y
infft.f_hat_iter = np.zeros(dim, dtype=np.complex128)
infft.before_loop()

niter = 100  # set number of iterations to 10
for iiter in range(niter):
    print("alive" + str(iiter))
    print(np.max(infft.r_iter))
    infft.loop_one_step()
Beispiel #10
0
u1 = (-cell)*(71.50 / wave_length)
v1 = (cell)*(-368.67 / wave_length)
vis1 = toComplex(53.456, math.radians(162.4)+2*math.pi*(u1*27+v1*27))
vis1 = toComplex(53.456, math.radians(173.2))
dim = [54,54]
img = np.zeros(dim, dtype=np.complex128)

inverseFT(img, vis0, u0, v0)
inverseFT(img, vis1, u1, v1)
#inverseFT(img, 1, 0.2,1)

plt.imshow(np.real(img))
print(img[0,0])
.


plan = NFFT(dim, 2)
plan.x = np.asarray([u0, v0, u1, v1])
plan.precompute()

plan.f = np.asarray([vis0, vis1])
res = plan.adjoint(use_dft=True)
print(res[0,0])
plt.imshow(np.real(res))





Beispiel #11
0
def get_plan(M, N):
    f = np.empty(M, dtype=np.complex128)
    f_hat = np.empty(N, dtype=np.complex128)
    plan = NFFT(f, f_hat)
    return plan
Beispiel #12
0
        #print Einv
        #print nodes
        #print values

        #print "Number of nodes: ", len(nodes)
        #print "Number of values: ", len(values)
        #sys.exit(0)

        # Fourier transform: initialization and precompute
        M = len(nodes)  # number of nodes
        N = len(nodes)  # number of Fourier coefficients

        f = np.empty(M, dtype=np.complex128)
        f_hat = np.empty([N, N], dtype=np.complex128)

        this_nfft = NFFT(N=[N, N], M=M)
        this_nfft.x = np.array([[node_i, 0.] for node_i in nodes])
        this_nfft.precompute()
        #print "precompute done"

        this_nfft.f = f
        ret2 = this_nfft.adjoint()
        #print "adjoint done"

        #print this_nfft.M  # number of nodes, complex typed
        #print this_nfft.N  # number of Fourier coefficients, complex typed
        #print this_nfft.x # nodes in [-0.5, 0.5), float typed

        this_solver = Solver(this_nfft)
        #print "Solver initialized"
        this_solver.y = values  # '''right hand side, samples.'''