Beispiel #1
0
def pseudospectral(problem):
    """  solution = pseudospectral(problem,options)
         integrate a Segment using Chebyshev pseudospectral method
         
         Inputs:
         
         Outputs:
         
         Assumptions:
         
         
    """

    # initialize probme
    problem.initialize()

    # check initial state
    check_initial_state(problem)

    # create "raw" Chebyshev data, t in range [0,1]
    N = problem.options.N
    t, D, I = chebyshev_data(N)
    problem.numerics.t = t
    problem.numerics.D = D
    problem.numerics.I = I

    # solve system
    solution = root(
        segment_residuals,
        problem.guess,
        args=problem,
        method="hybr",
        # jac    = jacobian_complex ,
        tol=problem.options.tol_solution,
    )

    # confirm final solution
    residuals(solution.x, problem)

    # pack solution
    problem.solution(solution.x)

    return
Beispiel #2
0
def pseudospectral(problem):
    """  solution = pseudospectral(problem,options)
         integrate a Segment using Chebyshev pseudospectral method
         
         Inputs:
         
         Outputs:
         
         Assumptions:
         
         
    """

    # initialize probme
    problem.initialize()

    # check initial state
    check_initial_state(problem)

    # create "raw" Chebyshev data, t in range [0,1]
    N = problem.options.N
    t, D, I = chebyshev_data(N)
    problem.numerics.t = t
    problem.numerics.D = D
    problem.numerics.I = I

    # solve system
    solution = root(
        segment_residuals,
        problem.guess,
        args=problem,
        method="hybr",
        #jac    = jacobian_complex ,
        tol=problem.options.tol_solution)

    # confirm final solution
    residuals(solution.x, problem)

    # pack solution
    problem.solution(solution.x)

    return
Beispiel #3
0
def jacobian_complex(x,problem):

    # Jacobian via complex step 
    problem.complex = True
    h = 1e-12; N = len(x)
    J = np.zeros((N,N))

    for i in xrange(N):

        xi = x + 0j
        xi[i] = np.complex(x[i],h)
        R = residuals(xi,problem)
        J[:,i] = np.imag(R)/h

    problem.complex = False
    return J
Beispiel #4
0
def jacobian_AD(x,problem):

    xi = ad(x,np.eye(len(x)))
    J = jacobian(residuals(xi,problem))

    return J
Beispiel #5
0
def qp(x, Q, c, C, d, A, b, maxiter):

    # Set leading dimension of A (number of equality constraints), C (number of inequality constraints), Q (number of assets)
    mA = len(A)
    mC = len(C)
    n = len(Q)

    # Initialize algorithm parameters: iteration count, tolerance level, step size, dampening, and centering power
    iter = 0
    eps = 1e-8
    alpha = 1
    eta = 0.99
    tau = 3

    # Initialize Lagrange multipliers, slackness condition, e, residuals, mu (complementary level), and sigma (centering level)
    y = np.ones((mA, 1))
    z = np.ones((mC, 1))
    s = np.ones((mC, 1))
    e = np.ones((mC, 1))
    rQ, rA, rC, rsz = residuals(x, y, z, s, Q, c, C, d, A, b)
    mu = np.dot(s.T, z) / mC
    sigma = 0.5

    while (iter <= maxiter and np.linalg.norm(rQ) >= eps
           and np.linalg.norm(rA) >= eps and np.linalg.norm(rC) >= eps
           and np.abs(mu) >= eps):

        # Set S, Z, S^(-1), Z^(-1) by diagonalizing s and z
        S = np.diag(s.T.flatten().tolist())
        Z = np.diag(z.T.flatten().tolist())
        Sinv = np.linalg.inv(S)
        Zinv = np.linalg.inv(Z)

        # Solve for dx_a, dy_a, dz_a, ds_a using LU decomposition/solver
        lhs = np.vstack(( np.hstack(( Q,-A.T,-C.T,np.zeros((n,mC)) )), \
        np.hstack(( A, np.zeros((mA,mA)), np.zeros((mA,mC)), np.zeros((mA,mC)) )), \
        np.hstack(( C, np.zeros((mC,mA)), np.zeros((mC,mC)), -np.eye(mC) )), \
        np.hstack(( np.zeros((mC,n)), np.zeros((mC,mA)), S, Z )) ))
        rhs = -np.vstack((rQ, rA, rC, rsz))
        dxyzs_a, L, U, P = lusolve(lhs, rhs)
        dx_a = dxyzs_a[0:n]
        dy_a = dxyzs_a[n:n + mA]
        dz_a = dxyzs_a[n + mA:n + mA + mC]
        ds_a = dxyzs_a[n + mA + mC:n + mA + mC + mC]

        # Compute alpha_a to be the largest value in (0,1] such that
        alpha_a, alphaz_a, alphas_a = steplength(z, s, dz_a, ds_a, eta)

        # Set mu_a and sigma_a
        mu_a = np.dot((z + alpha_a * dz_a).T, (s + alpha_a * ds_a)) / mC
        sigma = (mu_a / mu)**tau

        # Solve system for dx, dy, dz, ds
        rsz = rsz - sigma * mu * e + dz_a * ds_a
        rhs = -np.vstack((rQ, rA, rC, rsz))
        dxyzs, L, U, P = lusolve(lhs, rhs)
        dx = dxyzs[0:n]
        dy = dxyzs[n:n + mA]
        dz = dxyzs[n + mA:n + mA + mC]
        ds = dxyzs[n + mA + mC:n + mA + mC + mC]

        # Compute alpha to be the largest value in (0,1] such that
        alpha, alphaz, alphas = steplength(z, s, dz, ds, eta)

        # Update x, z, s, rQ, rA, rC, rsz, and mu
        x = x + alpha * dx
        y = y + alpha * dy
        z = z + alpha * dz
        s = s + alpha * ds
        rQ, rA, rC, rsz = residuals(x, y, z, s, Q, c, C, d, A, b)
        mu = np.dot(s.T, z) / mC

        # Iteration count
        iter = iter + 1

    xstar = x
    ystar = y
    zstar = z
    sstar = s

    return xstar, ystar, zstar, sstar
