Ejemplo n.º 1
0
def loRes(im, pctg):
    N = im.shape
    ph_ones = np.ones(N)
    [x, y] = np.meshgrid(np.linspace(-1, 1, N[1]), np.linspace(-1, 1, N[0]))
    rsq = x**2 + y**2
    loResMaskLocs = np.where(rsq < pctg)
    loResMask = np.zeros(N)
    loResMask[loResMaskLocs] = 1
    loResMask = sp.ndimage.filters.gaussian_filter(loResMask, 3)
    data = np.fft.fftshift(loResMask) * tf.fft2c(im, ph=ph_ones)
    im_lr_wph = tf.ifft2c(data, ph=ph_ones)
    ph_lr = tf.matlab_style_gauss2D(im_lr_wph, shape=(5, 5))
    ph_lr = np.exp(1j * ph_lr)
    im_lr = tf.ifft2c(data, ph=ph_lr)
    return im_lr
Ejemplo n.º 2
0
def loRes(im,pctg):
    N = im.shape
    ph_ones=np.ones(N)
    [x,y] = np.meshgrid(np.linspace(-1,1,N[1]),np.linspace(-1,1,N[0]))
    rsq = x**2 + y**2
    loResMaskLocs = np.where(rsq < pctg)
    loResMask = np.zeros(N)
    loResMask[loResMaskLocs] = 1
    loResMask = sp.ndimage.filters.gaussian_filter(loResMask,3)
    data = np.fft.fftshift(loResMask)*tf.fft2c(im, ph=ph_ones)
    im_lr_wph = tf.ifft2c(data,ph=ph_ones)
    ph_lr = tf.matlab_style_gauss2D(im_lr_wph,shape=(5,5))
    ph_lr = np.exp(1j*ph_lr)
    im_lr = tf.ifft2c(data, ph=ph_lr)
    return im_lr
Ejemplo n.º 3
0
def calcPhase(im, k, w1=10, w2=8, w3=4, eps = np.pi/18, sig = 0):
    '''
    This function is to try to iteratively calculate the phase as per Tisdall and Atkins 2005 (https://www.cs.sfu.ca/~stella/papers/2005/spie.pdf)
    
    With X(p) being our spatial domain value at pixel p:
        - X(p) = image we have
        - s(p) = signal proper
        - n_r(p) = real noise -- Gaussian
        - n_i(p) = imaginary noise -- Gaussian
        
    Assume: X(p) = s(p) exp[i φ(p)] + n_r(p) + i n_i(p)
    
    We want to calculate φ^(p) which is an estimate of φ(p), thrn multiply it in. If φ(p) == φ^(p), then:
    
    X(p) exp[-i φ^(p)] = s(p) + (n_r(p) + i n_i(p)) exp[-i φ^(p)]
        Because exp[-i φ^(p)] is just a rotation, the rotation of noise, just makes different noise, so (n_r(p) + i n_i (p)) exp[-i φ^(p)] == n_r`(p) + i n_i`(p)
    
    So our new measurement is:
        X(p) exp[-i φ^(p)] = s(p) + (n_r`(p) + i n_i`(p)) 
        
    '''
    if sig==0:
        sig = np.var(im[:50,:50])
    
    ph_ones = np.ones(im.shape)
    data = np.fft.ifftshift(k) * tf.fft2c(im, ph=ph_ones)
    im_scan_ph = tf.ifft2c(data, ph=ph_ones)
    ph = tf.matlab_style_gauss2D(im_scan_ph,shape=(5,5))
    im_scan = tf.ifft2c(data, ph=ph)

    N = im.shape
    window1 = int(np.ceil(w1/2))
    window2 = int(np.ceil(w2/2))
    window3 = int(np.ceil(w3/2))

    
    im_wrap = np.pad(im_scan,window1,'wrap')

    #ph = np.zeros(im.shape,complex)
    #ph_new = np.zeros(im.shape,complex)
    ph_new = ph.copy()
    wgts = np.ones(im.size)    
        
    '''
    
    We then do this over three steps. Step 1 is:
    
        1. Apply the given phase correction, φ^ to the recorded image, I to get our current best guess image, I`.
    
        2. Calculate the mean of the imaginary component of all the pixels in I` in a window of width w1 around p.
        
        3. If the mean imaginary component is greater than ||p||, the magnitude of p, set p’s new phase estimate, φ^`(p), to be π/2 to correct as much as possible.
        
        4. If the mean imaginary component is less than −||p||, set φ^`(p)=−π/2 to correct as much as possible.
        
        5. Set φ^`(p) so p’s phase is on (−π/2,π/2) and its imaginary component cancels the mean component of all the other pixels in the window.
    
    
    '''
    
    ph = ph_new.copy()
    
    for x in range(N[0]):
        for y in range(N[1]):
            mn = np.mean(im_wrap[x:x+1+w1,y:y+1+w1].imag)
            if mn > abs(im_scan[x,y]):
                ph_new[x,y] = +1j
            elif mn < -abs(im_scan[x,y]):
                ph_new[x,y] = -1j
            else:
                ph_new[x,y] = abs(ph_new[x,y].real) - mn*1j
                # The abs() is required here to ensure that the phase is on (-π/2,π/2)
    
    
    ''' 
    
    Step 2 requires us to look at those times where we shifted positives to negatives, and try to flip it back when necessary.
    
    This then follows three more substeps:
        
        1. Calculate the mean of the distances, wrapped onto the range [−π,π), from φ^(p) to each other phase estimate pixel in a window of with w2 centered on p.
        
        2. Calculate the mean of the distances, wrapped onto the range [−π,π), from φ^(p) + π to each other phase estimate pixel in a window of with w2 centered on p.
        
        3. If the second mean distance is smaller than the first, mark p as flipped.
        
    '''
    
    # need to map phases from [-pi,pi)
    #ph_wrap_angles_piShift = (np.angle(np.pad(ph_new,window2,'wrap')) + np.pi) % (2*np.pi)
    ph_wrap_angles = np.arctan2(ph_new.imag, ph_new.real)
    cnt = 0
    
    for x in range(N[0]):
        for y in range(N[1]):
            diffs = np.sum(np.diff(ph_wrap_angles[x:x+1+w2,y:y+1+w2],axis=0)) + \
                    np.sum(np.diff(ph_wrap_angles[x:x+1+w2,y:y+1+w2],axis=1)) 
            ph_wrap_hold = np.exp(1j*ph_wrap_angles[x,y]+np.pi)
            ph_wrap_angles[x,y] = np.arctan2(ph_wrap_hold.imag,ph_wrap_hold.real)
            diffs_piShift = np.sum(np.diff(ph_wrap_angles[x:x+1+w2,y:y+1+w2],axis=0)) + \
                            np.sum(np.diff(ph_wrap_angles[x:x+1+w2,y:y+1+w2],axis=1)) 
            
            if diffs_piShift < diffs:
                #print('Smaller')
                cnt+=1
                ph_new[x,y] = np.exp(1j*ph_wrap_angles[x,y])
            
            ph_wrap_hold = np.exp(1j*ph_wrap_angles[x,y]-np.pi)
            ph_wrap_angles[x,y] = np.arctan2(ph_wrap_hold.imag,ph_wrap_hold.real)
        
    ph_new = np.exp(1j*ph_wrap_angles)
    
    
            
