Exemplo n.º 1
0
def compute_posterior_params(freq_data, admittance_matrix, prior_params,
                             prior_params_std):
    """Calculate posterior parameters employing Bayesian approach.

    Args:
        freq_data (FreqData): Data after transformation from time domain
            to frequency domain produced by the 'prepare_data' function.
        admittance_matrix (AdmittanceMatrix): User-defined class
            representing an admittance matrix of a dynamical system.
        prior_params (numpy.ndarray): Prior parameters of a system.
        prior_params_std (numpy.ndarray): Prior uncertainties in
            system parameters (see the 'perturb_params' function).

    Returns:
        posterior_params (numpy.ndarray): Posterior parameters
            of a dynamical system calculated by employing Bayesian
            approach and special optimization routine.
    """
    if (len(freq_data.outputs) != admittance_matrix.data.shape[0]
            or len(freq_data.inputs) != admittance_matrix.data.shape[1]):
        raise ValueError('Inconsistent shapes of data and admittance matrix.')
    if len(prior_params.shape) != 1 or len(prior_params_std.shape) != 1:
        raise ValueError('Prior parameters and deviations'
                         'must be one-dimensional numpy arrays.')
    if prior_params.shape != prior_params_std.shape:
        raise ValueError('Number of system parameters is not equal'
                         'to number of deviation fractions.')

    obj_func = objective_function.ObjectiveFunction(
        freq_data=freq_data,
        admittance_matrix=admittance_matrix,
        prior_params=prior_params,
        prior_params_std=prior_params_std)

    # print('\n######################################################')
    # print('### DEBUG: OPTIMIZATION ROUTINE IS STARTING NOW!!! ###')
    # print('######################################################\n')
    posterior_params = optimize.minimize(func=obj_func, x0=prior_params)
    print('prior =', prior_params)
    print('posterior =', posterior_params)
    # WARNING! True parameters can be different! Remove the next line!
    # print('f(true_params) =', obj_func.compute(np.array([0.25, 1., 1., 0.01])))
    # print('f(posterior) =', obj_func.compute(posterior_params))
    # print('\n######################################################')
    return posterior_params
Exemplo n.º 2
0
def solve(fun, num_features, true_fun=None, domain="binary", maxiter=10000):
    solvers = (REAL_SOLVERS + BINARY_SOLVERS
               if domain == "binary" else REAL_SOLVERS)

    x0 = np.zeros(num_features)

    names = []
    columns = ["time", "score"]
    times = []
    scores = []
    for name, method, options in solvers:
        names.append(name)
        options["maxiter"] = maxiter
        start_time = time()
        result = minimize(fun, x0, method=method, options=options)
        total_time = time() - start_time
        times.append(total_time)
        if true_fun is None:
            scores.append(result.fun)
        else:
            scores.append(true_fun(result.x))
    return zip(names, times, scores)
Exemplo n.º 3
0
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"
im_scan = tf.ifft2c(data, ph)

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

# Optimization algortihm -- this is where everything culminates together
im_result = opt.minimize(optfun,
                         im_dc,
                         args=(N, TVWeight, XFMWeight, data, k, strtag,
                               dirWeight, dirs, M, nmins, scaling_factor, L,
                               ph),
                         method=method,
                         jac=derivative_fun,
                         options={
                             'maxiter': ItnLim,
                             'gtol': epsilon,
                             'disp': 1
                         })

# im_result gives us a lot of information, what we really need is ['x'] reshaped to the required image size -- N
return im_result, im_dc, im_scan
Exemplo n.º 4
0
    im_dc = tf.ifft2c(data / np.fft.ifftshift(pdf),
                      ph=ph).real.flatten().copy()

    #----------------#
    #     Step 1     #
    #----------------#
    args = (N, TV1, XFM1, data, k, strtag, ph, dirWeight, dirs, M, nmins,
            wavelet, mode, a)
    im_result = opt.minimize(optfun,
                             im_dc,
                             args=args,
                             method=method,
                             jac=derivative_fun,
                             options={
                                 'maxiter': ItnLim,
                                 'gtol': 0.01,
                                 'disp': 0,
                                 'alpha_0': 0.1,
                                 'c': 0.6,
                                 'xtol': xtol1,
                                 'TVWeight': TV1,
                                 'XFMWeight': XFM1,
                                 'N': N
                             })
    im_dc = im_result['x'].reshape(N)

    #----------------#
    #     Step 2     #
    #----------------#
    args = (N, TV2, XFM2, data, k, strtag, ph, dirWeight, dirs, M, nmins,
            wavelet, mode, a)
    im_result = opt.minimize(optfun,
Exemplo n.º 5
0
                                                aggregation=aggregation,
                                                problem=problem,
                                                n_dir=pop_size_per_epoch)