Beispiel #6
0
def hp(s, C, T, Methods, Index, Reg_L1, Reg_L2, Reg_C, Reg_S, Bounds, Nz, LCurve = False):
    """Returns heatmap

    s – s-domain points(time)
    C - transient F(s) = C
    T - Tempetarures

    Methods – name of methods to process dataset
    Index – index to plot specific slise of heatplot
    Reg_L1, Reg_L2 – reg. parameters for L1 and L2 routines
    Bounds – list of left and right bounds of s-domain points
    Nz – int value which is lenght of calculated vector
    """

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib import cm
    from matplotlib import gridspec
    from L1 import L1
    from L1_FISTA import l1_fista
    from L2 import L2
    from L1L2 import L1L2
    from ilt import Contin
    from reSpect import reSpect, InitializeH, getAmatrix, getBmatrix, oldLamC, getH, jacobianLM, kernelD, guiFurnishGlobals
    from residuals import residuals

    import sys

    def progressbar(i, iterations):
        i = i + 1
        sys.stdout.write('\r')
        # the exact output you're looking for:
        sys.stdout.write("[%-20s] %d%%  Building Heatmap" % ('#'*np.ceil(i*100/iterations*0.2).astype('int'), np.ceil(i*100/iterations)))
        sys.stdout.flush()

    cut = len(T)
    cus = Nz

    if len(Methods) > 1:
        print('Choose only one Method')
        Methods = Methods[0]

    XZ = []
    YZ = []
    ZZ = []

    for M in Methods:
        if M == 'L1':
            for i in range(0, cut):
                YZ.append(np.ones(cus)*T[i])
                TEMPE, TEMPX, a = l1_fista(s, C[i], Bounds, Nz, Reg_L1)
                XZ.append(TEMPE)
                ZZ.append(TEMPX*TEMPE)

                progressbar(i, cut)

        elif M == 'L2':
            for i in range(0, cut):
                YZ.append(np.ones(cus)*T[i])
                TEMPE, TEMPX, a = L2(s, C[i], Bounds, Nz, Reg_L2)
                XZ.append(TEMPE)
                ZZ.append(TEMPX*TEMPE)

                progressbar(i, cut)

        elif M == 'L1+L2':
            for i in range(0, cut):
                YZ.append(np.ones(cus)*T[i])
                TEMPE, TEMPX, a = L1L2(s, C[i], Bounds, Nz, Reg_L1, Reg_L2)
                XZ.append(TEMPE)
                ZZ.append(TEMPX*TEMPE)

                progressbar(i, cut)

        elif M == 'Contin':
            for i in range(0, cut):
                YZ.append(np.ones(cus)*T[i])
                if LCurve:
                    ay = 0
                    Reg_C = residuals(s, C[i], ay, Methods, Reg_L1, Reg_L2, Reg_C, Reg_S, Bounds, Nz, LCurve)
                TEMPE, TEMPX, a = Contin(s, C[i], Bounds, Nz, Reg_C)
                #print(YZ[-1][0], 'K; a = ', Reg_C)
                XZ.append(TEMPE)
                ZZ.append(TEMPX*TEMPE)

                progressbar(i, cut)

        elif M == 'reSpect':
            for i in range(0, cut):
                YZ.append(np.ones(cus)*T[i])
                if LCurve:
                    ay = 0
                    Reg_S = residuals(s, C[i], ay, Methods, Reg_L1, Reg_L2, Reg_C, Reg_S, Bounds, Nz, LCurve)
                TEMPE, TEMPX, a = reSpect(s, C[i], Bounds, Nz, Reg_S)
                #print(YZ[-1][0], 'K; a = ', Reg_C)
                XZ.append(TEMPE)
                ZZ.append(TEMPX)

                progressbar(i, cut)



    XZ = np.asarray(XZ)
    YZ = np.asarray(YZ)
    ZZ = np.asarray(ZZ)

    fig = plt.figure(figsize = (12,4.5))
    gs = gridspec.GridSpec(1, 2, width_ratios=[3, 1])
    a2d = fig.add_subplot(121)

    #cmap = cm.gnuplot
    cmap = cm.bwr

    v = np.amax(np.abs(ZZ))/5
    if Methods[0] == 'reSpect':
        v = np.average(np.abs(ZZ[10:-10,10:-10]))

    normalize = plt.Normalize(vmin = -v, vmax = v)

    extent = [np.log10(Bounds[0]), np.log10(Bounds[1]), (T[-1]), (T[0])]
    a2d.set_xlabel(r'Emission $\log_{10}{(e)}$')
    a2d.set_title(Methods[0])
    a2d.set_ylabel('Temperature T, K')
    #a2d.grid(True)



    pos = a2d.imshow(ZZ[::1,::1], cmap = cmap,
               norm = normalize, interpolation = 'none',
               aspect = 'auto', extent = extent)
    plt.colorbar(pos)

    from matplotlib.ticker import FormatStrFormatter
    a2d.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
    plt.xticks(np.arange(np.log10(TEMPE[0]),np.log10(TEMPE[-1]), 0.9999))
    plt.yticks(np.arange(T[0], T[-1], 20.0))
    #plt.yticks(np.arange(T[0], T[-1], 20.0))

    ad = fig.add_subplot(122)
    ad.set_xlabel('Temperature, K')
    ad.set_ylabel('LDLTS signal, arb. units')
    for i in range(int(len(TEMPE)*0.1), int(len(TEMPE)*0.8), 20):
        #ad.plot(T, ZZ[:, i], label=r'$\tau = %.3f s$'%(1/TEMPE[i]))
        ad.plot(T, ZZ[:, i]/np.amax(ZZ[:,i]), label=r'$\tau = %.3f s$'%(1/TEMPE[i]))
    #ad.set_yscale('log')
    #ad.set_ylim(1E-4, 10)
    ad.grid()
    ad.legend()

    plt.show()
    plt.tight_layout()

    ##save file
    #Table = []
    #Table.append([0] + (1/TEMPE).tolist())
    #for i in range(cut):
    #    Table.append([T[i]] + (ZZ[i,:]).tolist())

    Table = []
    e = 1/TEMPE
    Table.append([0] + e.tolist())
    for i in range(cut):
        Table.append([T[i]] + (ZZ[i,:]).tolist())


    #print(Table)
    #Table = np.asarray(Table)

    np.savetxt('SAMPLE_NAME'%((s[1]-s[0])*1000) +'_1'+'.LDLTS', Table, delimiter='\t', fmt = '%4E')