Ejemplo n.º 4
0
L = 2
method = 'CG'
dirFile = None
nmins = None

np.random.seed(2000)
im = np.load(filename)

for i in range(len(strtag)):
    strtag[i] = strtag[i].lower()

N = np.array(im.shape)  #image Size
tupleN = tuple(N)
pctg = 0.25  # undersampling factor
P = 5  # Variable density polymonial degree
ph = tf.matlab_style_gauss2D(im, shape=(5, 5))

pdf = samp.genPDF(
    N, P, pctg, radius=0.1, cyl=[0]
)  # Currently not working properly for the cylindrical case -- can fix at home
# Set the sampling pattern -- checked and this gives the right percentage
k = samp.genSampling(pdf, 10, 60)[0].astype(int)

# Diffusion information that we need
if dirFile:
    dirs = np.loadtxt(dirFile)
    M = d.calc_Mid_Matrix(dirs, nmins=4)
else:
    dirs = None
    M = None
Ejemplo n.º 5
0
ph_scan = np.zeros(N, complex)
data = np.zeros(N,complex)
im_scan = np.zeros(N, complex)

ph_scanDir = np.zeros(N, complex)
dataDir = np.zeros(N,complex)
im_scanDir = np.zeros(N, complex)

print('Data Production')
for i in range(N[0]):
    data[i,:,:] = np.fft.fftshift(k[i,:,:])*tf.fft2c(im[i,:,:], ph=ph_ones)
    dataDir[i,:,:] = np.fft.fftshift(kDir[i,:,:])*tf.fft2c(im[i,:,:], ph=ph_ones)
    dataFull[i,:,:] = np.fft.fftshift(tf.fft2c(im[i,:,:], ph=ph_ones))
    im_scan_wph = tf.ifft2c(data[i,:,:], ph=ph_ones)
    im_scan_wphDir = tf.ifft2c(dataDir[i,:,:], ph=ph_ones)
    ph_scan[i,:,:] = tf.matlab_style_gauss2D(im_scan_wph,shape=(5,5))
    ph_scanDir[i,:,:] = tf.matlab_style_gauss2D(im_scan_wphDir,shape=(5,5))
    ph_scan[i,:,:] = np.exp(1j*ph_scan[i,:,:])
    ph_scanDir[i,:,:] = np.exp(1j*ph_scanDir[i,:,:])
    im_scan[i,:,:] = tf.ifft2c(data[i,:,:], ph=ph_scan[i,:,:])
    im_scanDir[i,:,:] = tf.ifft2c(dataDir[i,:,:], ph=ph_scanDir[i,:,:])


print('Mix the Data')
dataDirComb = d.dirDataSharing(kDir,dataDir,dirs,N[-2:],maxCheck=5,bymax=1)
dataComb = d.dirDataSharing(k,data,dirs,N[-2:],maxCheck=5,bymax=1)
kDirComb = d.dirDataSharing(kDir,kDir,dirs,N[-2:],maxCheck=5,bymax=1)
kComb = d.dirDataSharing(k,k,dirs,N[-2:],maxCheck=5,bymax=1)