res = minimize(problem=problem,
               method='samoo',
               method_args={'seed': 53,
                            'method': 'samoo',
                            'framework_id': framework_id,
                            'ref_dirs': ref_dirs,
                            'metamodel_list': metamodel_list,
                            'acq_list': acq_list,
                            'framework_acq_dict': framework_acq_dict,
                            'aggregation': aggregation,
                            'lf_algorithm_list': lf_algorithm_list,
                            'init_pop_size': init_pop_size,
                            'pop_size_per_epoch': pop_size_per_epoch,
                            'pop_size_per_algorithm':pop_size_per_algorithm,
                            'pop_size_lf': pop_size_lf,
                            'n_gen_lf': 100,
                            'n_split': 2
                            },
               termination=('n_eval', 800),
               pf=pf,
               save_history=False,
               disp=True
               )
plotting.plot(pf, res.F, labels=["Pareto-front", "F"])
# filename = '/results/'+problem_name
# np.savetxt(filename+".F", res.pop.get("F"))
# np.savetxt(filename+".X", res.pop.get("X"))
Exemplo n.º 6
0
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"
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
args = (N, TVWeight, XFMWeight, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a)
im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun,
                         options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 0, 'alpha_0': 0.5, 'c': 0.6, 'xtol': 5e-3, 'TVWeight': TVWeight, 'XFMWeight': XFMWeight, 'N': N})
im_res = im_result['x'].reshape(N)
np.save('filtered-result.npy', im_res)

