Exemple #1
0
def dirSampPattern(N, P, pctg, radius, dirs, radFac=1.5):
    #import pdb; pdb.set_trace()
    N = np.array(N[-2:])
    smallImgSize = np.floor(radFac * (radius * N)).astype(int)
    if smallImgSize[0] % 2 == 1:
        smallImgSize[0] -= 1
    if smallImgSize[1] % 2 == 1:
        smallImgSize[1] -= 1
    sq = ((N - smallImgSize) / 2).astype(int)
    pctgSmall = np.min([2 * pctg, 0.75])
    pdf = samp.genPDF(smallImgSize,
                      P,
                      pctgSmall,
                      radius=1 / radFac,
                      cyl=[1, smallImgSize[-2], smallImgSize[-1]],
                      pft=False,
                      ext=0.5)
    #pdf = samp.genPDF(smallImgSize,P,pctgSmall,radius=1/radFac,cyl=[0],pft=False,ext=0.5)
    # We want to make sure that we're only looking at the circle now...
    x, y = np.meshgrid(np.linspace(-1, 1, smallImgSize[1]),
                       np.linspace(-1, 1, smallImgSize[0]))
    r = np.sqrt(x**2 + y**2)
    pdf[pdf <= pctg] = 0
    pdf[(pdf == 0) * (r <= 1)] = pctg
    k = np.zeros(np.hstack([len(dirs), N]))
    for i in range(len(dirs)):
        k[i, sq[0]:-sq[0],
          sq[1]:-sq[1]] = samp.genSampling(pdf, int(1e-2 * pdf.size),
                                           2)[0].astype(int)

    sampSets = makeDirSetsPE(dirs, pctg)[1]
    nDirs = len(dirs)
    nSets = len(sampSets[0])
    #nVals = len(sampSets[1])
    #sampSets = np.array(sampSets)

    x, y = np.meshgrid(np.linspace(-1, 1, N[1]), np.linspace(-1, 1, N[0]))
    rSamp = np.sqrt(x**2 + y**2)
    rLocs = (rSamp <= 1).astype(int)
    rSmall = zpad((r <= 1).astype(int), rSamp.shape)
    sampLocs = np.where(rLocs * (rSmall == 0))

    for i in range(len(sampLocs[0])):
        randDir = int(np.random.random(1) * nDirs)
        randSet = int(np.random.random(1) * nSets)
        k[sampSets[randDir][randSet], sampLocs[0][i], sampLocs[1][i]] = 1

    return k
def dirSampPattern(N,P,pctg,radius,dirs,radFac=1.5):
    #import pdb; pdb.set_trace()
    N = np.array(N[-2:])
    smallImgSize = np.floor(radFac*(radius*N)).astype(int)
    if smallImgSize[0]%2 == 1:
        smallImgSize[0] -= 1
    if smallImgSize[1]%2 == 1:
        smallImgSize[1] -= 1
    sq = ((N-smallImgSize)/2).astype(int)
    pctgSmall = np.min([2*pctg,0.75])
    pdf = samp.genPDF(smallImgSize,P,pctgSmall,radius=1/radFac,cyl=[1,smallImgSize[-2],smallImgSize[-1]],pft=False,ext=0.5)
    #pdf = samp.genPDF(smallImgSize,P,pctgSmall,radius=1/radFac,cyl=[0],pft=False,ext=0.5)
    # We want to make sure that we're only looking at the circle now...
    x,y = np.meshgrid(np.linspace(-1,1,smallImgSize[1]),np.linspace(-1,1,smallImgSize[0]))
    r = np.sqrt(x**2+y**2)
    pdf[pdf<=pctg] = 0
    pdf[(pdf == 0)*(r <= 1)] = pctg
    k = np.zeros(np.hstack([len(dirs), N]))
    for i in range(len(dirs)):
        k[i,sq[0]:-sq[0],sq[1]:-sq[1]] = samp.genSampling(pdf, int(1e-2*pdf.size), 2)[0].astype(int)
    
    sampSets = makeDirSetsPE(dirs,pctg)[1]
    nDirs = len(dirs)
    nSets = len(sampSets[0])
    #nVals = len(sampSets[1])
    #sampSets = np.array(sampSets)
    
    x,y = np.meshgrid(np.linspace(-1,1,N[1]),np.linspace(-1,1,N[0]))
    rSamp = np.sqrt(x**2+y**2)
    rLocs = (rSamp<=1).astype(int)
    rSmall = zpad((r<=1).astype(int),rSamp.shape)
    sampLocs = np.where(rLocs*(rSmall==0))
    
    for i in range(len(sampLocs[0])):
        randDir = int(np.random.random(1)*nDirs)
        randSet = int(np.random.random(1)*nSets)
        k[sampSets[randDir][randSet],sampLocs[0][i],sampLocs[1][i]] = 1
           
    return k