ph_scanComb = np.zeros(N, complex)
Ejemplo n.º 6
0
dirs = None
M = None
radius = 0.1

np.random.seed(2000)

# im = np.zeros([8,8]);
# im[3:5,3:5] = 1;

im = np.load(filename)

N = np.array(im.shape)  # image Size
#tupleN = tuple(N)
pctg = 0.25  # undersampling factor
P = 5  # Variable density polymonial degree
ph = tf.matlab_style_gauss2D(im,shape=(5,5));
#ph = np.ones(im.shape, complex)

# Generate the PDF for the sampling case -- note that this type is only used in non-directionally biased cases.
pdf = samp.genPDF(N, P, pctg, radius=radius, cyl=[0]) 
# Set the sampling pattern -- checked and this gives the right percentage
k = samp.genSampling(pdf, 50, 2)[0].astype(int)

# Here is where we build the undersampled data
data = np.fft.ifftshift(k) * tf.fft2c(im, ph=ph)
# ph = phase_Calculation(im,is_kspace = False)
# data = np.fft.ifftshift(np.fft.fftshift(data)*ph.conj());
filt = tf.fermifilt(N)
data = data * filt

# IMAGE from the "scanner data"
    k = k.reshape(N)
    im = im.reshape(N)
elif len(N) == 3:
    k = k.reshape(np.hstack([1,N[-2:]])).repeat(N[0],0)

ph_ones = np.ones(N[-2:], complex)
ph_scan = np.zeros(N, complex)
data = np.zeros(N,complex)
im_scan = np.zeros(N,complex)
for i in range(N[0]):
    k[i,:,:] = np.fft.fftshift(k[i,:,:])
    data[i,:,:] = k[i,:,:]*tf.fft2c(im[i,:,:], ph=ph_ones)

    # IMAGE from the "scanner data"
    im_scan_wph = tf.ifft2c(data[i,:,:], ph=ph_ones)
    ph_scan[i,:,:] = tf.matlab_style_gauss2D(im_scan_wph,shape=(5,5))
    ph_scan[i,:,:] = np.exp(1j*ph_scan[i,:,:])
    im_scan[i,:,:] = tf.ifft2c(data[i,:,:], ph=ph_scan[i,:,:])
    
    
    #im_lr = samp.loRes(im,pctg)


# ------------------------------------------------------------------ #
# A quick way to look at the PSF of the sampling pattern that we use #
delta = np.zeros(N[-2:])
delta[int(N[-2]/2),int(N[-1]/2)] = 1
psf = tf.ifft2c(tf.fft2c(delta,ph_ones)*k,ph_ones)
# ------------------------------------------------------------------ #