plt.imshow(im, interpolation='nearest', clim=(0, 1))
plt.title('True Image')
# plt.savefig('simpleBoxData/TVandXFM/SL-im.png')
plt.figure(2)
plt.imshow(np.reshape(im_dc, (N)), interpolation='nearest', clim=(0, 1))
plt.title('Original Image')
# plt.savefig('simpleBoxData/TVandXFM/SL-x0-zeros.png')
plt.figure(3)
plt.imshow(im_res, interpolation='nearest', clim=(0, 1))
plt.title('im as x0 Final Result')
# plt.savefig('simpleBoxData/TVandXFM/SL-final-im.png')
plt.show()
        minval = np.min(im)
        maxval = np.max(im)
        # 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()
        #for imdcs in ['zeros','ones','densCorr','imFull']:
        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

        #----------------#
        #     Step 1     #
        #----------------#
        args = (N, TV1, XFM1, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a)
        im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun,
                                options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': xtol1, 'TVWeight': TV1, 'XFMWeight': XFM1, 'N': N})
        im_dc = im_result['x'].reshape(N)

        #----------------#
        #     Step 2     #
        #----------------#
        args = (N, TV2, XFM2, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a)
        im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun,
                                options={'maxiter': ItnLim, 'gtol': 0.01, 'disp': 1, 'alpha_0': 0.1, 'c': 0.6, 'xtol': xtol2, 'TVWeight': TV2, 'XFMWeight': XFM2, 'N': N})
        im_dc = im_result['x'].reshape(N)
        
        #----------------#
        #     Step 3     #
        #----------------#
        args = (N, TV3, XFM3, data, k, strtag, ph, dirWeight, dirs, M, nmins, wavelet, mode, a)
        im_result = opt.minimize(optfun, im_dc, args=args, method=method, jac=derivative_fun,
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()
from numpy import *
import sys
sys.path.append("/home/asalerno/Documents/pyDirectionCompSense/source/")#path to modified optimize directory here
#import scipy.optimize as opt
import optimize as opt                                              #load by proper optimize directory name here

def f_Ab(p,A,b):
    return sum( (b-dot(A,p))**2 )

def g_f_Ab(p,A,b):
    gp = empty((len(p),),float)
    resids = 2*(b-dot(A,p))
    for j in range(len(gp)):
        gp[j] = dot(resids,(-A[:,j]))
    return gp

b=array([1,0,-1],float)
A=array([[1,2,0],[2,1,0],[0,1,2]],float)
p0=array([0,0,0],float)
args=(A,b)
optresult = opt.minimize(f_Ab,p0,args=args,method="CG",jac=g_f_Ab,
                         tol=1e-8,options={'maxiter': 100, 'gtol': 1e-6,'disp': True, 'c':0.6,'alpha_0':0.6,'xtol': 1e-6,'lineSearchItnLim': 30 })
Exemplo n.º 10
0
def f_Ab(p, A, b):
    return sum((b - dot(A, p))**2)


def g_f_Ab(p, A, b):
    gp = empty((len(p), ), float)
    resids = 2 * (b - dot(A, p))
    for j in range(len(gp)):
        gp[j] = dot(resids, (-A[:, j]))
    return gp


b = array([1, 0, -1], float)
A = array([[1, 2, 0], [2, 1, 0], [0, 1, 2]], float)
p0 = array([0, 0, 0], float)
args = (A, b)
optresult = opt.minimize(f_Ab,
                         p0,
                         args=args,
                         method="CG",
                         jac=g_f_Ab,
                         tol=1e-8,
                         options={
                             'maxiter': 100,
                             'gtol': 1e-6,
                             'disp': True,
                             'c': 0.6,
                             'alpha_0': 0.6,
                             'xtol': 1e-6,
                             'lineSearchItnLim': 30
                         })
Exemplo n.º 11
0
        XFMWeight = 0.
        TVWeight = 0.01
    elif i == 2:
        XFMWeight = 0.01
        TVWeight = 0.01

    for j in xrange(3):
        args = (N, TVWeight, XFMWeight, data, k, strtag, ph, dirWeight, dirs,
                M, nmins, wavelet, mode, a)
        im_result = opt.minimize(optfun,
                                 imvals[:, :, j].flatten(),
                                 args=args,
                                 method=method,
                                 jac=derivative_fun,
                                 options={
                                     'maxiter': ItnLim,
                                     'gtol': 0.01,
                                     'disp': 1,
                                     'alpha_0': 0.5,
                                     'c': 0.6,
                                     'xtol': 5e-3
                                 })
        im_res = im_result['x'].reshape(N)

        np.save('simpleBoxData/' + sty[i] + '/SL-' + x0sty[j] + '-result.npy',
                im_res)

        plt.figure(2)
        plt.imshow(np.reshape(im_vals[:, :, j], (N)),
                   interpolation='nearest',
                   clim=(0, 1))
Exemplo n.º 12
0
 
 if (j!=0) and (locSteps[j]!=0):
     kpad = tf.zpad(kStp[0],np.array(kSub.shape[-2:]).astype(int))
     data_dc = np.fft.fftshift(tf.zpad(np.ones(kStp.shape[-2:])*dataStp[0], np.array(kSub.shape[-2:]).astype(int)) + (1-kpad)*np.fft.fftshift(dataSub))
     im_dcSub = tf.ifft2c(data_dc[i,:,:] / np.fft.ifftshift(pdfDiv), ph=ph_scanSub[i,:,:]).real.copy().reshape(N_imSub)
 imdcs = [im_dcSub] #,np.zeros(N_im),np.ones(N_im),np.random.randn(np.prod(N_im)).reshape(N_im)]
 for i in range(len(imdcs)):
     wdcs.append(tf.wt(imdcs[i][0].real,wavelet,mode,dimsSub,dimOptSub,dimLenOptSub)[0].reshape(NSub))
     
 
 
 for kk in range(len(wdcs)):
     w_dc = wdcs[kk]
     print(mets[kk])
     args = (NSub, N_imSub, szFull, dimsSub, dimOptSub, dimLenOptSub, TV[j], XFM[j], dataSub, kSub, strtag, ph_scanSub, 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[j], 'TVWeight': TV[j], 'XFMWeight': XFM[j], 'N': NSub})
     #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']
         ##import pdb; pdb.set_trace()
         #stps.append(w_dc)
         #tvStps.append(TV[i])
         #w_stp.append(w_dc.reshape(NSub))
         #imStp.append(tf.iwt(w_stp[-1][0],wavelet,mode,dimsSub,dimOptSub,dimLenOptSub))
         ##plt.imshow(imStp[-1]); plt.colorbar(); plt.show()
         ##w_dc = w_stp[k].flatten()
         #stps.append(w_dc)
         #wdcHold = w_dc.reshape(NSub)
Exemplo n.º 13
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()
Exemplo n.º 14
0
$ ipython --pylab