Exemple #3
0
def create_scanner_k_space(im,
                           N,
                           P=2,
                           pctg=0.25,
                           dirData=False,
                           dirs=None,
                           radius=0.2,
                           cyl=[0],
                           style='mult',
                           pft=False,
                           ext=0.5):
    '''
    Read in the data, size, and the directions (if they exist) so that we can create a
    retrospectively sampled set of data for testing.
    '''

    # Create a pdf so that we can use it to make a starting point
    pdf = samp.genPDF(N[-2:],
                      P,
                      pctg,
                      radius=radius,
                      cyl=[1, N[-2], N[-1]],
                      style='mult',
                      pft=pft,
                      ext=0.5)

    # Generate the sampling scheme, depending on whether or not
    if dirData:
        if dirs is None:
            raise ValueError(
                'If we have directional data, you need to feed this into the function'
            )
        k = d.dirPDFSamp([int(dirs.shape[0]), N[-2], N[-1]],
                         P=2,
                         pctg=pctg,
                         radius=radius,
                         dirs=dirs,
                         cyl=True,
                         taper=0.25)[0]
    else:
        k = samp.genSampling(pdf, 50, 2)[0].astype(int)

    # Since our functions are built to work in 3D datasets, here we
    # make sure that N and things are all in 3D
    if len(N) == 2:
        N = np.hstack([1, N])
        k = k.reshape(N)
        im = im.reshape(N)
    elif len(N) == 3:
        if k.ndim == 2:
            k = k.reshape(np.hstack([1, N[-2:]])).repeat(N[0], 0)

    k = np.fft.fftshift(k, axes=(-2, -1))
    # Convert the image data into k-space
    ph_ones = np.ones(N, complex)
    dataFull = tf.fft2c(im, ph=ph_ones, axes=(-2, -1))
    # Apply our sampling
    data = k * dataFull
    # Now we need to calculate the phase in order to deal with the undersampled image and the
    # non perfect cancellation of terms
    #filtdata = gaussian_filter(im_scan_wph.real,0,0) + 1j*gaussian_filter(im_scan_wph.imag,0,0)
    #ph_scan = np.exp(1j*np.angle(filtdata.conj()))
    im_scan_wph = tf.ifft2c(data, ph=ph_ones)
    ph_scan = np.angle(
        gaussian_filter(im_scan_wph.real, 0) +
        1.j * gaussian_filter(im_scan_wph.imag, 0))
    ph_scan = np.exp(1j * ph_scan)
    im_scan = tf.ifft2c(data, ph=ph_scan)

    pdfDiv = pdf.copy()
    pdfZeros = np.where(pdf < 1e-4)
    pdfDiv[pdfZeros] = 1
    datadc = data / pdfDiv

    return dataFull, data, datadc, pdf, k, im_scan, ph_scan
Exemple #4
0
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

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

# IMAGE from the "scanner data"
P = 2
nSteps = 4

print('k for Directions')
#kDir = samp.genSamplingDir(img_sz=N, dirFile=dirFile, pctg=pctg, cyl=[1], radius=radius,            
                #nmins=nmins, engfile=engfile)
kDir = d.dirPDFSamp(N,P=2,pctg=0.25,radius=0.2,dirs=dirs,cyl=True,taper=0.25)

pdf = samp.genPDF(N[-2:], P, pctg, radius=radius, cyl=[1, N[-2], N[-1]], style='mult', pft=pft,ext=0.5)
k = np.zeros(N)