Beispiel #7
0
def qp(x, Q, c, C, d, A, b, maxiter):

    # Set leading dimension of A (number of equality constraints), C (number of inequality constraints), Q (number of assets)
    mA = len(A)
    mC = len(C)
    n = len(Q)

    # Initialize algorithm parameters: iteration count, tolerance level, step size, dampening, and centering power
    iter = 0
    eps = 1e-8
    alpha = 1
    eta = 0.99
    tau = 3

    # Initialize Lagrange multipliers, slackness condition, e, residuals, mu (complementary level), and sigma (centering level)
    y = np.ones((mA,1))
    z = np.ones((mC,1))
    s = np.ones((mC,1))
    e = np.ones((mC,1))
    rQ, rA, rC, rsz = residuals(x, y, z, s, Q, c, C, d, A, b)
    mu = np.dot(s.T,z)/mC
    sigma = 0.5

    while (iter<=maxiter and np.linalg.norm(rQ)>=eps and np.linalg.norm(rA)>=eps and np.linalg.norm(rC)>=eps and np.abs(mu)>=eps):

        # Set S, Z, S^(-1), Z^(-1) by diagonalizing s and z
        S = np.diag(s.T.flatten().tolist())
        Z = np.diag(z.T.flatten().tolist())
        Sinv = np.linalg.inv(S)
        Zinv = np.linalg.inv(Z)

        # Solve for dx_a, dy_a, dz_a, ds_a using LU decomposition/solver
        lhs = np.vstack(( np.hstack(( Q,-A.T,-C.T,np.zeros((n,mC)) )), \
        np.hstack(( A, np.zeros((mA,mA)), np.zeros((mA,mC)), np.zeros((mA,mC)) )), \
        np.hstack(( C, np.zeros((mC,mA)), np.zeros((mC,mC)), -np.eye(mC) )), \
        np.hstack(( np.zeros((mC,n)), np.zeros((mC,mA)), S, Z )) ))
        rhs = -np.vstack((rQ,rA,rC,rsz))
        dxyzs_a, L, U, P = lusolve(lhs,rhs)
        dx_a = dxyzs_a[0:n]
        dy_a = dxyzs_a[n:n+mA]
        dz_a = dxyzs_a[n+mA:n+mA+mC]
        ds_a = dxyzs_a[n+mA+mC:n+mA+mC+mC]

        # Compute alpha_a to be the largest value in (0,1] such that
        alpha_a, alphaz_a, alphas_a = steplength(z, s, dz_a, ds_a, eta)

        # Set mu_a and sigma_a
        mu_a = np.dot((z + alpha_a*dz_a).T,(s + alpha_a*ds_a))/mC
        sigma = (mu_a/mu)**tau

        # Solve system for dx, dy, dz, ds
        rsz = rsz - sigma*mu*e + dz_a*ds_a
        rhs = -np.vstack((rQ,rA,rC,rsz))
        dxyzs, L, U, P = lusolve(lhs,rhs)
        dx = dxyzs[0:n]
        dy = dxyzs[n:n+mA]
        dz = dxyzs[n+mA:n+mA+mC]
        ds = dxyzs[n+mA+mC:n+mA+mC+mC]

        # Compute alpha to be the largest value in (0,1] such that
        alpha, alphaz, alphas = steplength(z, s, dz, ds, eta)

        # Update x, z, s, rQ, rA, rC, rsz, and mu
        x = x + alpha*dx
        y = y + alpha*dy
        z = z + alpha*dz
        s = s + alpha*ds
        rQ, rA, rC, rsz = residuals(x, y, z, s, Q, c, C, d, A, b)
        mu = np.dot(s.T,z)/mC

        # Iteration count
        iter = iter + 1

    xstar = x
    ystar = y
    zstar = z
    sstar = s

    return xstar, ystar, zstar, sstar
Beispiel #8
0
import sys
sys.path.append('../')
from residuals import residuals
"""
Test class for residuals module
"""
"""
Test 1
"""
print('Test 1')
# Should return only Y's
x = "XXXXXYYYYXXXXYYYYYY"
inds = [[0, 5], [9, 13]]
res = residuals(x)
res.getResiduals(inds)
print(res.residuals)

inds = [[0, 4], [0, 5], [1, 3], [9, 9], [10, 10], [11, 13]]
res = residuals(x)
res.getResiduals(inds)
print(res.residuals)

res = residuals(x)
res.getResiduals(inds[::-1])
print(res.residuals)
"""
Test 2
"""
print('Test 2')
x = "YYYYXYYYY"
inds = [[4, 4], [4, 4]]