Python 2.7.4 (default, Apr 19 2013, 18:28:01)
Type "copyright", "credits" or "license" for more information.

IPython 0.13.2 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

Welcome to pylab, a matplotlib-based Python environment [backend: Agg].
For more information, type 'help(pylab)'.

In [1]: from scipy import special, optimize

In [2]: f = lambda x: -special.jv(3, x)

In [3]: sol = optimize.minimize(f, 1.0)

In [4]: x = linspace(0, 10, 5000)

In [5]: x
Out[5]:
array([  0.00000000e+00,   2.00040008e-03,   4.00080016e-03, ...,
         9.99599920e+00,   9.99799960e+00,   1.00000000e+01])

In [6]: plot(x, special.jv(3, x), '-', sol.x, -sol.fun, 'o')

In [7]: savefig('plot.png', dpi=96)
wdcs = []


for i in range(len(imdcs)):
    wdcs.append(tf.wt(imdcs[i][0].real,wavelet,mode,dims,dimOpt,dimLenOpt)[0].reshape(N))

ims = []
stps = []
tvStps = []
#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']
            stps.append(w_dc)
            tvStps.append(TV[i])
            
            
    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)
Exemplo n.º 16
0
# Optimization algortihm -- this is where everything culminates together
#M, dIM, Ause, inds = dirInfo

for i in range(len(TV)):
    args = (N, TV[i], XFM[i], data_b1, k, strtag, ph_b1, dirWeight, dirs,
            dirInfo, nmins, wavelet, mode, a)
    im_result = opt.minimize(optfun,
                             im_dc,
                             args=args,
                             method=method,
                             jac=derivative_fun,
                             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(im_result['x'])):
        print('Some nan' 's found. Dropping TV and XFM values')
    else:
        im_dc = im_result['x'].reshape(N)
        alpha_k = im_result['alpha_k']
Exemplo n.º 17
0
    def load_layer(self):

        layers = self.iface.legendInterface().layers()

        #for layer in layers:

        #pop_feat, pop_attr = self.extract_features(layer.getFeatures())
        #print pop_feat

        celllayer = QgsVectorLayer("/home/kiran/Dropbox/cell.shp", "celltower",
                                   "ogr")
        cell_feat, cell_attr = self.extract_features(celllayer.getFeatures())
        cell_feat = [list(elem) for elem in cell_feat]
        attr_cell = []
        for attr in cell_attr:
            attr_cell.append(int(attr[1]))
        print cell_feat

        poplayer = QgsVectorLayer("/home/kiran/Dropbox/pop.shp", "population",
                                  "ogr")
        pop_feat, pop_attr = self.extract_features(poplayer.getFeatures())
        pop_feat = [list(elem) for elem in pop_feat]
        attr_pop = []
        for attr in pop_attr:
            attr_pop.append(int(attr[1]))
        print pop_feat

        elevlayer = QgsVectorLayer("/home/kiran/Dropbox/elev.shp", "elevation",
                                   "ogr")
        elev_feat, elev_attr = self.extract_features(elevlayer.getFeatures())
        elev_feat = [list(elem) for elem in elev_feat]
        attr_elev = []
        for attr in elev_attr:
            attr_elev.append(int(attr[1]))
        print elev_feat

        landlayer = QgsVectorLayer("/home/kiran/Dropbox/land.shp", "landcost",
                                   "ogr")
        land_feat, land_attr = self.extract_features(landlayer.getFeatures())
        attr_land = []
        for attr in land_attr:
            attr_land.append(int(attr[1]))

        cost_feat = []
        for each in land_feat:
            each = each[0]
            land_list = [list(elem) for elem in each]
            cost_feat.append(land_list)
        print cost_feat

        geomx = []
        geomy = []
        for geom in pop_feat:
            geomx.append(geom[0])
            geomy.append(geom[1])
        guess = [(sum(geomx) / len(geomx)), (sum(geomy) / len(geomy))]

        ret = optimize.minimize(guess, cell_feat, attr_cell, pop_feat,
                                attr_pop, elev_feat, attr_elev, cost_feat,
                                attr_land)
        #ret = optimize.testfun(guess)

        ##Draw the optimal location of cell tower
        newlayer = QgsVectorLayer("/home/kiran/Dropbox/new.shp",
                                  "optimal_tower", "ogr")
        self.draw_point(newlayer, ret)
        print "optimal location is"
        print ret