print('k for non')
for i in xrange(N[0]):                             
    np.random.seed(int(i*abs(np.random.randn(1)*np.random.randn(1))))
    print(i)
    k[i,:,:] = samp.genSampling(pdf, 50, 2)[0].astype(int)


ph_ones = np.ones(N[-2:], complex)
dataFull = np.zeros(N,complex)

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]):
Exemple #6
0
#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=0.3, 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, 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());

# IMAGE from the "scanner data"
im_scan = tf.ifft2c(data, ph=ph)

# Primary first guess. What we're using for now. Density corrected
im_dc = tf.ifft2c(data / np.fft.ifftshift(pdf), ph=ph).real.flatten().copy()

# Optimization algortihm -- this is where everything culminates together
a = 10.0
testargs = (N, TVWeight, XFMWeight, data, k, strtag, ph, dirWeight, dirs, M,
def dirPDFSamp(N,P,pctg,radius,dirs,cyl=True,taper=0.1):
    print("Create PDF")
    N0 = N
    N = np.array(N[-2:])
    x,y = np.meshgrid(np.linspace(-1+1e-4,1-1e-4,N[1]),np.linspace(-1+1e-4,1-1e-4,N[0]))
    r = np.sqrt(x**2 + y**2)
    pdf = np.zeros(N)
    pdf[r<=radius] = 1
    if cyl:
        totPix = np.pi/4*np.prod(N)
        PCTG = round(pctg*totPix)
    else:
        totPix = np.prod(N)
        PCTG = round(pctg*totPix)
    midPix = round(np.sum(pdf))
    leftPix = PCTG-midPix
    leftPdf = leftPix/totPix
    rTap = radius+taper
    rHold = r.copy()
    rHold = ((r<=rTap)*(r>radius))*r
    rHold = abs(rHold - np.max(rHold))/taper
    rHold[rHold>1] = 1e6
    leftPdf = (leftPix - (np.sum((rHold<=1)*(rHold>=0)*(1-leftPdf))/P))/totPix
    rHold[(rHold<=1)*(rHold>=0)] += leftPdf**(1/P)
    rHold[(rHold>=1)*(rHold<=1e3)] = 1
    rHold[rHold>1e4] = 0
    pdf = pdf + rHold**P
    tapPix = round(np.sum(pdf))
    
    if cyl:
        pdf[(r<=1)*(r>rTap)] = leftPdf
    else:
        pdf[r>rTap] = leftPdf
    
    pdf = ndimage.filters.gaussian_filter(pdf,1)
    pdf[pdf>1] = 1
    
    if cyl:
        pdf[(r<=1)*(pdf<leftPdf)] = leftPdf
        pdf[r>1] = 0
    else:
        pdf[(r<=1)*(pdf<leftPdf)] = leftPdf
        
    pdf[abs(pdf-leftPdf)<1e-4] = 0
    print("Create Var. Dens. Pattern")
    k = np.zeros(N0)    
    for i in range(N0[0]):
        k[i] = samp.genSampling(pdf, 10, 2)[0].astype(int)
    
    print("Create teams of directions")
    sampSets = makeDirSetsPE(dirs,leftPdf)[1]
    nDirs = len(dirs)
    nSets = len(sampSets[0])
    
    rLocs = ((r<=1)*(r>=rTap)).astype(int)
    sampLocs = np.where(rLocs)
    
    print("Choose groups for each point in k-space")
    for i in range(len(sampLocs[0])):
        randDir = int(np.random.random(1)*nDirs)
        randSet = int(np.random.random(1)*nSets)
        k[sampSets[randDir][randSet],sampLocs[0][i],sampLocs[1][i]] = 1
    
    return k
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()
ph = tf.matlab_style_gauss2D(im,shape=(5,5));
#ph = np.ones(im.shape, complex)
Ps = np.arange(0,5.1,.5)

kmult = np.zeros(np.hstack([len(Ps), N]))
kadd = np.zeros(kmult.shape)
pdfadd = np.zeros(kmult.shape)
pdfmult = np.zeros(kmult.shape)

cnt = -1
for P in Ps:
    cnt += 1
    print(P)
    if P>2:
        pdfadd[cnt,:,:] = samp.genPDF(N, P, pctg, radius=radius, cyl=[0])
        kadd[cnt,:,:] = samp.genSampling(pdfadd[cnt,:,:], 50, 2)[0].astype(int)
        
    pdfmult[cnt,:,:] = samp.genPDF(N, P, pctg, radius=radius, cyl=[0], style = 'mult')
    kmult[cnt,:,:] = samp.genSampling(pdfmult[cnt,:,:], 50, 2)[0].astype(int)

cnt = -1
rads = np.linspace(-np.sqrt(2),np.sqrt(2),N[0])
plt.rcParams['lines.linewidth'] = 4
cols = ('b','k','r','g','m','c','y','0.5','0.75',(0.25,0.25,0.75),(1,0.25,0.5))
fig=plt.figure()
strPs = map(str,Ps)
for P in Ps:
    print(P)
    cnt += 1
    plt.plot(rads,pdfmult[cnt,147,:],color=cols[cnt])
    #samp.pltSlice(pdfmult[cnt,:,:],sl=147,rads=rads,col=cols[cnt])
Exemple #10
0
def dirPDFSamp(N, P, pctg, radius, dirs, cyl=True, taper=0.1):
    print("Create PDF")
    N0 = N
    N = np.array(N[-2:])
    x, y = np.meshgrid(np.linspace(-1 + 1e-4, 1 - 1e-4, N[1]),
                       np.linspace(-1 + 1e-4, 1 - 1e-4, N[0]))
    r = np.sqrt(x**2 + y**2)
    pdf = np.zeros(N)
    pdf[r <= radius] = 1
    if cyl:
        totPix = np.pi / 4 * np.prod(N)
        PCTG = round(pctg * totPix)
    else:
        totPix = np.prod(N)
        PCTG = round(pctg * totPix)
    midPix = round(np.sum(pdf))
    leftPix = PCTG - midPix
    leftPdf = leftPix / totPix
    rTap = radius + taper
    rHold = r.copy()
    rHold = ((r <= rTap) * (r > radius)) * r
    rHoldMax = np.max(rHold)
    rHold = abs(rHold - rHoldMax) / taper
    rHold[rHold > (rHoldMax / taper - 1e-9)] = 0
    leftPdf = (leftPix - (np.sum(
        (rHold < 1) * (rHold > 0) * (1 - leftPdf)) / P)) / totPix
    if cyl:
        leftPdf = leftPdf * np.pi / 4
    rHold[(rHold < 1) * (rHold > 0)] += leftPdf  #**(1/P)
    rHold = rHold / np.max(rHold)
    rHold[rHold > 1] = 0
    #rHold[rHold<1(rHold>=1)*(rHold<=1e3)] = 1
    #rHold[rHold>1e4] = 0
    pdf = pdf + rHold
    tapPix = round(np.sum(pdf))

    if cyl:
        pdf[(r <= 1) * (r > rTap)] = leftPdf
    else:
        pdf[r > rTap] = leftPdf

    pdf = ndimage.filters.gaussian_filter(pdf, 1)
    pdf[pdf > 1] = 1

    if cyl:
        pdf[(r <= 1) * (pdf < leftPdf)] = leftPdf
        pdf[r > 1] = 0
    else:
        pdf[(r <= 1) * (pdf < leftPdf)] = leftPdf

    #pdf[abs(pdf-leftPdf)<1e-4] = 0
    print("Create Var. Dens. Pattern")
    k = np.zeros(N0)
    for i in range(N0[0]):
        k[i] = samp.genSampling(pdf, 10, 2)[0].astype(int)

    print("Create teams of directions")
    sampSets = makeDirSetsPE(dirs, leftPdf)[1]
    nDirs = len(dirs)
    nSets = len(sampSets[0])

    rLocs = ((r <= 1) * (r >= (0.95 * rTap))).astype(int)
    sampLocs = np.where(rLocs)

    print("Choose groups for each point in k-space")
    for i in range(len(sampLocs[0])):
        randDir = int(np.random.random(1) * nDirs)
        randSet = int(np.random.random(1) * nSets)
        k[sampSets[randDir][randSet], sampLocs[0][i], sampLocs[1][i]] = 1

    return k, pdf
Exemple #11
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()