def runCSAlgorithm(fromfid=False,
                   filename='/home/asalerno/Documents/pyDirectionCompSense/brainData/P14/data/fullySampledBrain.npy',
                   sliceChoice=150,
                   strtag = ['','spatial', 'spatial'],
                   xtol = [1e-2, 1e-3, 5e-4, 5e-4],
                   TV = [0.01, 0.005, 0.002, 0.001],
                   XFM = [0.01,.005, 0.002, 0.001],
                   dirWeight=0,
                   pctg=0.25,
                   radius=0.2,
                   P=2,
                   pft=False,
                   ext=0.5,
                   wavelet='db4',
                   mode='per',
                   method='CG',
                   ItnLim=30,
                   lineSearchItnLim=30,
                   alpha_0=0.6,
                   c=0.6,
                   a=10.0,
                   kern = 
                   np.array([[[ 0.,  0.,  0.], 
                   [ 0.,  0.,  0.], 
                   [ 0.,  0.,  0.]],                
                  [[ 0.,  0.,  0.],
                  [ 0., -1.,  0.],
                  [ 0.,  1.,  0.]],
                  [[ 0.,  0.,  0.],
                  [ 0., -1.,  1.],
                  [ 0.,  0.,  0.]]]),
                   dirFile = None,
                   nmins = None,
                   dirs = None,
                   M = None,
                   dirInfo = [None]*4,
                   saveNpy=False,
                   saveNpyFile=None,
                   saveImsPng=False,
                   saveImsPngFile=None,
                   saveImDiffPng=False,
                   saveImDiffPngFile=None,
                   disp=False):
    ##import pdb; pdb.set_trace()
    if fromfid==True:
        inputdirectory=filename[0]
        petable=filename[1]
        fullImData = rff.getDataFromFID(petable,inputdirectory,2)[0,:,:,:]
        fullImData = fullImData/np.max(abs(fullImData))
        im = fullImData[:,:,sliceChoice]
    else:
        im = np.load(filename)[sliceChoice,:,:]
        
    N = np.array(im.shape)  # image Size

    pdf = samp.genPDF(N[-2:], P, pctg, radius=radius, cyl=np.hstack([1, N[-2:]]), style='mult', pft=pft, ext=ext)
    if pft:
        print('Partial Fourier sampling method used')
    k = samp.genSampling(pdf, 50, 2)[0].astype(int)
    if len(N) == 2:
        N = np.hstack([1, N])
        k = k.reshape(N)
        im = im.reshape(N)
    elif (len(N) == 3) and ('dir' not in strtag):
        k = k.reshape(np.hstack([1,N[-2:]])).repeat(N[0],0)

    ph_ones = np.ones(N[-2:], complex)
    ph_scan = np.zeros(N, complex)
    data = np.zeros(N,complex)
    im_scan = np.zeros(N,complex)
    for i in range(N[0]):
        k[i,:,:] = np.fft.fftshift(k[i,:,:])
        data[i,:,:] = k[i,:,:]*tf.fft2c(im[i,:,:], ph=ph_ones)

        # IMAGE from the "scanner data"
        im_scan_wph = tf.ifft2c(data[i,:,:], ph=ph_ones)
        ph_scan[i,:,:] = tf.matlab_style_gauss2D(im_scan_wph,shape=(5,5))
        ph_scan[i,:,:] = np.exp(1j*ph_scan[i,:,:])
        im_scan[i,:,:] = tf.ifft2c(data[i,:,:], ph=ph_scan[i,:,:])
        #im_lr = samp.loRes(im,pctg)
    
    # ------------------------------------------------------------------ #
    # A quick way to look at the PSF of the sampling pattern that we use #
    delta = np.zeros(N[-2:])
    delta[int(N[-2]/2),int(N[-1]/2)] = 1
    psf = tf.ifft2c(tf.fft2c(delta,ph_ones)*k,ph_ones)
    # ------------------------------------------------------------------ #


    ## ------------------------------------------------------------------ #
    ## -- Currently broken - Need to figure out what's happening here. -- #
    ## ------------------------------------------------------------------ #
    #if pft:
        #for i in xrange(N[0]):
            #dataHold = np.fft.fftshift(data[i,:,:])
            #kHold = np.fft.fftshift(k[i,:,:])
            #loc = 98
            #for ix in xrange(N[-2]):
                #for iy in xrange(loc,N[-1]):
                    #dataHold[-ix,-iy] = dataHold[ix,iy].conj()
                    #kHold[-ix,-iy] = kHold[ix,iy]
    ## ------------------------------------------------------------------ #
    
    pdfDiv = pdf.copy()
    pdfZeros = np.where(pdf==0)
    pdfDiv[pdfZeros] = 1
    #im_scan_imag = im_scan.imag
    #im_scan = im_scan.real

    N_im = N.copy()
    hld, dims, dimOpt, dimLenOpt = tf.wt(im_scan[0].real,wavelet,mode)
    N = np.hstack([N_im[0], hld.shape])

    w_scan = np.zeros(N)
    w_full = np.zeros(N)
    im_dc = np.zeros(N_im)
    w_dc = np.zeros(N)

    for i in xrange(N[0]):
        w_scan[i,:,:] = tf.wt(im_scan.real[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt)[0]
        w_full[i,:,:] = tf.wt(abs(im[i,:,:]),wavelet,mode,dims,dimOpt,dimLenOpt)[0]

        im_dc[i,:,:] = tf.ifft2c(data[i,:,:] / np.fft.ifftshift(pdfDiv), ph=ph_scan[i,:,:]).real.copy()
        w_dc[i,:,:] = tf.wt(im_dc,wavelet,mode,dims,dimOpt,dimLenOpt)[0]

    w_dc = w_dc.flatten()
    im_sp = im_dc.copy().reshape(N_im)
    minval = np.min(abs(im))
    maxval = np.max(abs(im))
    data = np.ascontiguousarray(data)

    imdcs = [im_dc,np.zeros(N_im),np.ones(N_im),np.random.randn(np.prod(N_im)).reshape(N_im)]
    imdcs[-1] = imdcs[-1] - np.min(imdcs[-1])
    imdcs[-1] = imdcs[-1]/np.max(abs(imdcs[-1]))
    mets = ['Density Corrected','Zeros','1/2''s','Gaussian Random Shift (0,1)']
    wdcs = []
    for i in range(len(imdcs)):
        wdcs.append(tf.wt(imdcs[i][0],wavelet,mode,dims,dimOpt,dimLenOpt)[0].reshape(N))

    ims = []
    #print('Starting the CS Algorithm')
    for kk in range(len(wdcs)):
        w_dc = wdcs[kk]
        print(mets[kk])
        for i in range(len(TV)):
            args = (N, N_im, dims, dimOpt, dimLenOpt, TV[i], XFM[i], data, k, strtag, ph_scan, kern, dirWeight, dirs, dirInfo, nmins, wavelet, mode, a)
            w_result = opt.minimize(f, w_dc, args=args, method=method, jac=df, 
                                        options={'maxiter': ItnLim, 'lineSearchItnLim': lineSearchItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': alpha_0, 'c': c, 'xtol': xtol[i], 'TVWeight': TV[i], 'XFMWeight': XFM[i], 'N': N})
            if np.any(np.isnan(w_result['x'])):
                print('Some nan''s found. Dropping TV and XFM values')
            elif w_result['status'] != 0:
                print('TV and XFM values too high -- no solution found. Dropping...')
            else:
                w_dc = w_result['x']
                
        w_res = w_dc.reshape(N)
        im_res = np.zeros(N_im)
        for i in xrange(N[0]):
            im_res[i,:,:] = tf.iwt(w_res[i,:,:],wavelet,mode,dims,dimOpt,dimLenOpt)
        ims.append(im_res)
    
    if saveNpy:
        if saveNpyFile is None:
            np.save('./holdSave_im_res_' + str(int(pctg*100)) + 'p_all_SP',ims)
        else:
            np.save(saveNpyFile,ims)
    
    if saveImsPng:
        vis.figSubplots(ims,titles=mets,clims=(minval,maxval),colorbar=True)
        if not disp:
            if saveImsPngFile is None:
                saveFig.save('./holdSave_ims_' + str(int(pctg*100)) + 'p_all_SP')
            else:
                saveFig.save(saveImsPngFile)
    
    if saveImDiffPng:
        imdiffs, clims = vis.imDiff(ims)
        diffMets = ['DC-Zeros','DC-Ones','DC-Random','Zeros-Ones','Zeros-Random','Ones-Random']
        vis.figSubplots(imdiffs,titles=diffMets,clims=clims,colorbar=True)
        if not disp:
            if saveImDiffPngFile is None:
                saveFig.save('./holdSave_im_diffs_' + str(int(pctg*100)) + 'p_all_SP')
            else:
                saveFig.save(saveImDiffPngFile)
    
    if disp:
        plt.show()
Ejemplo n.º 9
0
N = data_b1.shape

######################################################
# Remember that the b0 will ALWAYS BE FULLY SAMPLED

# Try to find the phase of the fully sampled b0s as well, so have a ph_ones
ph_ones = np.ones(N[-2:])

ph_b0 = np.ones(data_b0.shape, dtype='complex')
im_b0_wph = np.zeros(data_b0.shape, dtype='complex')
im_b0_scan = np.zeros(data_b0.shape, dtype='complex')

for i in range(data_b0.shape[0]):
    im_b0_wph[i, :, :] = tf.ifft2c(data_b0[i, :, :], ph=ph_ones)
    ph_b0[i, :, :] = np.exp(
        1j * tf.matlab_style_gauss2D(im_b0_wph[i, :, :], shape=(5, 5)))
    im_b0_scan[i, :, :] = tf.ifft2c(data_b0[i, :, :], ph_b0[i, :, :])

im_b0_avg = np.mean(im_b0_scan, axis=(0))
minval = np.min(abs(im_b0_avg))
maxval = np.max(abs(im_b0_avg))

###############################################################################
# Now for both the undersampled cases and fully sampled cases for the actual
ph_b1 = np.ones(data_b1.shape, dtype='complex')
im_b1_wph = np.zeros(data_b1.shape, dtype='complex')
im_b1_scan = np.zeros(data_b1.shape, dtype='complex')

ph_b1_full = np.ones(data_b1.shape, dtype='complex')
im_b1_wph_full = np.zeros(data_b1.shape, dtype='complex')
im_b1_full = np.zeros(data_b1.shape, dtype='complex')
Ejemplo n.º 10
0
            k = samp.genSampling(pdf, 50, 2)[0].astype(int)
            if len(N) == 2:
                N = np.hstack([1, N])
                k = k.reshape(N)

            # Here is where we build the undersampled data
            ph_ones = np.ones(im.shape, complex)
            data = np.fft.ifftshift(k) * tf.fft2c(im, ph=ph_ones)
            # data = np.fft.ifftshift(np.fft.fftshift(data)*ph.conj());
            #filt = tf.fermifilt(N)
            #data = data * filt

            # IMAGE from the "scanner data"
            #ph_ones = np.ones(im.shape, complex)
            im_scan_wph = tf.ifft2c(data, ph=ph_ones)
            ph_scan = tf.matlab_style_gauss2D(im_scan_wph, shape=(5, 5))
            #ph_scan = tf.matlab_style_gauss2D(im,shape=(5,5))

            #for i in range(phIter):
            #ph_scan = tf.laplacianUnwrap(ph_scan,N,[75,75])

            ph_scan = np.exp(1j * ph_scan)
            im_scan = tf.ifft2c(data, ph=ph_scan)
            #im_scan = abs(tf.ifft2c(data,ph_ones))
            #data = tf.fft2c(im_scan,ph_ones).reshape(data.size).reshape(N)
            #ph_scan = ph_ones

            minval = np.min(abs(im))
            maxval = np.max(abs(im))

            # Primary first guess. What we're using for now. Density corrected
data_b1 = data_b1_full*np.fft.fftshift(k,axes=(-2,-1))
N = data_b1.shape

######################################################
# Remember that the b0 will ALWAYS BE FULLY SAMPLED

# Try to find the phase of the fully sampled b0s as well, so have a ph_ones
ph_ones = np.ones(N[-2:])

ph_b0 = np.ones(data_b0.shape, dtype='complex')
im_b0_wph = np.zeros(data_b0.shape, dtype='complex')
im_b0_scan = np.zeros(data_b0.shape, dtype='complex')

for i in range(data_b0.shape[0]):
    im_b0_wph[i,:,:] = tf.ifft2c(data_b0[i,:,:],ph=ph_ones)
    ph_b0[i,:,:] = np.exp(1j*tf.matlab_style_gauss2D(im_b0_wph[i,:,:],shape=(5,5)))
    im_b0_scan[i,:,:] = tf.ifft2c(data_b0[i,:,:],ph_b0[i,:,:])

im_b0_avg = np.mean(im_b0_scan,axis=(0))
minval = np.min(abs(im_b0_avg))
maxval = np.max(abs(im_b0_avg))

###############################################################################
# Now for both the undersampled cases and fully sampled cases for the actual
ph_b1 = np.ones(data_b1.shape, dtype='complex')
im_b1_wph = np.zeros(data_b1.shape, dtype='complex')
im_b1_scan = np.zeros(data_b1.shape, dtype='complex')

ph_b1_full = np.ones(data_b1.shape, dtype='complex')
im_b1_wph_full = np.zeros(data_b1.shape, dtype='complex')
im_b1_full = np.zeros(data_b1.shape, dtype='complex')
Ejemplo n.º 12
0
im_scan = np.zeros(N, complex)

ph_scanDir = np.zeros(N, complex)
dataDir = np.zeros(N, complex)
im_scanDir = np.zeros(N, complex)

print('Data Production')
for i in range(N[0]):
    data[i, :, :] = np.fft.fftshift(k[i, :, :]) * tf.fft2c(im[i, :, :],
                                                           ph=ph_ones)
    dataDir[i, :, :] = np.fft.fftshift(kDir[i, :, :]) * tf.fft2c(im[i, :, :],
                                                                 ph=ph_ones)
    dataFull[i, :, :] = np.fft.fftshift(tf.fft2c(im[i, :, :], ph=ph_ones))
    im_scan_wph = tf.ifft2c(data[i, :, :], ph=ph_ones)
    im_scan_wphDir = tf.ifft2c(dataDir[i, :, :], ph=ph_ones)
    ph_scan[i, :, :] = tf.matlab_style_gauss2D(im_scan_wph, shape=(5, 5))
    ph_scanDir[i, :, :] = tf.matlab_style_gauss2D(im_scan_wphDir, shape=(5, 5))
    ph_scan[i, :, :] = np.exp(1j * ph_scan[i, :, :])
    ph_scanDir[i, :, :] = np.exp(1j * ph_scanDir[i, :, :])
    im_scan[i, :, :] = tf.ifft2c(data[i, :, :], ph=ph_scan[i, :, :])
    im_scanDir[i, :, :] = tf.ifft2c(dataDir[i, :, :], ph=ph_scanDir[i, :, :])

print('Mix the Data')
dataDirComb = d.dirDataSharing(kDir,
                               dataDir,
                               dirs,
                               N[-2:],
                               maxCheck=5,
                               bymax=1)
dataComb = d.dirDataSharing(k, data, dirs, N[-2:], maxCheck=5, bymax=1)
kDirComb = d.dirDataSharing(kDir, kDir, dirs, N[-2:], maxCheck=5, bymax=1)
Ejemplo n.º 13
0
elif len(N) == 3:
    k = k.reshape(np.hstack([1,N[-2:]])).repeat(N[0],0)

ph_ones = np.ones(N[-2:], complex)
ph_scan = np.zeros(N, complex)
data = np.zeros(N,complex)
dataFull = np.zeros(N,complex)
im_scan = np.zeros(N,complex)
for i in range(N[0]):
    #k[i,:,:] = np.fft.fftshift(k[i,:,:])
    data[i,:,:] = np.fft.fftshift(k[i,:,:])*tf.fft2c(im[i,:,:], ph=ph_ones)
    dataFull[i,:,:] = np.fft.fftshift(tf.fft2c(im[i,:,:], ph=ph_ones))

    # IMAGE from the "scanner data"
    im_scan_wph = tf.ifft2c(data[i,:,:], ph=ph_ones)
    ph_scan[i,:,:] = tf.matlab_style_gauss2D(im_scan_wph,shape=(5,5))
    ph_scan[i,:,:] = np.exp(1j*ph_scan[i,:,:])
    im_scan[i,:,:] = tf.ifft2c(data[i,:,:], ph=ph_scan[i,:,:])
    
    
    #im_lr = samp.loRes(im,pctg)


# ------------------------------------------------------------------ #
# A quick way to look at the PSF of the sampling pattern that we use #
delta = np.zeros(N[-2:])
delta[int(N[-2]/2),int(N[-1]/2)] = 1
psf = tf.ifft2c(tf.fft2c(delta,ph_ones)*k,ph_ones)
# ------------------------------------------------------------------ #

Ejemplo n.º 14
0
def runCSAlgorithm(
        fromfid=False,
        filename='/home/asalerno/Documents/pyDirectionCompSense/brainData/P14/data/fullySampledBrain.npy',
        sliceChoice=150,
        strtag=['', 'spatial', 'spatial'],
        xtol=[1e-2, 1e-3, 5e-4, 5e-4],
        TV=[0.01, 0.005, 0.002, 0.001],
        XFM=[0.01, .005, 0.002, 0.001],
        dirWeight=0,
        pctg=0.25,
        radius=0.2,
        P=2,
        pft=False,
        ext=0.5,
        wavelet='db4',
        mode='per',
        method='CG',
        ItnLim=30,
        lineSearchItnLim=30,
        alpha_0=0.6,
        c=0.6,
        a=10.0,
        kern=np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
                       [[0., 0., 0.], [0., -1., 0.], [0., 1., 0.]],
                       [[0., 0., 0.], [0., -1., 1.], [0., 0., 0.]]]),
        dirFile=None,
        nmins=None,
        dirs=None,
        M=None,
        dirInfo=[None] * 4,
        saveNpy=False,
        saveNpyFile=None,
        saveImsPng=False,
        saveImsPngFile=None,
        saveImDiffPng=False,
        saveImDiffPngFile=None,
        disp=False):
    ##import pdb; pdb.set_trace()
    if fromfid == True:
        inputdirectory = filename[0]
        petable = filename[1]
        fullImData = rff.getDataFromFID(petable, inputdirectory, 2)[0, :, :, :]
        fullImData = fullImData / np.max(abs(fullImData))
        im = fullImData[:, :, sliceChoice]
    else:
        im = np.load(filename)[sliceChoice, :, :]

    N = np.array(im.shape)  # image Size

    pdf = samp.genPDF(N[-2:],
                      P,
                      pctg,
                      radius=radius,
                      cyl=np.hstack([1, N[-2:]]),
                      style='mult',
                      pft=pft,
                      ext=ext)
    if pft:
        print('Partial Fourier sampling method used')
    k = samp.genSampling(pdf, 50, 2)[0].astype(int)
    if len(N) == 2:
        N = np.hstack([1, N])
        k = k.reshape(N)
        im = im.reshape(N)
    elif (len(N) == 3) and ('dir' not in strtag):
        k = k.reshape(np.hstack([1, N[-2:]])).repeat(N[0], 0)

    ph_ones = np.ones(N[-2:], complex)
    ph_scan = np.zeros(N, complex)
    data = np.zeros(N, complex)
    im_scan = np.zeros(N, complex)
    for i in range(N[0]):
        k[i, :, :] = np.fft.fftshift(k[i, :, :])
        data[i, :, :] = k[i, :, :] * tf.fft2c(im[i, :, :], ph=ph_ones)

        # IMAGE from the "scanner data"

        im_scan_wph = tf.ifft2c(data[i, :, :], ph=ph_ones)
        ph_scan[i, :, :] = tf.matlab_style_gauss2D(im_scan_wph, shape=(5, 5))
        ph_scan[i, :, :] = np.exp(1j * ph_scan[i, :, :])
        im_scan[i, :, :] = tf.ifft2c(data[i, :, :], ph=ph_scan[i, :, :])
        #im_lr = samp.loRes(im,pctg)

    # ------------------------------------------------------------------ #
    # A quick way to look at the PSF of the sampling pattern that we use #
    delta = np.zeros(N[-2:])
    delta[int(N[-2] / 2), int(N[-1] / 2)] = 1
    psf = tf.ifft2c(tf.fft2c(delta, ph_ones) * k, ph_ones)
    # ------------------------------------------------------------------ #

    ## ------------------------------------------------------------------ #
    ## -- Currently broken - Need to figure out what's happening here. -- #
    ## ------------------------------------------------------------------ #
    #if pft:
    #for i in xrange(N[0]):
    #dataHold = np.fft.fftshift(data[i,:,:])
    #kHold = np.fft.fftshift(k[i,:,:])
    #loc = 98
    #for ix in xrange(N[-2]):
    #for iy in xrange(loc,N[-1]):
    #dataHold[-ix,-iy] = dataHold[ix,iy].conj()
    #kHold[-ix,-iy] = kHold[ix,iy]
    ## ------------------------------------------------------------------ #

    pdfDiv = pdf.copy()
    pdfZeros = np.where(pdf == 0)
    pdfDiv[pdfZeros] = 1
    #im_scan_imag = im_scan.imag
    #im_scan = im_scan.real

    N_im = N.copy()
    hld, dims, dimOpt, dimLenOpt = tf.wt(im_scan[0].real, wavelet, mode)
    N = np.hstack([N_im[0], hld.shape])

    w_scan = np.zeros(N)
    w_full = np.zeros(N)
    im_dc = np.zeros(N_im)
    w_dc = np.zeros(N)

    for i in xrange(N[0]):
        w_scan[i, :, :] = tf.wt(im_scan.real[i, :, :], wavelet, mode, dims,
                                dimOpt, dimLenOpt)[0]
        w_full[i, :, :] = tf.wt(abs(im[i, :, :]), wavelet, mode, dims, dimOpt,
                                dimLenOpt)[0]

        im_dc[i, :, :] = tf.ifft2c(data[i, :, :] / np.fft.ifftshift(pdfDiv),
                                   ph=ph_scan[i, :, :]).real.copy()
        w_dc[i, :, :] = tf.wt(im_dc, wavelet, mode, dims, dimOpt, dimLenOpt)[0]

    w_dc = w_dc.flatten()
    im_sp = im_dc.copy().reshape(N_im)
    minval = np.min(abs(im))
    maxval = np.max(abs(im))
    data = np.ascontiguousarray(data)

    imdcs = [
        im_dc,
        np.zeros(N_im),
        np.ones(N_im),
        np.random.randn(np.prod(N_im)).reshape(N_im)
    ]
    imdcs[-1] = imdcs[-1] - np.min(imdcs[-1])
    imdcs[-1] = imdcs[-1] / np.max(abs(imdcs[-1]))
    mets = [
        'Density Corrected', 'Zeros', '1/2'
        's', 'Gaussian Random Shift (0,1)'
    ]
    wdcs = []
    for i in range(len(imdcs)):
        wdcs.append(
            tf.wt(imdcs[i][0], wavelet, mode, dims, dimOpt,
                  dimLenOpt)[0].reshape(N))

    ims = []
    #print('Starting the CS Algorithm')
    for kk in range(len(wdcs)):
        w_dc = wdcs[kk]
        print(mets[kk])
        for i in range(len(TV)):
            args = (N, N_im, dims, dimOpt, dimLenOpt, TV[i], XFM[i], data, k,
                    strtag, ph_scan, kern, dirWeight, dirs, dirInfo, nmins,
                    wavelet, mode, a)
            w_result = opt.minimize(f,
                                    w_dc,
                                    args=args,
                                    method=method,
                                    jac=df,
                                    options={
                                        'maxiter': ItnLim,
                                        'lineSearchItnLim': lineSearchItnLim,
                                        'gtol': 0.01,
                                        'disp': 1,
                                        'alpha_0': alpha_0,
                                        'c': c,
                                        'xtol': xtol[i],
                                        'TVWeight': TV[i],
                                        'XFMWeight': XFM[i],
                                        'N': N
                                    })
            if np.any(np.isnan(w_result['x'])):
                print('Some nan' 's found. Dropping TV and XFM values')
            elif w_result['status'] != 0:
                print(
                    'TV and XFM values too high -- no solution found. Dropping...'
                )
            else:
                w_dc = w_result['x']

        w_res = w_dc.reshape(N)
        im_res = np.zeros(N_im)
        for i in xrange(N[0]):
            im_res[i, :, :] = tf.iwt(w_res[i, :, :], wavelet, mode, dims,
                                     dimOpt, dimLenOpt)
        ims.append(im_res)

    if saveNpy:
        if saveNpyFile is None:
            np.save('./holdSave_im_res_' + str(int(pctg * 100)) + 'p_all_SP',
                    ims)
        else:
            np.save(saveNpyFile, ims)

    if saveImsPng:
        vis.figSubplots(ims,
                        titles=mets,
                        clims=(minval, maxval),
                        colorbar=True)
        if not disp:
            if saveImsPngFile is None:
                saveFig.save('./holdSave_ims_' + str(int(pctg * 100)) +
                             'p_all_SP')
            else:
                saveFig.save(saveImsPngFile)

    if saveImDiffPng:
        imdiffs, clims = vis.imDiff(ims)
        diffMets = [
            'DC-Zeros', 'DC-Ones', 'DC-Random', 'Zeros-Ones', 'Zeros-Random',
            'Ones-Random'
        ]
        vis.figSubplots(imdiffs, titles=diffMets, clims=clims, colorbar=True)
        if not disp:
            if saveImDiffPngFile is None:
                saveFig.save('./holdSave_im_diffs_' + str(int(pctg * 100)) +
                             'p_all_SP')
            else:
                saveFig.save(saveImDiffPngFile)

    if disp:
        plt.show()
Ejemplo n.º 15
0
    except:
        radius = 0.5*radius
# Set the sampling pattern -- checked and this gives the right percentage

if len(N) == 2:
    N = np.hstack([1, N])
    k = k.reshape(N)

# Here is where we build the undersampled data
ph_ones = np.ones(im.shape, complex)
data = tf.fft2c(im, ph=ph_ones)
data_full = tf.fft2c(imf, ph=ph_ones)

# IMAGE from the "scanner data"
im_scan_wph = tf.ifft2c(data, ph=ph_ones)
ph_scan = np.exp(1j*tf.matlab_style_gauss2D(im_scan_wph,shape=(5,5)))
im_scan = tf.ifft2c(data, ph=ph_scan)

ph_full = np.exp(1j*tf.matlab_style_gauss2D(imf,shape=(5,5)))
im_full = tf.ifft2c(data_full, ph=ph_full)
#im_scan = abs(tf.ifft2c(data,ph_ones))
#data = tf.fft2c(im_scan,ph_ones).reshape(data.size).reshape(N)
#ph_scan = ph_ones

minval = np.min(abs(im))
maxval = np.max(abs(im))

# Primary first guess. What we're using for now. Density corrected
pdfDiv = pdf.copy()
pdfZeros = np.where(pdf<0.01)
pdfDiv[pdfZeros] = 1