Example #1
0
def calc_brush_height(x, phi):
    '''
    The brush height is defined as:
        h = <x> = \int_{x*phi(x)dx}/\int_{phi(x)dx}
    '''
    I1 = cheb_quadrature_clencurt(x[:, 0] * phi)
    I2 = cheb_quadrature_clencurt(phi)
    return I1 / I2
Example #2
0
def test_quadrature_clencurt():
    '''
    Four funcitons in [-1, 1] are tested:
        f(x) = |x|^3,       I = .5
        f(x) = exp(-x^(-2)),   I = 2*(exp(-1) + sqrt(pi)*(erf(1) - 1))
        f(x) = 1/(1+x^2),   I = pi/2
        f(x) = x^10,        I = 2/11
    '''

    Nmax = 25
    xN = np.arange(2, Nmax + 1)
    E1 = np.zeros(Nmax - 1)
    I1 = .5
    E2 = np.zeros(Nmax - 1)
    I2 = 2 * (np.exp(-1) + np.sqrt(np.pi) * (erf(1) - 1))
    E3 = np.zeros(Nmax - 1)
    I3 = .5 * np.pi
    E4 = np.zeros(Nmax - 1)
    I4 = 2. / 11
    for N in xrange(2, Nmax + 1):
        theta = np.arange(N + 1) * np.pi / N
        x = np.cos(theta)
        f1 = np.abs(x)**3
        E1[N - 2] = np.abs(cheb_quadrature_clencurt(f1) - I1)
        f2 = np.exp(-x**(-2))
        E2[N - 2] = np.abs(cheb_quadrature_clencurt(f2) - I2)
        f3 = 1. / (1 + x**2)
        E3[N - 2] = np.abs(cheb_quadrature_clencurt(f3) - I3)
        f4 = x**10
        E4[N - 2] = np.abs(cheb_quadrature_clencurt(f4) - I4)

    plt.semilogy(xN, E1 + 1e-100, '.')
    plt.semilogy(xN, E1 + 1e-100)
    plt.axis([0, Nmax + 2, 1e-18, 1e3])
    plt.grid('on')
    plt.show()

    plt.semilogy(xN, E2 + 1e-100, '.')
    plt.semilogy(xN, E2 + 1e-100)
    plt.axis([0, Nmax + 2, 1e-18, 1e3])
    plt.grid('on')
    plt.show()

    plt.semilogy(xN, E3 + 1e-100, '.')
    plt.semilogy(xN, E3 + 1e-100)
    plt.axis([0, Nmax + 2, 1e-18, 1e3])
    plt.grid('on')
    plt.show()

    plt.semilogy(xN, E4 + 1e-100, '.')
    plt.semilogy(xN, E4 + 1e-100)
    plt.axis([0, Nmax + 2, 1e-18, 1e3])
    plt.grid('on')
    plt.show()
Example #3
0
def test_exact_neumann_dirichlet():
    L = 10

    N = 128
    Ns = 200 + 1 #20000 + 1
    algo = 1
    scheme = 1

    W, u0, x = init_chebyshev_fredrikson(N, L)
    u0[0] = 0.

    print 'ETDRK4 N = ', N, ' Ns = ', Ns-1
    #q3, x3 = cheb_mde_neumann_dirichlet_etdrk4(W, u0, L, Ns, algo, scheme)
    lbc = BC('Neumann')
    rbc = BC('Dirichlet')
    etdrk4_solver = ETDRK4(L, N, Ns, h=None, lbc=lbc, rbc=rbc)
    q3, x3 = etdrk4_solver.solve(W, u0)
    Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
    if scheme == 0:
        #data_name = 'benchmark/NBC-DBC/exact/ETDRK4_Cox_N' 
        data_name = 'ETDRK4_Cox_N' 
        data_name = data_name + str(N) + '_Ns' + str(Ns-1)
    else:
        #data_name = 'benchmark/NBC-DBC/exact/ETDRK4_Krogstad_N' 
        data_name = 'ETDRK4_Krogstad_N' 
        data_name = data_name + str(N) + '_Ns' + str(Ns-1)
    savemat(data_name,{
            'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
            'x':x, 'q':q3, 'Q':Q3})
    plt.plot(x3, q3, 'r')
    plt.axis([0, 10, 0, 1.15])
    plt.xlabel('$z$')
    plt.ylabel('$q(z)$')
    plt.savefig(data_name, bbox_inches='tight')
    plt.show()
Example #4
0
def test_cheb_mde_dirichlet():
    L = 10
    Ns = 200 + 1

    print 'test_cheb_mde_dirichlet'

    N = 32
    W, u0, x = init_fourier(N, L)
    u0[0] = 0.
    u0[N] = 0.
    print 'OSS N = ', N, ' Ns= ', Ns - 1
    #plt.plot(x, W)
    #plt.axis([0, 10, -1.1, 1.1])
    #plt.show()
    q1, x1 = cheb_mde_oss(W, u0, L, Ns)
    Q1 = L * oss_integral_weights(q1)

    N = 32
    W, u0, x2 = init_chebyshev(N, L)
    u0[0] = 0
    u0[N] = 0
    print 'OSCHEB N = ', N, ' Ns= ', Ns - 1
    #plt.plot(x, W)
    #plt.axis([0, 10, -1.1, 1.1,])
    #plt.show()
    q2 = cheb_mde_dirichlet_oscheb(W, u0, L, Ns)
    Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)

    N = 32
    Ns = 200 + 1
    algo = 1
    scheme = 1
    W, u0, x = init_chebyshev(N, L)
    u0[0] = 0
    u0[N] = 0
    print 'ETDRK4 N = ', N, ' Ns= ', Ns - 1
    q3, x3 = cheb_mde_dirichlet_etdrk4(W, u0, L, Ns, algo, scheme)
    Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)

    plt.plot(x1, q1, 'b')
    plt.plot(x2, q2, 'g')
    plt.plot(x3, q3, 'r')
    plt.axis([0, 10, 0, 1.15])
    plt.show()
Example #5
0
def matching_force_by_linear_least_square(basis_set, target):
    '''
    Perform force matching by linear least square method.
        X * K = R
    where K is a vector of fitted coefficients, R is a vector, and X is a matrix. R and X can be constructed from the input basis and target.
    In particular,
        X_{ij} = \int dx basis[i]*basis[j]
        R_i = \int dx basis[i]*target
    '''
    n = len(basis_set)
    X = np.zeros( (n,n) )
    R = np.zeros(n)
    for i in xrange(n):
        R[i] = 0.5*cheb_quadrature_clencurt(basis_set[i] * target)
        for j in xrange(n):
            X[i,j] = 0.5*cheb_quadrature_clencurt(basis_set[i] * basis_set[j])
    print 'X =', X
    print 'R =', R
    return np.linalg.solve(X, R)
Example #6
0
def test_exact_robin():
    L = 10

    N = 128
    Ns = 20000 + 1
    ka = -1. * L
    kb = 1.5 * L
    algo = 1
    scheme = 1

    W, u0, x = init_chebyshev(N, L)

    print 'ETDRK4 N = ', N, ' Ns = ', Ns - 1
    q3, x3 = cheb_mde_robin_etdrk4(W, u0, L, Ns, ka, kb, algo, scheme)
    Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
    if scheme == 0:
        data_name = 'benchmark/RBC-RBC/exact/ETDRK4_Cox_N'
        data_name = data_name + str(N) + '_Ns' + str(Ns - 1)
    else:
        data_name = 'benchmark/RBC-RBC/exact/ETDRK4_Krogstad_N'
        data_name = data_name + str(N) + '_Ns' + str(Ns - 1)
    savemat(data_name, {
        'N': N,
        'Ns': Ns - 1,
        'W': W,
        'u0': u0,
        'Lz': L,
        'x': x,
        'q': q3,
        'Q': Q3
    })
    plt.plot(x3, q3, 'r')
    plt.axis([0, 10, 0, 1.15])
    plt.xlabel('$z$')
    plt.ylabel('$q(z)$')
    plt.savefig(data_name, bbox_inches='tight')
    plt.show()
Example #7
0
def plot(path, data):
    skipfiles = []
    datafiles = list_datafile(path, data)
    datafiles.sort()
    for f in skipfiles:
        for df in datafiles:
            p = os.path.dirname(df)
            d = os.path.basename(p)
            if d == f:
                datafiles.remove(df)
    Fs = []
    labels = []
    labels_tex = []

    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)  # F vs t
    fig2 = plt.figure()
    ax2 = fig2.add_subplot(111)  # F vs time
    fig3 = plt.figure()
    ax3 = fig3.add_subplot(111)  # err_res vs t
    fig4 = plt.figure()
    ax4 = fig4.add_subplot(111)  # err_res vs time
    fig5 = plt.figure()
    ax5 = fig5.add_subplot(111)  # err_phi vs t
    fig6 = plt.figure()
    ax6 = fig6.add_subplot(111)  # err_phi vs time
    fig7 = plt.figure()
    ax7 = fig7.add_subplot(111)  # err_F vs t
    fig8 = plt.figure()
    ax8 = fig8.add_subplot(111)  # err_F vs time

    for dfile in datafiles:
        mat = loadmat(dfile)
        p = os.path.dirname(dfile)
        label = os.path.basename(p)
        print label
        t, time, F = mat['t'], mat['time'], mat['F']
        t = t.reshape(t.size)
        time = time.reshape(time.size)
        F = F.reshape(F.size)
        err_res = mat['err_residual']
        err_res = err_res.reshape(err_res.size)
        try:
            err_phi = mat['err_phi']
        except:
            err_phi = np.ones_like(err_res)
        err_phi = err_phi.reshape(err_phi.size)
        for i in xrange(t.size):
            if t[i] == 0:
                imax = i
                break
        t = t[:imax]
        time = time[:imax]
        F = F[:imax]
        err_res = err_res[:imax]
        err_phi = err_phi[:imax]
        err_F = F[1:] - F[:-1]
        Fs.append(F[-1])
        labels.append(label)
        phiA_meanx = np.mean(mat['phiA'], axis=0)
        phiA_meanxy = np.mean(phiA_meanx, axis=0)
        phiA_mean = 0.5 * cheb_quadrature_clencurt(phiA_meanxy)
        print '\t', str(F[-1]), '\t', str(t[-1]), '\t', str(time[-1]),
        print '\t', str(phiA_mean)
        print '\t', str(err_res[-1])
        label = '$' + label + '$'
        labels_tex.append(label)
        ax1.plot(t, F, label=label)
        ax2.plot(time, F, label=label)
        ax3.plot(t, err_res, label=label)
        ax4.plot(time, err_res, label=label)
        ax5.plot(t, err_phi, label=label)
        ax6.plot(time, err_phi, label=label)
        ax7.plot(t[1:], np.abs(err_F), label=label)
        ax8.plot(time[1:], np.abs(err_F), label=label)

    datafile = os.path.join(path, 'data.mat')
    savemat(datafile, {'labels': labels, 'F': Fs})

    ax3.set_yscale('log')
    ax4.set_yscale('log')
    ax5.set_yscale('log')
    ax6.set_yscale('log')
    ax7.set_xscale('log')
    ax7.set_yscale('log')
    ax8.set_xscale('log')
    ax8.set_yscale('log')
    ax1.legend(loc='best')
    ax2.legend(loc='best')
    ax3.legend(loc='best')
    ax4.legend(loc='best')
    ax5.legend(loc='best')
    ax6.legend(loc='best')
    ax7.legend(loc='best')
    ax8.legend(loc='best')

    figfile = os.path.join(path, 'F-t.eps')
    fig1.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'F-time.eps')
    fig2.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'err_res-t.eps')
    fig3.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'err_res-time.eps')
    fig4.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'err_phi-t.eps')
    fig5.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'err_phi-time.eps')
    fig6.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'err_F-t.eps')
    fig7.savefig(figfile, format='eps', bbox_inches='tight')
    figfile = os.path.join(path, 'err_F-time.eps')
    fig8.savefig(figfile, format='eps', bbox_inches='tight')
    plt.close('all')

    x = np.arange(len(datafiles))
    Fs = np.array(Fs)
    fig9 = plt.figure(figsize=[10, 3])
    ax9 = fig9.add_subplot(111)  # F vs test
    ax9.plot(x, Fs, 'o')
    #plt.xscale('log')
    plt.xticks(x, labels_tex)
    figfile = os.path.join(path, 'F-all.eps')
    fig9.savefig(figfile, format='eps', bbox_inches='tight')
    plt.close()
Example #8
0
def test_N_dirichlet():
    '''
    1 OSS
    2 OSCHEB
    3 ETDRK4
    '''
    err_mode = 1  # 0: max(|q-q_ref|)/max(q_ref); 1: |Q - Q_ref|/|Q_ref|
    L = 10
    N1 = 2
    N2 = 2048
    N3 = 2
    Ns1 = 100000 + 1
    Ns2 = 100000 + 1
    Ns3 = 100000 + 1
    algo3 = 1  # 0: circular, 1: hyperbolic, 2: scaling and squaring
    scheme = 1  # 0: Cox-Matthews, 2: Krogstad
    data_name = 'benchmark/N_DBC_Ns' + str(Ns1 - 1) + '_hyperbolic'
    print data_name

    oscheb_ref = 'benchmark/exact/OSCHEB_N'
    oscheb_ref = oscheb_ref + '8192_Ns200000.mat'
    mat = loadmat(oscheb_ref)
    q2_ref = mat['q']
    Q2_ref = mat['Q'][0, 0]
    N2_ref = mat['N']
    Ns2_ref = mat['Ns']

    #oss_ref = 'benchmark/exact/OSS_N'
    #oss_ref = oss_ref + '4096_Ns100000.mat'
    oss_ref = oscheb_ref
    mat = loadmat(oss_ref)
    q1_ref = mat['q']
    Q1_ref = mat['Q'][0, 0]
    N1_ref = mat['N']
    Ns1_ref = mat['Ns']

    #if scheme == 0:
    #    etdrk4_ref = 'benchmark/exact/CoxMatthews/ETDRK4_N'
    #elif scheme == 1:
    #    etdrk4_ref = 'benchmark/exact/Krogstad/ETDRK4_N'
    #else:
    #    raise ValueError('No such scheme!')
    #etdrk4_ref = etdrk4_ref + '256_Ns100000.mat'
    etdrk4_ref = oscheb_ref
    mat = loadmat(etdrk4_ref)
    q3_ref = mat['q']
    Q3_ref = mat['Q'][0, 0]
    N3_ref = mat['N']
    Ns3_ref = mat['Ns']

    print 'OSS'
    errs1 = []
    Qs1 = []
    NN1 = []
    n_max = int(np.log2(N1))  # N_max = 2^{n_max - 1}
    for N in np.power(2, np.arange(4, n_max)).astype(int):
        W, u0, x = init_fourier(N, L)
        u0[0] = 0.
        u0[-1] = 0.
        q1, x1 = cheb_mde_oss(W, u0, L, Ns1)
        Q1 = L * oss_integral_weights(q1)

        err1 = np.abs(Q1 - Q1_ref) / np.abs(Q1_ref)
        NN1.append(N)
        Qs1.append(Q1)
        errs1.append(err1)
        print N, '\t', err1

    print 'OSCHEB'
    errs2 = []
    Qs2 = []
    NN2 = []
    n_max = int(np.log2(N2))  # N_max = 2^{n_max - 1}
    for N in np.power(2, np.arange(4, n_max)).astype(int):
        W, u0, x = init_chebyshev(N, L)
        u0[0] = 0.
        u0[-1] = 0.
        q2 = cheb_mde_dirichlet_oscheb(W, u0, L, Ns2)
        Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)

        err2 = np.abs(Q2 - Q2_ref) / np.abs(Q2_ref)
        NN2.append(N)
        Qs2.append(Q2)
        errs2.append(err2)
        print N, '\t', err2

    print 'ETDRK4'
    errs3 = []
    Qs3 = []
    NN3 = []
    n_max = int(np.log2(N3))  # N_max = 2^{n_max - 1}
    for N in np.power(2, np.linspace(4, 7.6, 0)).astype(int):
        N = int(N)

        W, u0, x = init_chebyshev(N, L)
        u0[0] = 0.
        u0[-1] = 0.
        q3, x3 = cheb_mde_dirichlet_etdrk4(W, u0, L, Ns3, algo3, scheme)
        Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)

        err3 = np.abs(Q3 - Q3_ref) / np.abs(Q3_ref)
        NN3.append(N)
        Qs3.append(Q3)
        errs3.append(err3)
        print N, '\t', err3

    savemat(
        data_name, {
            'N_ref1': N1_ref,
            'N_ref2': N2_ref,
            'N_ref3': N3_ref,
            'Ns1': Ns1 - 1,
            'Ns2': Ns2 - 1,
            'Ns3': Ns3 - 1,
            'Ns1_ref': Ns1_ref,
            'Ns2_ref': Ns2_ref,
            'Ns3_ref': Ns3_ref,
            'Algorithm1': 'OSS',
            'Algorithm2': 'OSCHEB',
            'Algorithm3': 'ETDRK4',
            'Q1_ref': Q1_ref,
            'Q2_ref': Q2_ref,
            'Q3_ref': Q3_ref,
            'Q1': Qs1,
            'Q2': Qs2,
            'Q3': Qs3,
            'N1': NN1,
            'err1': errs1,
            'N2': NN2,
            'err2': errs2,
            'N3': NN3,
            'err3': errs3
        })

    plt.plot(NN1, errs1, 'bo-', label='OSS')
    plt.plot(NN2, errs2, 'go-', label='OSCHEB')
    plt.plot(NN3, errs3, 'ro-', label='ETDRK4')
    plt.yscale('log')
    plt.xlabel('$N_z$')
    plt.ylabel('Relative Error at s=1')
    handles, labels = plt.gca().get_legend_handles_labels()
    plt.legend(handles, labels, loc='upper right')
    plt.grid('on')
    plt.savefig(data_name, bbox_inches='tight')
    plt.show()
Example #9
0
def test_Ns_dirichlet():
    '''
    1 OSS
    2 OSCHEB
    3 ETDRK4
    '''
    L = 10
    N = 128
    Ns1 = 200000 + 1
    Ns2 = 200000 + 1
    Ns3 = 200000 + 1
    method = 2  # 0: OSS, 1: OSCHEB, 2: ETDRK4
    algo3 = 1  # 0: circular, 1: hyperbolic, 2: scaling and squaring
    scheme = 1
    data_name = 'benchmark/Ns_convergence/'
    if method == 0:
        data_name = data_name + 'OSS/Ns_DBC_N' + str(N)
    elif method == 1:
        data_name = data_name + 'OSCHEB/Ns_DBC_N' + str(N)
    elif method == 2:
        if scheme == 0:
            data_name = data_name + 'Cox_Matthews/Ns_DBC_N' + str(N)
        else:
            data_name = data_name + 'Krogstad/Ns_DBC_N' + str(N)
    else:
        raise ValueError('No such method!')

    print data_name

    oscheb_ref = '../benchmark/exact/OSCHEB_N'
    oscheb_ref = oscheb_ref + '8192_Ns200000.mat'
    mat = loadmat(oscheb_ref)
    q2_ref = mat['q']
    Q2_ref = mat['Q'][0, 0]
    N2_ref = mat['N']
    Ns2_ref = mat['Ns']

    #oss_ref = 'benchmark/exact/OSS_N'
    #oss_ref = oss_ref + str(N) + '_Ns20000.mat'
    oss_ref = oscheb_ref
    mat = loadmat(oss_ref)
    q1_ref = mat['q']
    Q1_ref = mat['Q'][0, 0]
    N1_ref = mat['N']
    Ns1_ref = mat['Ns']

    #if scheme == 0:
    #    etdrk4_ref = 'benchmark/exact/CoxMatthews/ETDRK4_N'
    #elif scheme == 1:
    #    etdrk4_ref = 'benchmark/exact/Krogstad/ETDRK4_N'
    #else:
    #    raise ValueError('No such scheme!')
    #etdrk4_ref = etdrk4_ref + str(N) + '_Ns20000.mat'
    etdrk4_ref = oscheb_ref
    mat = loadmat(etdrk4_ref)
    q3_ref = mat['q']
    Q3_ref = mat['Q'][0, 0]
    print Q3_ref.shape
    N3_ref = mat['N']
    Ns3_ref = mat['Ns']

    mode = 0  # error mode 0: Q only, 1: q and Q
    if N1_ref == N and N2_ref.size == N and N3_ref.size == N:
        mode = 1

    print 'OSS'
    if method == 0:
        iters = 10
    else:
        iters = 0
    errs0_1 = []
    errs1_1 = []
    Qs1 = []
    Nss1 = []
    W1, u0, x = init_fourier(N, L)
    u0[0] = 0.
    u0[-1] = 0.
    ns_max = int(np.log10((Ns1 - 1) / 2))  # Ns_max = 10^{ns_max}
    for Ns in np.power(10, np.linspace(0, ns_max, iters)).astype(int) + 1:
        q1, x1 = cheb_mde_oss(W1, u0, L, Ns)
        Q1 = L * oss_integral_weights(q1)
        Qs1.append(Q1)
        if mode:
            err1 = np.max(np.abs(q1 - q1_ref)) / np.max(q1_ref)
            errs0_1.append(err1)
        err1 = np.abs(Q1 - Q1_ref) / np.abs(Q1_ref)
        errs1_1.append(err1)
        Nss1.append(1. / (Ns - 1))
        print Ns - 1, '\t', err1

    print 'OSCHEB'
    if method == 1:
        iters = 10
    else:
        iters = 0
    errs0_2 = []
    errs1_2 = []
    Qs2 = []
    Nss2 = []
    W2, u0, x = init_chebyshev_fredrikson(N, L)
    u0[0] = 0.
    u0[-1] = 0.
    ns_max = int(np.log10((Ns2 - 1) / 2))  # Ns_max = 10^{ns_max}
    for Ns in np.power(10, np.linspace(0, ns_max, iters)).astype(int) + 1:
        q2 = cheb_mde_dirichlet_oscheb(W2, u0, L, Ns)
        Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)
        Qs2.append(Q2)
        if mode:
            err2 = np.max(np.abs(q2 - q2_ref)) / np.max(q2_ref)
            errs0_2.append(err2)
        err2 = np.abs(Q2 - Q2_ref) / np.abs(Q2_ref)
        errs1_2.append(err2)
        Nss2.append(1. / (Ns - 1))
        print Ns - 1, '\t', err2

    if scheme == 0:
        print 'ETDRK4-Cox-Matthews'
    else:
        print 'ETDRK4-Krogstad', 'N =', N
    if method == 2:
        iters = 10
    else:
        iters = 0
    errs0_3 = []
    errs1_3 = []
    Qs3 = []
    Nss3 = []
    W3, u0, x = init_chebyshev_fredrikson(N, L)
    u0[0] = 0.
    u0[-1] = 0.
    ns_max = int(np.log10((Ns3 - 1) / 2))  # Ns_max = 10^{ns_max}
    for Ns in np.power(10, np.linspace(0, ns_max, iters)).astype(int) + 1:
        #q3, x3 = cheb_mde_dirichlet_etdrk4(W3, u0, L, Ns,
        #                                   None, None, algo3, scheme)
        solver = ETDRK4(L, N, Ns)
        q3, x3 = solver.solve(W3, u0)
        q3.shape = (q3.size, )
        Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
        Qs3.append(Q3)
        if mode:
            err3 = np.max(np.abs(q3 - q3_ref)) / np.max(q3_ref)
            errs0_3.append(err3)
        err3 = np.abs(Q3 - Q3_ref) / np.abs(Q3_ref)
        errs1_3.append(err3)
        Nss3.append(1. / (Ns - 1))
        print Ns - 1, '\t', err3, '\t', Q3_ref

    savemat(
        data_name, {
            'N_ref1': N1_ref,
            'N_ref2': N2_ref,
            'N_ref3': N3_ref,
            'N': N,
            'Ns1_ref': Ns1_ref,
            'Ns2_ref': Ns2_ref,
            'Ns3_ref': Ns3_ref,
            'Algorithm1': 'OSS',
            'Algorithm2': 'OSCHEB',
            'Algorithm3': 'ETDRK4',
            'Q1_ref': Q1_ref,
            'Q2_ref': Q2_ref,
            'Q3_ref': Q3_ref,
            'Q1': Qs1,
            'Q2': Qs2,
            'Q3': Qs3,
            'Ns0_1': Nss1,
            'err0_1': errs0_1,
            'Ns1_1': Nss1,
            'err1_1': errs1_1,
            'Ns0_2': Nss2,
            'err0_2': errs0_2,
            'Ns1_2': Nss2,
            'err1_2': errs1_2,
            'Ns0_3': Nss3,
            'err0_3': errs0_3,
            'Ns1_3': Nss3,
            'err1_3': errs1_3
        })

    if mode:
        plt.plot(Nss1, errs0_1, 'bo-', label='OSS')
        plt.plot(Nss2, errs0_2, 'go-', label='OSCHEB')
        plt.plot(Nss3, errs0_3, 'ro-', label='ETDRK4')
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('$\Delta s$')
        plt.ylabel('Relative Error at s=1')
        handles, labels = plt.gca().get_legend_handles_labels()
        plt.legend(handles, labels, loc='lower right')
        plt.grid('on')
        plt.show()

    plt.plot(Nss1, errs1_1, 'bo-', label='OSS')
    plt.plot(Nss2, errs1_2, 'go-', label='OSCHEB')
    plt.plot(Nss3, errs1_3, 'ro-', label='ETDRK4')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlabel('$\Delta s$')
    plt.ylabel('Relative Error at s=1')
    handles, labels = plt.gca().get_legend_handles_labels()
    plt.legend(handles, labels, loc='lower right')
    plt.grid('on')
    plt.savefig(data_name, bbox_inches='tight')
    plt.show()
Example #10
0
    def run(self):
        config = self.config
        fA, fB = self.fA, self.fB
        chiN = self.chiN
        Lx, La = self.Lx, self.La
        lamA, lamB, lamY = self.lamA, self.lamB, self.lamY
        ds = self.ds
        print 'fA=', fA, 'fB=', fB
        print 'MsA=', self.config.grid.vMs[0],
        print 'MsB=', self.config.grid.vMs[1]
        print 'chi_AB*N=', chiN
        print 'Lx=', Lx, 'La=', La
        print 'lamA=', lamA, 'lamB=', lamB, 'lamY=', lamY
        #config.display()

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir, config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir, config.scft.q_file)

        phiA = np.zeros([Lx])
        phiB = np.zeros([Lx])
        ii = np.arange(Lx)
        x = np.cos(np.pi * ii / (Lx - 1))
        x = 0.5 * (x + 1) * La
        ts = []
        Fs = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter + 1):
            # Solve MDE
            self.qA_solver.solve(self.wA, self.qA[0], self.qA)

            self.qB[0] = self.qA[-1]
            if t % display_interval == 0:
                plt.plot(x, self.qB[0])
                plt.xlabel('qB[0]')
                plt.show()
            self.qB_solver.solve(self.wB, self.qB[0], self.qB)
            if t % display_interval == 0:
                plt.plot(x, self.qB[-1])
                plt.xlabel('qB[-1]')
                plt.show()

            self.qBc_solver.solve(self.wB, self.qBc[0], self.qBc)

            self.qAc[0] = self.qBc[-1]
            if t % display_interval == 0:
                plt.plot(x, self.qAc[0])
                plt.xlabel('qAc[0]')
                plt.show()
            self.qAc_solver.solve(self.wA, self.qAc[0], self.qAc)
            if t % display_interval == 0:
                plt.plot(x, self.qAc[-1])
                plt.xlabel('qAc[-1]')
                plt.show()

            # Calculate Q
            # Q = (1/La) * \int_0^Lx q(x, s=1) dx
            Q = 0.5 * cheb_quadrature_clencurt(self.qB[-1])
            Qc = 0.5 * cheb_quadrature_clencurt(self.qAc[-1])

            # Calculate density
            phiA0 = phiA
            phiB0 = phiB
            # Don't divide Q_AB here to intentionally force Q_AB = 1.0
            # which stablize the algorithm.
            phiA = calc_density_1d(self.qA, self.qAc, self.ds)
            phiB = calc_density_1d(self.qB, self.qBc, self.ds)

            # Calculate energy
            ff = self.chiN * phiA * phiB - self.wA * phiA - self.wB * phiB
            F1 = 0.5 * cheb_quadrature_clencurt(ff)
            F2 = -np.log(Q)
            F = F1 + F2

            if t % display_interval == 0:
                plt.plot(x, phiA, label='$\phi_A$')
                plt.plot(x, phiB, label='$\phi_B$')
                plt.legend(loc='best')
                plt.xlabel('$x$')
                plt.xlabel('$\phi(x)$')
                plt.show()

            # Estimate error
            # Incompressible model
            resA = self.chiN * phiB - self.wA + self.yita
            resB = self.chiN * phiA - self.wB + self.yita
            # Compressible model
            resY = phiA + phiB - 1.0
            #resA = self.chiN*phiB + self.yita*resY - self.wA
            #resB = self.chiN*phiA + self.yita*resY - self.wB
            err1 = 0.0
            err1 += np.mean(np.abs(resA))
            err1 += np.mean(np.abs(resB))
            # ONLY for incompressible model
            err1 += np.mean(np.abs(resY))
            err1 /= 3.
            # Compressible model
            #err1 /= 2.

            err2 = 0.0
            err2 += np.linalg.norm(phiA - phiA0)
            err2 += np.linalg.norm(phiB - phiB0)
            err2 /= 2.

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                errs_residual.append(err1)
                errs_phi.append(err2)
                time = t_end - t_start
                times.append(time)
                print t, '\ttime =', time, '\tF =', F
                print '\tQ =', Q, '\tQc =', Qc
                print '\t<A> =', 0.5 * cheb_quadrature_clencurt(phiA),
                print '\t[', phiA.min(), ', ', phiA.max(), ']'
                print '\t<B> =', 0.5 * cheb_quadrature_clencurt(phiB),
                print '\t[', phiB.min(), ', ', phiB.max(), ']'
                print '\t<wA> =', 0.5 * cheb_quadrature_clencurt(self.wA),
                print '\t[', self.wA.min(), ', ', self.wA.max(), ']'
                print '\t<wB> =', 0.5 * cheb_quadrature_clencurt(self.wB),
                print '\t[', self.wB.min(), ', ', self.wB.max(), ']'
                #print '\tyita =', self.yita
                #print '\tkaB =', self.qB_solver.lbc.beta,
                #print '\tkbB =', self.qB_solver.rbc.beta
                print '\terr1 =', err1, '\terr2 =', err2
                print
            if t % save_interval == 0:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'x': x,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phiA': phiA,
                        'wA': self.wA,
                        'phiB': phiB,
                        'wB': self.wB,
                        'yita': self.yita
                    })
                if save_q:
                    savemat(
                        q_file + '_' + str(t), {
                            'qA': self.qA,
                            'qAc': self.qAc,
                            'qB': self.qB,
                            'qBc': self.qBc
                        })

            if err1 < thresh_residual:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'x': x,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phiA': phiA,
                        'wA': self.wA,
                        'phiB': phiB,
                        'wB': self.wB,
                        'yita': self.yita
                    })
                if save_q:
                    savemat(
                        q_file + '_' + str(t), {
                            'qA': self.qA,
                            'qAc': self.qAc,
                            'qB': self.qB,
                            'qBc': self.qBc
                        })
                exit()

            # Update field
            self.wA = self.wA + self.lamA * resA
            self.wB = self.wB + self.lamB * resB
            # ONLY for incompressible model
            self.yita = self.yita + self.lamY * resY
Example #11
0
def test_speed_space_etdrk4():
    '''
    The expect complexity for ETDRK4 is O(N^2).
    However, due to the calculation of matrix exponential,
    it exceeds O(N^2) for large N.
    '''
    # Construct reference solution
    oscheb_ref = '../benchmark/exact/OSCHEB_N'
    oscheb_ref = oscheb_ref + '8192_Ns200000.mat'
    mat = loadmat(oscheb_ref)
    q_ref = mat['q']
    Q_ref = mat['Q'][0,0]
    N_ref = mat['N']
    Ns_ref = mat['Ns']

    L = 10.0
    n = 10 # Nmax = 2^n
    Ns = 200+1 # highest accuracy for reference. h = 1e-4
    M_array = np.ones(n-1) # number of same run
    M_array[0:5] = 1000 # 4, 8, 16, 32, 64
    M_array[5] = 500 # 128
    M_array[6] = 100 # 256
    M_array[7] = 20 # 512
    M_array[8] = 5 # 1024

    N_array = []
    t_full_array = []
    t_array = []
    err_array = []
    i = 0
    for N in 2**np.arange(2, n+1):
        M = int(M_array[i])
        W, u0, x = init_chebyshev_fredrikson(N, L)
        
        solver = ETDRK4(L, N, Ns)
        t = clock()
        for m in xrange(M):
            q, x = solver.solve(W, u0)
        t = (clock() - t) / M
        t_array.append(t)

        t_full = clock()
        for m in xrange(M):
            solver = ETDRK4(L, N, Ns)
            q, x = solver.solve(W, u0)
        t_full = (clock() - t_full) / M
        t_full_array.append(t_full)

        N_array.append(N)
        q.shape = (q.size,)
        Q = 0.5 * L * cheb_quadrature_clencurt(q)
        err = np.abs(Q - Q_ref) / np.abs(Q_ref)
        err_array.append(err)
        print N, '\t', t_full_array[-1], '\t', 
        print t_array[-1], '\t', err_array[-1]
        i += 1

    is_save = 1
    is_display = 1
    if is_save:
        savemat('speed_ETDRK4_N',{
            'N':N_array, 'Ns':Ns-1, 'N_ref':N_ref, 'Ns_ref':Ns_ref,
            't_full':t_full_array, 't':t_array, 'err':err_array})
    if is_display:
        plt.figure()
        ax = plt.subplot(111)
        ax.plot(N_array, t_full_array, '.-', label='Full')
        ax.plot(N_array, t_array, '.-', label='Core')
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('$N$')
        plt.ylabel('Computer time')
        plt.grid('on')
        ax.legend(loc='upper left')
        if is_save:
            plt.savefig('speed_ETDRK4_N', bbox_inches='tight')
        plt.show()

        plt.figure()
        ax = plt.subplot(111)
        ax.plot(err_array, t_array, 'o-')
        plt.xscale('log')
        plt.yscale('log')
        plt.xlabel('Relative error in $Q$')
        plt.ylabel('Computer time')
        plt.grid('on')
        if is_save:
            plt.savefig('speed_error_ETDRK4_N', bbox_inches='tight')
        plt.show()
Example #12
0
    def run(self):
        config = self.config
        print 'fA=', self.fA, 'chiN=', self.chiN
        print 'Lx=', self.Lx, 'Ly=', self.Ly
        print 'La=', self.La, 'Lb=', self.Lb
        print 'lamA=', self.lamA, 'lamB=', self.lamB, 'lamY=', self.lamY
        config.display()

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir,
                                 config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir,
                                 config.scft.q_file)

        phiA = np.zeros([self.Lx, self.Ly])
        phiB = np.zeros([self.Lx, self.Ly])
        ii = np.arange(self.Ly)
        y = np.cos(np.pi * ii / (self.Ly - 1))
        y = 0.5 * (y + 1) * self.Lb
        ts = []
        Fs = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter+1):
            # Solve MDE
            self.qA_solver.solve(self.wA, self.qA[0], self.qA)

            self.qB[0] = self.qA[-1]
            if t % display_interval == 0:
                plt.imshow(self.qB[0])
                plt.show()
            self.qB_solver.solve(self.wB, self.qB[0], self.qB)
            if t % display_interval == 0:
                plt.imshow(self.qB[-1])
                plt.show()

            self.qBc_solver.solve(self.wB, self.qBc[0], self.qBc)

            self.qAc[0] = self.qBc[-1]
            if t % display_interval == 0:
                plt.imshow(self.qAc[0])
                plt.show()
            self.qAc_solver.solve(self.wA, self.qAc[0], self.qAc)
            if t % display_interval == 0:
                plt.imshow(self.qAc[-1])
                plt.show()

            # Calculate Q
            # Q = (1/La/Lb) * \int_0^Lx \int_0^Ly q(x,y,s=1) dx dy
            Qx = np.mean(self.qB[-1], axis=0) # integrate along x
            Q = 0.5 * cheb_quadrature_clencurt(Qx)
            Qcx = np.mean(self.qAc[-1], axis=0) # integrate along x
            Qc = 0.5 * cheb_quadrature_clencurt(Qcx)

            # Calculate density
            phiA0 = phiA
            phiB0 = phiB
            phiA = calc_density_2d(self.qA, self.qAc, self.ds) / Q
            phiB = calc_density_2d(self.qB, self.qBc, self.ds) / Q
            # Following codes are for strong surface interactions
            #fAy = np.mean(phiA, axis=0)
            #fBy = np.mean(phiB, axis=0)
            #fAy0 = fAy[0]; fAyL = fAy[-1]
            #fBy0 = fBy[0]; fByL = fBy[-1]
            #kaB = -self.kaA * fAy0 / fBy0
            #kbB = -self.kbA * fAyL / fByL
            #self.qB_solver.lbc.beta = kaB
            #self.qB_solver.rbc.beta = kbB
            #self.qB_solver.update()
            #self.qBc_solver.lbc.beta = kaB
            #self.qBc_solver.rbc.beta = kbB
            #self.qBc_solver.update()

            # Calculate energy
            ff = self.chiN*phiA*phiB - self.wA*phiA - self.wB*phiB
            F1x = np.mean(ff, axis=0)
            F1 = 0.5 * cheb_quadrature_clencurt(F1x)
            F2 = -np.log(Q)
            F = F1 + F2

            if t % display_interval == 0:
                phiAB = phiA - phiB
                plt.imshow(phiAB)
                plt.show()
                plt.plot(y, phiA[self.Lx/2])
                plt.plot(y, phiB[self.Lx/2])
                plt.show()

            # Estimate error
            #resA = self.chiN*phiB - self.wA + self.yita # For incompressible model
            #resB = self.chiN*phiA - self.wB + self.yita # For incompressible model
            resY = phiA + phiB - 1.0
            resA = self.chiN*phiB + self.yita*resY - self.wA # For compressible model
            resB = self.chiN*phiA + self.yita*resY - self.wB # For compressible model
            err1 = 0.0
            err1 += np.mean(np.abs(resA))
            err1 += np.mean(np.abs(resB))
            #err1 += np.mean(np.abs(resY)) # For incompressible model
            err1 /= 2.
            err2 = 0.0
            err2 += np.linalg.norm(phiA-phiA0)
            err2 += np.linalg.norm(phiB-phiB0)

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                errs_residual.append(err1)
                errs_phi.append(err2)
                time = t_end - t_start
                times.append(time)
                phiA_meanx = np.mean(phiA, axis=0)
                phiA_mean = 0.5 * cheb_quadrature_clencurt(phiA_meanx)
                phiB_meanx = np.mean(phiB, axis=0)
                phiB_mean = 0.5 * cheb_quadrature_clencurt(phiB_meanx)
                print t, '\ttime =', time, '\tF =', F
                print '\tQ =', Q, '\tQc =', Qc
                print '\t<A> =', phiA_mean, '\t<B> =', phiB_mean
                print '\t<wA> =', np.mean(self.wA), '\t<wB> =', np.mean(self.wB)
                #print '\tyita =', self.yita
                #print '\tkaB =', self.qB_solver.lbc.beta,
                #print '\tkbB =', self.qB_solver.rbc.beta
                print '\terr1 =', err1, '\terr2 =', err2
                print
            if t % save_interval == 0:
                savemat(data_file+'_'+str(t), {'t':ts, 'time':times,
                                    'F':Fs,
                                    'err_residual':errs_residual,
                                    'err_phi':errs_phi,
                                    'phiA':phiA, 'wA':self.wA,
                                    'phiB':phiB, 'wB':self.wB,
                                    'yita':self.yita})
                if save_q:
                    savemat(q_file+'_'+str(t), {'qA':self.qA, 'qAc':self.qAc,
                                                'qB':self.qB, 'qBc':self.qBc})

            if err1 < thresh_residual:
                savemat(data_file+'_'+str(t), {'t':ts, 'time':times,
                                    'F':Fs,
                                    'err_residual':errs_residual,
                                    'err_phi':errs_phi,
                                    'phiA':phiA, 'wA':self.wA,
                                    'phiB':phiB, 'wB':self.wB,
                                    'yita':self.yita})
                if save_q:
                    savemat(q_file+'_'+str(t), {'qA':self.qA, 'qAc':self.qAc,
                                                'qB':self.qB, 'qBc':self.qBc})
                exit()

            # Update field
            self.wA = self.wA + self.lamA * resA
            self.wB = self.wB + self.lamB * resB
Example #13
0
def test_cheb_mde_brush():
    '''
    Solving MDE for polymer brushes.
    The Dirac initial condition is approximate by a Kronecker delta.

    Suppose the Dirac is \delta(x-x0), Kronecker delta is d_x0

    For Splitting method, the space is uniformly discretized, to constrain
    the integral of Dirac function to 1, that is
        I = \Integrate d_x0 = q[x0] * (L/N) = 1
    Thus, the initial condition of q is
        q(x) = N/L, x = x0
        q(x) = 0,   otherwise.

    For ETDRK4 method, the space is discretized in a manner that grids
    are clustered near the boundary (Chebyshev Gauss-Lobatto Grids). We
    can evaluate the integral by Clenshaw-Curtis quadrature, that is
        I = \Integrate d_x0 = (L/2) * q[x0] * w[x0] = 1
    where w[x0] is the Clenshaw-Curtis weight at x0. Thus the initial
    condition of q is
        q(x) = 2/(L*w(x)), x = x0
        q(x) = 0,          otherwise

    Apporximate Dirac delta via Chebyshev differention of a step function,
        H_x0 = 0, x < x0
        H_x0 = 1, x >= x0
    Then the Driac delta is
        D .dot. H_x0
    Where D is Chebyshev first order differentiation matrix.
    Ref: Jung Jae-Hun, A spectral collocation approximation of one
        dimensional head-on colisions of black-holes.
    '''
    L = 15.0
    x0 = 0.2
    N = 128
    Ns = 200 + 1
    ds = 1. / (Ns - 1)

    ii = np.arange(N + 1)
    x = 1. * ii * L / N
    W = np.zeros_like(x)
    u0 = np.zeros(N + 1)
    ix = int(np.round(N * x0 / L))
    x0 = x[ix]
    print 'ix_eq =', ix, 'x0_eq =', x0
    u0[ix] = N / L
    plt.plot(x, u0)
    plt.show()

    q_exact_eq = 1. / np.sqrt(4 * np.pi) * np.exp(-(x - x0)**2 / 4)

    q1, x1 = cheb_mde_oss(W, u0, L, Ns)
    #q1, x1 = cheb_mde_osc(W, u0, L, Ns)
    print np.linalg.norm(q1 - q_exact_eq)

    ii = np.arange(N + 1)
    x = np.cos(np.pi * ii / N)
    x = .5 * (x + 1) * L
    ix = int(np.arccos(2 * x0 / L - 1) / np.pi * N)
    x0 = x[ix]
    print 'ix_cheb =', ix, 'x0_cheb =', x0
    W = np.zeros_like(x)

    q_exact_cheb = 1. / np.sqrt(4 * np.pi) * np.exp(-(x - x0)**2 / 4)
    q_exact_cheb.shape = (N + 1, 1)

    # Apporximate Dirac delta via Kronecker delta
    u0 = np.zeros(N + 1)
    w = clencurt_weights_fft(N)
    u0[ix] = (2 / L) / w[ix]
    u0_dbc = u0
    u0_nbc = 0.5 * u0
    print 'Kronecker integral DBC =', (L /
                                       2) * cheb_quadrature_clencurt(u0_dbc)
    print 'Kronecker integral NBC =', (L /
                                       2) * cheb_quadrature_clencurt(u0_nbc)
    plt.plot(x, u0)
    plt.show()

    q2, x2 = cheb_mde_dirichlet_etdrk4(W, u0_dbc, L, Ns)
    #q2, x2 = cheb_mde_neumann_etdrk4(W, u0_nbc, L, Ns)
    print np.linalg.norm(q2 - q_exact_cheb)

    # Apporximate Dirac delta via Chebyshev differentiation
    D, xc = cheb_D1_mat(N)
    H = np.zeros(N + 1)
    H[0:ix] = 1
    H[ix] = 0.5
    plt.plot(x, H)
    plt.show()
    u0 = (2 / L) * np.dot(D, H)
    #u0 = u0 / cheb_quadrature_clencurt(u0)
    u0_step = u0
    print 'Step intetral =', (L / 2) * cheb_quadrature_clencurt(u0)
    plt.plot(x, u0)
    plt.show()

    q3, x3 = cheb_mde_dirichlet_etdrk4(W, u0, L, Ns)
    #q3, x3 = cheb_mde_neumann_etdrk4(W, u0, L, Ns)
    print np.linalg.norm(q3 - q_exact_cheb)

    # Apporximate Dirac delta via Gaussian distribution
    alpha = 0.001
    # for DBC
    u0_dbc = 0.5 * np.exp(-(x-x0)**2/(2*alpha)) \
            / np.sqrt(0.5 * np.pi * alpha)
    # for NBC
    u0_nbc = 0.5 * np.exp(-(x-x0)**2/(2*alpha)) \
            / np.sqrt(0.5 * np.pi * alpha) \
            + 0.5 * x**2 * np.exp(-L**2/(2*alpha)) \
            / (2 * alpha * np.sqrt(0.5 * np.pi * alpha))
    print 'Gauss intetral DBC =', (L / 2) * cheb_quadrature_clencurt(u0_dbc)
    print 'Gauss intetral NBC =', (L / 2) * cheb_quadrature_clencurt(u0_nbc)
    plt.plot(x, u0_dbc)
    plt.plot(x, u0_nbc)
    plt.show()

    q4, x4 = cheb_mde_dirichlet_etdrk4(W, u0_dbc, L, Ns)
    #q4, x4 = cheb_mde_neumann_etdrk4(W, u0_nbc, L, Ns)
    print np.linalg.norm(q4 - q_exact_cheb)

    # Apporximate Dirac delta via CKE integration
    print 'CKE + MDE'
    u0 = np.exp(-ds * W) / np.sqrt(4 * np.pi * ds) \
            * np.exp(-(x-x0)**2/(4*ds))
    q1_exact_cheb = u0
    plt.plot(x, u0)
    plt.show()

    q5, x5 = cheb_mde_dirichlet_etdrk4(W, u0, L, Ns - 1, ds)
    #q5, x5 = cheb_mde_neumann_etdrk4(W, u0, L, Ns-1, ds)
    print np.linalg.norm(q5 - q_exact_cheb)

    # CKE method
    #x6 = x
    ##q0 = 2 * u0_step
    #q0 = q1_exact_cheb
    #q6 = np.zeros_like(q0)
    #for s in xrange(0, Ns):
    #    for k in xrange(N+1):
    #        kernel = 1 / np.sqrt(4 * np.pi * ds) \
    #                    * np.exp(-(x[k]-x)**2/(4*ds))
    #        q6[k] = np.exp(-ds * W[k]) * (L/2) \
    #                * cheb_quadrature_clencurt(kernel*q0)
    #    q0 = q6
    #    #print 's =', s
    #    #plt.plot(x6, q6)
    #    #plt.plot(x6, q1_exact_cheb)
    #    #plt.plot(x6, q_exact_cheb)
    #    #plt.axis([0, 6, 1e-10, 4])
    #    #plt.show()

    savemat(
        'IC', {
            'N': N,
            'Ns': Ns - 1,
            'Lz': L,
            'x': x,
            'q_exact': q_exact_cheb,
            'q_kron': q2,
            'q_heav': q3,
            'q_gauss': q4,
            'q_cke': q5
        })

    plt.figure()
    ax = plt.subplot(111)
    ax.plot(x, q_exact_cheb, 'k', label='Exact')
    #plt.plot(x1, np.abs(q1), 'b', label='OSC')
    ax.plot(x2, np.abs(q2), 'g', label='Kronecker')
    ax.plot(x3, np.abs(q3), 'r', label='Heaviside')
    ax.plot(x4, np.abs(q4), 'm', label='Gaussian')
    ax.plot(x5, np.abs(q5), 'c', label='CKE')
    #ax.plot(x6, np.abs(q6), 'y', label='CKE')
    #plt.axis([0, 6, 1e-10, 0.4])
    plt.yscale('log')
    plt.xlabel('$z$')
    plt.ylabel('$q(z, s=1)$')
    #plt.grid('on')
    ax.legend(loc='lower left')
    plt.savefig('IC', bbox_inches='tight')
    plt.show()
Example #14
0
    def run(self):
        config = self.config
        fA, fB, fC = self.fA, self.fB, self.fC
        chiN, chiACN, chiBCN = self.chiN, self.chiACN, self.chiBCN
        Lx, Ly, La, Lb = self.Lx, self.Ly, self.La, self.Lb
        lamA, lamB, lamC, lamY = self.lamA, self.lamB, self.lamC, self.lamY
        ds = self.ds
        sigma = self.sigma
        print 'fA=', fA, 'fB=', fB, 'fC=', fC
        print 'MsA=', self.config.grid.vMs[0],
        print 'MsB=', self.config.grid.vMs[1],
        print 'MsC=', self.config.grid.vMs[2]
        print 'chiAB*N=', chiN, 'chiBC*N=', chiACN, 'chiBC*N=', chiBCN
        print 'lamA=', lamA, 'lamB=', lamB, 'lamC=', lamC, 'lamY=', lamY
        print 'Lx=', Lx, 'Ly=', Ly
        print 'La=', La, 'Lb=', Lb
        print 'sigma=', sigma

        #if self.lbcC == DIRICHLET:
        #    iy0 = -2
        #else:
        iy0 = -1  # DBC is not supported currently
        delta, y = make_delta(Ly-1, iy0, Lb)
        print 'y0=', y[iy0], 'iy0=', iy0

        display_interval = config.scft.display_interval
        display_interval_test = 100000
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir,
                                 config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir,
                              config.scft.q_file)

        phiA = np.zeros((Lx, Ly))
        phiB = np.zeros((Lx, Ly))
        phiC = np.zeros((Lx, Ly))
        ii = np.arange(Ly)
        y = np.cos(np.pi * ii / (Ly - 1))
        y = 0.5 * (y + 1) * self.Lb
        ts = []
        Fs = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter+1):
            # Solve MDE
            self.qA_solver.solve(self.wA, self.qA[0], self.qA)

            self.qB[0] = self.qA[-1]
            if t % display_interval_test == 0:
                self.show_grid(self.qB[0])
            self.qB_solver.solve(self.wB, self.qB[0], self.qB)
            if t % display_interval_test == 0:
                self.show_grid(self.qB[-1])

            self.qBc_solver.solve(self.wB, self.qBc[0], self.qBc)

            self.qAc[0] = self.qBc[-1]
            if t % display_interval_test == 0:
                self.show_grid(self.qAc[0])
            self.qAc_solver.solve(self.wA, self.qAc[0], self.qAc)
            if t % display_interval_test == 0:
                self.show_grid(self.qAc[-1])

            self.qC_solver.solve(self.wC, self.qC[0], self.qC)

            for i in np.arange(Lx):
                self.qCc[0, i] = 2.0 * delta / self.qC[-1, i, iy0]
            if t % display_interval_test == 0:
                self.show_grid(self.qCc[0])
            self.qCc_solver.solve(self.wC, self.qCc[0], self.qCc)
            if t % display_interval_test == 0:
                self.show_grid(self.qCc[-1])

            # Calculate Q
            # Q = (1/La/Lb) * \int_0^Lx \int_0^Ly q(x,y,s=1) dx dy
            Qx_AB = np.mean(self.qB[-1], axis=0)  # integrate along x
            Q_AB = 0.5 * cheb_quadrature_clencurt(Qx_AB)
            Qcx_AB = np.mean(self.qAc[-1], axis=0)  # integrate along x
            Qc_AB = 0.5 * cheb_quadrature_clencurt(Qcx_AB)
            Qx_C = np.mean(self.qC[-1], axis=0)  # integrate along x
            Q_C = 0.5 * cheb_quadrature_clencurt(Qx_C)

            # Calculate density
            phiA0, phiB0, phiC0 = phiA, phiB, phiC
            c_AB = 1. / (1 + sigma*fC)
            phiA = c_AB * calc_density_2d(self.qA, self.qAc, ds)
            phiB = c_AB * calc_density_2d(self.qB, self.qBc, ds)
            c_C = sigma * c_AB * Lb
            phiC = c_C * calc_density_2d(self.qC, self.qCc, ds)
            # Following codes are for strong surface interactions
            #fAy = np.mean(phiA, axis=0)
            #fBy = np.mean(phiB, axis=0)
            #fAy0 = fAy[0]; fAyL = fAy[-1]
            #fBy0 = fBy[0]; fByL = fBy[-1]
            #kaB = -self.kaA * fAy0 / fBy0
            #kbB = -self.kbA * fAyL / fByL
            #self.qB_solver.lbc.beta = kaB
            #self.qB_solver.rbc.beta = kbB
            #self.qB_solver.update()
            #self.qBc_solver.lbc.beta = kaB
            #self.qBc_solver.rbc.beta = kbB
            #self.qBc_solver.update()

            # Calculate energy
            ff = chiN*phiA*phiB + chiACN*phiA*phiC + chiBCN*phiB*phiC
            ff = ff - self.wA*phiA - self.wB*phiB - self.wC*phiC
            F1x = np.mean(ff, axis=0)
            F1 = 0.5 * cheb_quadrature_clencurt(F1x)
            F2 = -c_AB*np.log(Q_AB) - c_C*np.log(Q_C)
            F = F1 + F2

            if t % display_interval == 0:
                self.show_density(phiA, phiB, phiC)

            # Estimate error
            # incompressible model
            resA = chiN*phiB + chiACN*phiC + self.yita - self.wA
            resB = chiN*phiA + chiBCN*phiC + self.yita - self.wB
            resC = chiACN*phiA + chiBCN*phiB + self.yita - self.wC
            resY = phiA + phiB + phiC - 1.0
            # compresible model
            #resA = chiN*phiB + chiACN*phiC + self.yita*resY - self.wA
            #resB = chiN*phiA + chiBCN*phiC + self.yita*resY - self.wB
            #resC = chiACN*phiA + chiBCN*phiB + self.yita*resY - self.wC
            err1 = 0.0
            err1 += np.mean(np.abs(resA))
            err1 += np.mean(np.abs(resB))
            err1 += np.mean(np.abs(resC))
            # ONLY for incompressible model
            err1 += np.mean(np.abs(resY))
            err1 /= 4.

            err2 = 0.0
            err2 += np.linalg.norm(phiA-phiA0)
            err2 += np.linalg.norm(phiB-phiB0)
            err2 += np.linalg.norm(phiC-phiC0)
            err2 /= 3.

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                errs_residual.append(err1)
                errs_phi.append(err2)
                time = t_end - t_start
                times.append(time)
                phiA_meanx = np.mean(phiA, axis=0)
                phiA_mean = 0.5 * cheb_quadrature_clencurt(phiA_meanx)
                phiB_meanx = np.mean(phiB, axis=0)
                phiB_mean = 0.5 * cheb_quadrature_clencurt(phiB_meanx)
                phiC_meanx = np.mean(phiC, axis=0)
                phiC_mean = 0.5 * cheb_quadrature_clencurt(phiC_meanx)
                wA_meanx = np.mean(self.wA, axis=0)
                wA_mean = 0.5 * cheb_quadrature_clencurt(wA_meanx)
                wB_meanx = np.mean(self.wB, axis=0)
                wB_mean = 0.5 * cheb_quadrature_clencurt(wB_meanx)
                wC_meanx = np.mean(self.wC, axis=0)
                wC_mean = 0.5 * cheb_quadrature_clencurt(wC_meanx)
                print t, '\ttime =', time, '\tF =', F
                print '\tQ_AB =', Q_AB, '\tQc_AB =', Qc_AB,
                print '\tQ_C =', Q_C
                print '\t<A> =', phiA_mean, '\t<B> =', phiB_mean,
                print '\t<C> =', phiC_mean
                print '\t<wA> =', wA_mean, '\t<wB> =', wB_mean,
                print '\t<wC> =', wC_mean
                #print '\tyita =', self.yita
                #print '\tkaB =', self.qB_solver.lbc.beta,
                #print '\tkbB =', self.qB_solver.rbc.beta
                print '\terr1 =', err1, '\terr2 =', err2
                print
            if t % save_interval == 0:
                savemat(data_file+'_'+str(t), {'t': ts, 'time': times,
                        'F': Fs,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phiA': phiA, 'wA': self.wA,
                        'phiB': phiB, 'wB': self.wB,
                        'phiC': phiC, 'wC': self.wC,
                        'yita': self.yita})
                if save_q:
                    savemat(q_file+'_'+str(t), {'qA': self.qA, 'qAc': self.qAc,
                                                'qB': self.qB, 'qBc': self.qBc,
                                                'qC': self.qC, 'qCc': self.qCc}
                            )

            if err1 < thresh_residual:
                savemat(data_file+'_'+str(t), {'t': ts, 'time': times,
                        'F': Fs,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phiA': phiA, 'wA': self.wA,
                        'phiB': phiB, 'wB': self.wB,
                        'phiC': phiC, 'wC': self.wC,
                        'yita': self.yita})
                if save_q:
                    savemat(q_file+'_'+str(t), {'qA': self.qA, 'qAc': self.qAc,
                                                'qB': self.qB, 'qBc': self.qBc,
                                                'qC': self.qC, 'qCc': self.qCc}
                            )
                exit()

            # Update fields
            self.wA = self.wA + self.lamA * resA
            self.wB = self.wB + self.lamB * resB
            self.wC = self.wC + self.lamC * resC
            self.yita = self.yita + self.lamY * resY  # incompressible model
Example #15
0
def plot_force():
    #base_dir = 'benchmark/BCC'
    data_dir = [#'B0.5_C25_fts_fixphi_run1/fts_out_50000.mat',
                #'B0.5_C25_fts_fixscftphi/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_run1/fts_out_50000.mat',
                #'B0.5_C25_fts_fixscftphi_run2/fts_out_50000.mat',
                #'B0.5_C25_fts_fixscftphi_run3/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_run4/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_run5/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_run6/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_run7/fts_out_100000.mat',
                'B25_C0.5_fts_fixclphi_update_phi_imag/fts_out_100000.mat',
                #'B25_C0.5_fts_fixphi/fts_out_50000.mat',
                #'B25_C0.5_fts_fixphi_run1/fts_out_50000.mat',
                #'B25_C0.5_fts_fixscftphi/fts_out_100000.mat',
                #'B25_C0.5_fts_fixscftphi_update_phi_imag/fts_out_150000.mat',
                #'B25_C0.5_fts_fixscftphi_update_phi_imag_run1/fts_out_100000.mat',
                #'B25_C0.5_fts_fixscftphi_update_phi_imag_run2/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_update_phi_imag_run1/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_update_phi_imag_run2/fts_out_100000.mat',
                #'B0.5_C25_fts_fixscftphi_update_phi_imag_run3/fts_out_200000.mat',
                #'B0.5_C25_fts_fixotherphi/fts_out_50000.mat',
                #'B0.5_C25_fts_fixphi_Lx128/fts_out_50000.mat',
                ]
    is_cl = [True, True, True, True, True]
    labels = [#'$\phi_{CL}, L_x=64$',
              '$\phi_{CL}, \lambda\Delta t=10^{-3}, t=8 \\times 10^4$',
              #'$\phi_{CL}, \lambda\Delta t=10^{-3}, t=3 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=1 \\times 10^5$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=6 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-4}, t=5 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=1.8 \\times 10^5$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-3}, t=3 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-4}, t=3 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-4}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-5}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-5}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-2}, t=8 \\times 10^4$',
              #'$\phi_{SCFT}, \lambda\Delta t=10^{-6}, t=8 \\times 10^4$',
              #'$\phi_{other}, L_x=64$',
              #'$\phi_{CL}, L_x=128$'
              ]
    B = [0.5, 0.5, 0.5, 0.5, 0.5]
    C = [25, 25, 25, 25, 25]

    fig, ax = plt.subplots(1)
    linestyle = mpltex.linestyle_generator(lines=['-'], markers=['o'],
                                           hollow_styles=[])

    i = 0
    for f in data_dir:
        print 'Processing ', f
        try:
            mat = loadmat(f)
        except:
            print 'Missing datafile', f
            continue
        x = mat['x']
        x = x.reshape(x.size)
        if is_cl[i]:
            iw_avg = mat['iw_avg'].real
            iw_avg = iw_avg.reshape(iw_avg.size)
            phi = mat['phi'].real
            phi = phi.reshape(phi.size)
        y = np.arange(-1, 1, 0.01)
        force = C[i] * phi - iw_avg / B[i]
        print "\tmean force: ", 0.5 * cheb_quadrature_clencurt(force)
        #force = cheb_interpolation_1d(y, force)
        #yp = 0.5 * (y + 1) * (x.max() - x.min())
        ax.plot(x, force, label=labels[i], **linestyle.next())
        i += 1

    #ax.set_yscale('log')
    ax.locator_params(nbins=5)
    ax.set_xlabel('$x$')
    ax.set_ylabel('$<\\frac{\delta H}{\delta \phi}>_{\phi}$')
    #ax.set_xlim([0.4, 0.6])
    #ax.set_ylim([1.71, 1.76])
    ax.legend(loc='best')

    fig.tight_layout(pad=0.1)
    fig.savefig('force_profile')
Example #16
0
    def run(self):
        config = self.config
        C, B = self.C, self.B
        Lx, La = self.Lx, self.La
        lam = self.lam
        Ms, ds = self.config.grid.Ms, self.ds
        print 'C=', C, 'B=', B
        print 'Ms=', Ms
        print 'Lx=', Lx, 'La=', La
        print 'lam=', lam
        #config.display()

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir, config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir, config.scft.q_file)

        phi = np.zeros([Lx])
        ii = np.arange(Lx)
        x = np.cos(np.pi * ii / (Lx - 1))
        x = 0.5 * (x + 1) * La
        ts = []
        Fs = []
        mus = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter + 1):
            # Solve MDE
            self.q_solver.solve(self.w, self.q[0], self.q)
            if t % (100 * display_interval) == 0:
                plt.plot(x, self.q[-1])
                plt.xlabel('$x$')
                plt.ylabel('q[-1]')
                plt.show()

            # Calculate Q
            # Q = (1/La) * \int_0^Lx q(x, s=1) dx
            Q = 0.5 * cheb_quadrature_clencurt(self.q[-1])

            # Calculate density
            phi0 = phi
            phi = calc_density_1d(self.q, self.q, self.ds) / Q

            # Calculate energy
            ff = 0.5 * B * C * C * phi * phi - self.w * phi
            F1 = 0.5 * cheb_quadrature_clencurt(ff)
            F2 = -C * np.log(Q)
            F = F1 + F2
            mu = -np.log(Q) + np.log(C)

            if t % (100 * display_interval) == 0:
                plt.plot(x, phi, label='$\phi$')
                plt.legend(loc='best')
                plt.xlabel('$x$')
                plt.ylabel('$\phi(x)$')
                plt.show()

            res = B * C * C * phi - C * self.w
            err1 = 0.0
            err1 += np.mean(np.abs(res))

            err2 = 0.0
            err2 += np.linalg.norm(phi - phi0)

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                mus.append(mu)
                errs_residual.append(err1)
                errs_phi.append(err2)
                time = t_end - t_start
                times.append(time)

            if t % display_interval == 0 or err1 < thresh_residual:
                print t, '\ttime =', time, '\tF =', F
                print '\tQ =', Q
                print '\t<A> =', 0.5 * cheb_quadrature_clencurt(phi),
                print '\t[', phi.min(), ', ', phi.max(), ']'
                print '\t<wA> =', 0.5 * cheb_quadrature_clencurt(self.w),
                print '\t[', self.w.min(), ', ', self.w.max(), ']'
                print '\terr1 =', err1, '\terr2 =', err2
                print

            if t % save_interval == 0:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'mu': mus,
                        'x': x,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phi': phi,
                        'w': self.w
                    })
                if save_q:
                    savemat(q_file + '_' + str(t), {'q': self.q})

            if err1 < thresh_residual:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'mu': mus,
                        'x': x,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phi': phi,
                        'w': self.w
                    })
                if save_q:
                    savemat(q_file + '_' + str(t), {'q': self.q})
                exit()

            # Update field
            self.w = self.w + self.lam * res
Example #17
0
    def run(self):
        config = self.config
        fA, fB, fC = self.fA, self.fB, self.fC
        chiN, chiACN, chiBCN = self.chiN, self.chiACN, self.chiBCN
        Lx, La = self.Lx, self.La
        lamA, lamB, lamC, lamY = self.lamA, self.lamB, self.lamC, self.lamY
        ds = self.ds
        sigma = self.sigma
        print 'fA=', fA, 'fB=', fB, 'fC', fC
        print 'MsA=', self.config.grid.vMs[0],
        print 'MsB=', self.config.grid.vMs[1],
        print 'MsC=', self.config.grid.vMs[2]
        print 'chiAB*N=', chiN, 'chiBC*N', chiACN, 'chiBC*N=', chiBCN
        print 'Lx=', Lx, 'La=', La
        print 'lamA=', lamA, 'lamB=', lamB, 'lamC=', lamC, 'lamY=', lamY
        #config.display()

        #if self.lbcC == DIRICHLET:
        #    ix0 = -2
        #else:
        ix0 = -1  # DBC is not supported currently
        delta, x = make_delta(Lx - 1, ix0, La)
        print 'x0=', x[ix0], 'ix0=', ix0

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir, config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir, config.scft.q_file)

        phiA = np.zeros([Lx])
        phiB = np.zeros([Lx])
        phiC = np.zeros([Lx])
        ii = np.arange(Lx)
        x = np.cos(np.pi * ii / (Lx - 1))
        x = 0.5 * (x + 1) * La
        ts = []
        Fs = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter + 1):
            # Solve MDE
            self.qA_solver.solve(self.wA, self.qA[0], self.qA)

            self.qB[0] = self.qA[-1]
            if t % display_interval == 0:
                plt.plot(x, self.qB[0])
                plt.xlabel('qB[0]')
                plt.show()
            self.qB_solver.solve(self.wB, self.qB[0], self.qB)
            if t % display_interval == 0:
                plt.plot(x, self.qB[-1])
                plt.xlabel('qB[-1]')
                plt.show()

            self.qBc_solver.solve(self.wB, self.qBc[0], self.qBc)

            self.qAc[0] = self.qBc[-1]
            if t % display_interval == 0:
                plt.plot(x, self.qAc[0])
                plt.xlabel('qAc[0]')
                plt.show()
            self.qAc_solver.solve(self.wA, self.qAc[0], self.qAc)
            if t % display_interval == 0:
                plt.plot(x, self.qAc[-1])
                plt.xlabel('qAc[-1]')
                plt.show()

            self.qC_solver.solve(self.wC, self.qC[0], self.qC)

            self.qCc[0] = 2.0 * delta / self.qC[-1, ix0]
            #qCc1, x = generate_IC(self.wC, ds, ix0, La, 1.0)  # CKE
            #self.qCc[1] = qCc1
            if t % display_interval == 0:
                plt.plot(x, self.qCc[0])
                plt.xlabel('qCc[1]')
                plt.show()
            self.qCc_solver.solve(self.wC, self.qCc[0], self.qCc)
            #self.qCc_solver.solve(self.wC, self.qCc[1], self.qCc[1:])
            if t % display_interval == 0:
                plt.plot(x, self.qCc[-1])
                plt.xlabel('qCc[-1]')
                plt.show()

            # Calculate Q
            # Q = (1/La) * \int_0^Lx q(x,s=1) dx
            Q_AB = 0.5 * cheb_quadrature_clencurt(self.qB[-1])
            Qc_AB = 0.5 * cheb_quadrature_clencurt(self.qAc[-1])
            Q_C = self.qC[-1, ix0]

            # Calculate density
            phiA0 = phiA
            phiB0 = phiB
            phiC0 = phiC
            # Don't divide Q_AB here to intentionally force Q_AB = 1.0
            # which stablize the algorithm.
            c_AB = 1. / (1 + sigma * fC)
            phiA = c_AB * calc_density_1d(self.qA, self.qAc, ds)
            phiB = c_AB * calc_density_1d(self.qB, self.qBc, ds)
            c_C = sigma * c_AB * La
            phiC = c_C * calc_density_1d(self.qC, self.qCc, ds)

            # Calculate energy
            ff = chiN * phiA * phiB + chiACN * phiA * phiC + chiBCN * phiB * phiC
            ff = ff - self.wA * phiA - self.wB * phiB - self.wC * phiC
            F1 = 0.5 * cheb_quadrature_clencurt(ff)
            F2 = -c_AB * np.log(Q_AB) - c_C * np.log(Q_C)
            F = F1 + F2

            if t % display_interval == 0:
                plt.plot(x, phiA, label='$\phi_A$')
                plt.plot(x, phiB, label='$\phi_B$')
                plt.plot(x, phiC, label='$\phi_C$')
                plt.legend(loc='best')
                plt.ylabel('$\phi(x)$')
                plt.xlabel('$x$')
                plt.show()

            # Estimate error
            # incompressible model
            resA = chiN * phiB + chiACN * phiC + self.yita - self.wA
            resB = chiN * phiA + chiBCN * phiC + self.yita - self.wB
            resC = chiACN * phiA + chiBCN * phiB + self.yita - self.wC
            # compresible model
            resY = phiA + phiB + phiC - 1.0
            #resA = chiN*phiB + chiACN*phiC + self.yita*resY - self.wA
            #resB = chiN*phiA + chiBCN*phiC + self.yita*resY - self.wB
            #resC = chiACN*phiA + chiBCN*phiB + self.yita*resY - self.wC
            err1 = 0.0
            err1 += np.mean(np.abs(resA))
            err1 += np.mean(np.abs(resB))
            err1 += np.mean(np.abs(resC))
            # ONLY for incompressible model
            err1 += np.mean(np.abs(resY))
            err1 /= 4.

            err2 = 0.0
            err2 += np.linalg.norm(phiA - phiA0)
            err2 += np.linalg.norm(phiB - phiB0)
            err2 += np.linalg.norm(phiC - phiC0)
            err2 /= 3.

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                errs_residual.append(err1)
                errs_phi.append(err2)
                time = t_end - t_start
                times.append(time)
                print t, '\ttime =', time, '\tF =', F
                print '\tQ_AB =', Q_AB, '\tQc_AB =', Qc_AB,
                print '\tQ_C =', Q_C
                print '\t<A> =', 0.5 * cheb_quadrature_clencurt(phiA),
                print '\t<B> =', 0.5 * cheb_quadrature_clencurt(phiB),
                print '\t<C> =', 0.5 * cheb_quadrature_clencurt(phiC)
                print '\t<wA> =', 0.5 * cheb_quadrature_clencurt(self.wA),
                print '\t<wB> =', 0.5 * cheb_quadrature_clencurt(self.wB),
                print '\t<wC> =', 0.5 * cheb_quadrature_clencurt(self.wC)
                #print '\tyita =', self.yita
                #print '\tkaB =', self.qB_solver.lbc.beta,
                #print '\tkbB =', self.qB_solver.rbc.beta
                print '\terr1 =', err1, '\terr2 =', err2
                print
            if t % save_interval == 0:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phiA': phiA,
                        'wA': self.wA,
                        'phiB': phiB,
                        'wB': self.wB,
                        'phiC': phiC,
                        'wC': self.wC,
                        'yita': self.yita
                    })
                if save_q:
                    savemat(
                        q_file + '_' + str(t), {
                            'qA': self.qA,
                            'qAc': self.qAc,
                            'qB': self.qB,
                            'qBc': self.qBc,
                            'qC': self.qC,
                            'qCc': self.qCc
                        })

            if err1 < thresh_residual:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phiA': phiA,
                        'wA': self.wA,
                        'phiB': phiB,
                        'wB': self.wB,
                        'phiC': phiC,
                        'wC': self.wC,
                        'yita': self.yita
                    })
                if save_q:
                    savemat(
                        q_file + '_' + str(t), {
                            'qA': self.qA,
                            'qAc': self.qAc,
                            'qB': self.qB,
                            'qBc': self.qBc,
                            'qC': self.qC,
                            'qCc': self.qCc
                        })
                exit()

            # Update fields
            self.wA = self.wA + self.lamA * resA
            self.wB = self.wB + self.lamB * resB
            self.wC = self.wC + self.lamC * resC
            self.yita = self.yita + lamY * resY  # incompressible model
Example #18
0
def test_exact_dirichlet(oss=0,oscheb=0,etdrk4=0):
    L = 10.0

    if oss:
        N = 1024 #4096
        Ns = 1000 + 1 #100000 + 1
        W, u0, x = init_fourier(N, L)
        u0[0] = 0.; u0[N] = 0.;
        print 'OSS N = ', N, ' Ns = ', Ns-1
        #q1, x1 = cheb_mde_oss(W, u0, L, Ns)
        oss_solver = OSS(L, N, Ns)
        q1, x1 = oss_solver.solve(W, u0)
        Q1 = L * oss_integral_weights(q1)
        #data_name = 'benchmark/exact/OSS_N' + str(N) + '_Ns' + str(Ns-1)
        data_name = 'OSS_N' + str(N) + '_Ns' + str(Ns-1)
        savemat(data_name,{
                'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
                'x':x, 'q':q1, 'Q':Q1})
        plt.plot(x1, q1, 'b')
        plt.axis([0, 10, 0, 1.15])
        #plt.show()

    if oscheb:
        N = 128 #16384
        Ns = 200 + 1 #1000000 + 1
        W, u0, x = init_chebyshev_fredrikson(N, L)
        u0[0] = 0; u0[N] = 0;
        print 'OSCHEB N = ', N, ' Ns = ', Ns-1
        #q2 = cheb_mde_dirichlet_oscheb(W, u0, L, Ns)
        oscheb_sovler = OSCHEB(L, N, Ns)
        q2, x2 = oscheb_sovler.solve(W, u0)
        Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)
        #data_name = 'benchmark/exact/OSCHEB_N' + str(N) + '_Ns' + str(Ns-1)
        data_name = 'OSCHEB_N' + str(N) + '_Ns' + str(Ns-1)
        savemat(data_name,{
                'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
                'x':x2, 'q':q2, 'Q':Q2})
        plt.plot(x2, q2, 'g')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        #plt.show()

    if etdrk4:
        N = 128
        Ns = 200 + 1 #20000 + 1
        algo = 1
        scheme = 1
        W, u0, x = init_chebyshev_fredrikson(N, L)
        u0[0] = 0; u0[N] = 0;
        print 'ETDRK4 N = ', N, ' Ns = ', Ns-1
        #q3, x3 = cheb_mde_dirichlet_etdrk4(W, u0, L, Ns, algo, scheme)
        etdrk4_solver = ETDRK4(L, N, Ns)
        q3, x3 = etdrk4_solver.solve(W, u0)
        Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
        #data_name = 'benchmark/exact/ETDRK4_N' + str(N) + '_Ns' + str(Ns-1)
        data_name = 'ETDRK4_N' + str(N) + '_Ns' + str(Ns-1)
        savemat(data_name,{
                'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
                'x':x, 'q':q3, 'Q':Q3})
        plt.plot(x3, q3, 'r')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        plt.show()
Example #19
0
    def run(self):
        config = self.config
        L = self.L
        Lx = self.Lx
        N = self.N
        Ms = config.grid.Ms
        ds = 1. / (Ms - 1)
        beta = self.beta
        lam = config.grid.lam[0]
        x_ref = self.z_hat
        phi = np.zeros(Lx)
        print 'beta =', beta, 'x_ref =', x_ref, 'Lz =', L
        print 'Lx =', Lx, 'Ms =', Ms, 'lam =', lam

        if self.lbc == DIRICHLET:
            x0 = 0.122 / x_ref  # x0 = 0.1R_g = 0.1/x_ref
            ix0 = int(np.arccos(2 * x0 / L - 1) / np.pi * N)
        else:
            x0 = 0.0
            ix0 = -1
        delta, x = make_delta(Lx - 1, ix0, L)
        print 'x0 =', x[ix0], 'ix0 =', ix0
        print 'delta integral =', 0.5 * L * cheb_quadrature_clencurt(delta)

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir, config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir, config.scft.q_file)
        ts = []
        Fs = []
        hs = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter + 1):
            #raw_input()

            # Solve MDE
            if t % display_interval == 0:
                plt.plot(x, self.w)
                plt.ylabel('w')
                plt.show()
            #    plt.plot(x_rescaled, self.q[0])
            #    plt.ylabel('q(0)')
            #    plt.show()
            self.q[0, :] = 1.
            self.q_solver.solve(self.w, self.q[0], self.q)
            if t % display_interval == 0:
                plt.plot(x, self.q[-1])
                plt.ylabel('q(-1)')
                plt.show()
            self.qc[0] = delta / self.q[-1, ix0]
            qc1, x = generate_IC(self.w, ds, ix0, L, x_ref)  # CKE
            self.qc[1] = qc1  # CKE
            if t % display_interval == 0:
                plt.plot(x, self.qc[1])
                plt.ylabel('qc[1]')
                plt.show()
            #self.qc_solver.solve(self.w, self.qc[0], self.qc) # approx delta
            self.qc_solver.solve(self.w, self.qc[1], self.qc[1:])  # CKE
            if t % display_interval == 0:
                plt.plot(x, self.qc[-1])
                plt.ylabel('qc(-1)')
                plt.show()

            # Calculate Q
            Q = self.q[-1, ix0]

            # Calculate density
            phi0 = phi
            phi = calc_density(self.q, self.qc)
            phi_total = 0.5 * L * cheb_quadrature_clencurt(phi)
            if t % display_interval == 0:
                plt.plot(x, phi)
                plt.ylabel('$\phi$')
                plt.show()

            # Calculate energy
            F1 = -0.5 * beta * (0.5 * L * cheb_quadrature_clencurt(phi * phi))
            F2 = -np.log(Q)
            F = F1 + F2

            # Estimate error
            res = beta * phi - self.w
            if t % display_interval == 0:
                plt.plot(x, res)
                plt.ylabel('res')
                plt.show()
            err1 = np.linalg.norm(res)
            err2 = np.linalg.norm(phi - phi0)

            h = calc_brush_height(x, phi)

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                hs.append(h)
                errs_residual.append(err1)
                errs_phi.append(err2)
                times.append((t_end - t_start) / record_interval)
                print t, '\t', F, '\t', F1, '\t', F2
                print '\t', phi_total
                print '\t', err1, '\t', err2
                print

            if t % save_interval == 0:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'h': hs,
                        'ix0': ix0,
                        'beta': beta,
                        'x_ref': x_ref,
                        'x': x,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phi': phi,
                        'w': self.w
                    })
                if save_q:
                    savemat(q_file + '_' + str(t), {
                        'q': self.q,
                        'qc': self.qc
                    })

            if err1 < thresh_residual:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'h': hs,
                        'ix0': ix0,
                        'beta': beta,
                        'x_ref': x_ref,
                        'x': x,
                        'err_residual': errs_residual,
                        'err_phi': errs_phi,
                        'phi': phi,
                        'w': self.w
                    })
                if save_q:
                    savemat(q_file + '_' + str(t), {
                        'q': self.q,
                        'qc': self.qc
                    })
                exit()

            # Update field
            self.w = self.w + lam * res
Example #20
0
def test_exact_neumann(osc=0,oscheb=0,etdrk4=0):
    L = 10.0

    if osc:
        N = 128
        Ns = 1000 + 1 #20000 + 1
        W, u0, x = init_fourier(N, L)
        print 'OSC N = ', N, ' Ns = ', Ns-1
        #q1, x1 = cheb_mde_osc(W, u0, L, Ns)
        osc_solver = OSC(L, N, Ns)
        q1, x1 = osc_solver.solve(W, u0)
        Q1 = L * simps(q1, dx=1./N)
        #data_name = 'benchmark/NBC-NBC/exact/OSS_N' 
        data_name = 'OSS_N' 
        data_name = data_name + str(N) + '_Ns' + str(Ns-1)
        savemat(data_name,{
                'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
                'x':x, 'q':q1, 'Q':Q1})
        plt.plot(x1, q1, 'b')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        #plt.show()

    if oscheb:
        N = 128
        Ns = 200 + 1 #20000 + 1
        W, u0, x = init_chebyshev_fredrikson(N, L)
        print 'OSCHEB N = ', N, ' Ns = ', Ns-1
        #q2 = cheb_mde_neumann_oscheb(W, u0, L, Ns)
        oscheb_sovler = OSCHEB(L, N, Ns, bc=BC('Neumann'))
        q2, x2 = oscheb_sovler.solve(W, u0)
        Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)
        #data_name = 'benchmark/NBC-NBC/exact/OSCHEB_N'
        data_name = 'OSCHEB_N'
        data_name = data_name + str(N) + '_Ns' + str(Ns-1)
        savemat(data_name,{
                'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
                'x':x2, 'q':q2, 'Q':Q2})
        plt.plot(x2, q2, 'g')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        #plt.show()

    if etdrk4:
        N = 128
        Ns = 200 + 1
        algo = 1
        scheme = 1
        W, u0, x = init_chebyshev_fredrikson(N, L)
        print 'ETDRK4 N = ', N, ' Ns = ', Ns-1
        #q3, x3 = cheb_mde_neumann_etdrk4(W, u0, L, Ns, None, algo, scheme)
        lbc = BC('Neumann')
        rbc = BC('Neumann')
        etdrk4_solver = ETDRK4(L, N, Ns, h=None, lbc=lbc, rbc=rbc)
        q3, x3 = etdrk4_solver.solve(W, u0)
        Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
        #if scheme == 0:
        #    data_name = 'benchmark/NBC-NBC/exact/ETDRK4_Cox_N' 
        #    data_name = data_name + str(N) + '_Ns' + str(Ns-1)
        #else:
        #    data_name = 'benchmark/NBC-NBC/exact/ETDRK4_Krogstad_N' 
        #    data_name = data_name + str(N) + '_Ns' + str(Ns-1)
        #savemat(data_name,{
        #        'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
        #        'x':x, 'q':q3, 'Q':Q3})
        plt.plot(x3, q3, 'r')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        #plt.savefig(data_name, bbox_inches='tight')
        plt.show()
Example #21
0
def test_exact_dirichlet(oss=0, oscheb=0, etdrk4=0):
    L = 10

    if oss:
        N = 4096
        Ns = 100000 + 1
        W, u0, x = init_fourier(N, L)
        u0[0] = 0.
        u0[N] = 0.
        print 'OSS N = ', N, ' Ns = ', Ns - 1
        q1, x1 = cheb_mde_oss(W, u0, L, Ns)
        Q1 = L * oss_integral_weights(q1)
        data_name = 'benchmark/exact/OSS_N' + str(N) + '_Ns' + str(Ns - 1)
        savemat(
            data_name, {
                'N': N,
                'Ns': Ns - 1,
                'W': W,
                'u0': u0,
                'Lz': L,
                'x': x,
                'q': q1,
                'Q': Q1
            })
        plt.plot(x1, q1, 'b')
        plt.axis([0, 10, 0, 1.15])
        plt.show()

    if oscheb:
        N = 16384
        Ns = 1000000 + 1
        W, u0, x = init_chebyshev(N, L)
        u0[0] = 0
        u0[N] = 0
        print 'OSCHEB N = ', N, ' Ns = ', Ns - 1
        q2 = cheb_mde_dirichlet_oscheb(W, u0, L, Ns)
        Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)
        data_name = 'benchmark/exact/OSCHEB_N' + str(N) + '_Ns' + str(Ns - 1)
        savemat(
            data_name, {
                'N': N,
                'Ns': Ns - 1,
                'W': W,
                'u0': u0,
                'Lz': L,
                'x': x,
                'q': q2,
                'Q': Q2
            })
        plt.plot(x, q2, 'g')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        plt.show()

    if etdrk4:
        N = 128
        Ns = 20000 + 1
        algo = 1
        scheme = 1
        W, u0, x = init_chebyshev(N, L)
        u0[0] = 0
        u0[N] = 0
        print 'ETDRK4 N = ', N, ' Ns = ', Ns - 1
        q3, x3 = cheb_mde_dirichlet_etdrk4(W, u0, L, Ns, algo, scheme)
        Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
        data_name = 'benchmark/exact/ETDRK4_N' + str(N) + '_Ns' + str(Ns - 1)
        savemat(
            data_name, {
                'N': N,
                'Ns': Ns - 1,
                'W': W,
                'u0': u0,
                'Lz': L,
                'x': x,
                'q': q3,
                'Q': Q3
            })
        plt.plot(x3, q3, 'r')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        plt.show()
Example #22
0
def test_speed_accuracy_oscheb():
    '''
    Computation time vs. error.
    '''
    # Construct reference solution
    oscheb_ref = '../benchmark/exact/OSCHEB_N'
    oscheb_ref = oscheb_ref + '8192_Ns200000.mat'
    mat = loadmat(oscheb_ref)
    q_ref = mat['q']
    Q_ref = mat['Q'][0,0]
    N_ref = mat['N']
    Ns_ref = mat['Ns']

    L = 10
    n = 10 # Nmax = 2^n
    Ns = 20000+1 
    M_array = np.ones(n-1) # number of same run
    #M_array[:5] = 1000 # 4, 8, 16, 32, 64
    #M_array[5] = 500 # 128
    #M_array[6] = 200 # 256
    #M_array[7] = 100 # 512
    #M_array[8] = 50 # 1024
    is_save = 1

    N_array = []
    t_array = [] # do not include initialization
    err_array = []
    i = 0
    for N in 2**np.arange(2, n+1):
        M = int(M_array[i])
        W, u0, x = init_chebyshev_fredrikson(N, L)
        u0[0] = 0.; u0[N] = 0.;

        solver = OSCHEB(L, N, Ns)
        t = clock()
        for m in xrange(M):
            q, x = solver.solve(W, u0)
        t = (clock() - t) / M
        t_array.append(t)

        N_array.append(N)
        q.shape = (q.size,)
        Q = 0.5 * L * cheb_quadrature_clencurt(q)
        err = np.abs(Q - Q_ref) / np.abs(Q_ref)
        err_array.append(err)
        print N, '\t', t_array[-1], '\t', err_array[-1]
        i += 1

    if is_save:
        savemat('speed_OSCHEB_accuracy',{
            'N':N_array, 'Ns':Ns-1, 'N_ref':N_ref, 'Ns_ref':Ns_ref, 
            't':t_array, 'err':err_array})

    plt.figure()
    ax = plt.subplot(111)
    ax.plot(N_array, t_array, 'o-')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlabel('$N$')
    plt.ylabel('Computer time')
    plt.grid('on')
    if is_save:
        plt.savefig('speed_OSCHEB_accuracy', bbox_inches='tight')
    plt.show()

    plt.figure()
    ax = plt.subplot(111)
    ax.plot(t_array, err_array, 'o-')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlabel('Computer time')
    plt.ylabel('Relative error in $Q$')
    plt.grid('on')
    if is_save:
        plt.savefig('speed_error_OSCHEB_accuracy', bbox_inches='tight')
    plt.show()
Example #23
0
def test_exact_neumann(osc=0, oscheb=0, etdrk4=0):
    L = 10

    if osc:
        N = 128
        Ns = 20000 + 1
        W, u0, x = init_fourier(N, L)
        print 'OSC N = ', N, ' Ns = ', Ns - 1
        q1, x1 = cheb_mde_osc(W, u0, L, Ns)
        Q1 = L * simps(q1, dx=1. / N)
        data_name = 'benchmark/NBC-NBC/exact/OSS_N'
        data_name = data_name + str(N) + '_Ns' + str(Ns - 1)
        savemat(
            data_name, {
                'N': N,
                'Ns': Ns - 1,
                'W': W,
                'u0': u0,
                'Lz': L,
                'x': x,
                'q': q1,
                'Q': Q1
            })
        plt.plot(x1, q1, 'b')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        plt.show()

    if oscheb:
        N = 128
        Ns = 20000 + 1
        W, u0, x = init_chebyshev(N, L)
        print 'OSCHEB N = ', N, ' Ns = ', Ns - 1
        q2 = cheb_mde_neumann_oscheb(W, u0, L, Ns)
        Q2 = 0.5 * L * cheb_quadrature_clencurt(q2)
        data_name = 'benchmark/NBC-NBC/exact/OSCHEB_N'
        data_name = data_name + str(N) + '_Ns' + str(Ns - 1)
        savemat(
            data_name, {
                'N': N,
                'Ns': Ns - 1,
                'W': W,
                'u0': u0,
                'Lz': L,
                'x': x,
                'q': q2,
                'Q': Q2
            })
        plt.plot(x, q2, 'g')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        plt.savefig(data_name, bbox_inches='tight')
        plt.show()

    if etdrk4:
        N = 128
        Ns = 200 + 1
        algo = 1
        scheme = 1
        W, u0, x = init_chebyshev(N, L)
        print 'ETDRK4 N = ', N, ' Ns = ', Ns - 1
        q3, x3 = cheb_mde_neumann_etdrk4(W, u0, L, Ns, None, algo, scheme)
        Q3 = 0.5 * L * cheb_quadrature_clencurt(q3)
        #if scheme == 0:
        #    data_name = 'benchmark/NBC-NBC/exact/ETDRK4_Cox_N'
        #    data_name = data_name + str(N) + '_Ns' + str(Ns-1)
        #else:
        #    data_name = 'benchmark/NBC-NBC/exact/ETDRK4_Krogstad_N'
        #    data_name = data_name + str(N) + '_Ns' + str(Ns-1)
        #savemat(data_name,{
        #        'N':N, 'Ns':Ns-1, 'W':W, 'u0':u0, 'Lz':L,
        #        'x':x, 'q':q3, 'Q':Q3})
        plt.plot(x3, q3, 'r')
        plt.axis([0, 10, 0, 1.15])
        plt.xlabel('$z$')
        plt.ylabel('$q(z)$')
        #plt.savefig(data_name, bbox_inches='tight')
        plt.show()
Example #24
0
    def run(self):
        config = self.config
        C, B = self.C, self.B
        Lx, La = self.Lx, self.La
        dx = La / Lx
        lam = self.lam
        Ms, ds = self.config.grid.Ms, self.ds
        num_eq_step = self.config.scft.eq_iter
        num_avg_step = self.config.scft.max_iter - num_eq_step
        print 'ftsSlabAS1d_phi'
        print 'C=', C, 'B=', B
        print 'Ms=', Ms
        print 'Lx=', Lx, 'La=', La
        print 'lam=', lam
        #config.display()

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir, config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir, config.scft.q_file)

        phi_op = np.zeros(Lx, dtype=np.complex128)
        ii = np.arange(Lx)
        x = np.cos(np.pi * ii / (Lx - 1))
        x = 0.5 * (x + 1) * La
        ts = []
        Fs = []
        errs_residual = []
        errs_phi = []
        times = []
        mu = []
        mu_sum = 0j
        mu_avg = 0j
        t_avg = 0
        phi_sum = np.zeros(Lx, dtype=np.complex128)
        phi_avg = np.zeros(Lx, dtype=np.complex128)
        iw_sum = np.zeros(Lx, dtype=np.complex128)
        iw_avg = np.zeros(Lx, dtype=np.complex128)
        t_start = clock()
        for t in xrange(1, config.scft.max_iter + 1):
            # Solve MDE
            self.q_solver.solve(self.w, self.q[0], self.q)
            if t % (100 * display_interval) == 0:
                plt.plot(x, self.q[-1].real)
                plt.xlabel('$x$')
                plt.ylabel('q[-1]')
                plt.show()

            # Calculate Q
            # Q = (1/La) * \int_0^Lx q(x, s=1) dx
            Q = 0.5 * cheb_quadrature_clencurt(self.q[-1])

            # Calculate density operator
            #phi0 = self.phi
            phi_op = calc_density_1d(self.q, self.q, ds) / Q

            # Calculate energy
            ff = 0.5 * B * C * C * self.phi * self.phi - C * self.phi * self.w
            F1 = 0.5 * cheb_quadrature_clencurt(ff)
            F2 = -C * np.log(Q)
            F = F1 + F2

            # Calculate chemical potential in production runs
            if t > num_eq_step:
                t_avg += 1
                iw_sum += self.w
                iw_avg = iw_sum / t_avg
                phi_sum += phi_op
                phi_avg = phi_sum / t_avg
                mu_op = -np.log(Q) + np.log(C)
                mu.append(mu_op)
                mu_sum += mu_op
                mu_avg = mu_sum / t_avg

            if t % (100 * display_interval) == 0:
                if t > num_eq_step:
                    plt.plot(x, phi_avg.real, label='$<\phi>$')
                else:
                    plt.plot(x, phi_op.real, label='$\phi$')
                plt.legend(loc='best')
                plt.xlabel('$x$')
                plt.ylabel('$\phi(x)$')
                plt.show()

            force_phi = C * (B * C * self.phi - self.w)
            force_w = C * (self.phi - phi_op)

            if t % record_interval == 0:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                time = t_end - t_start
                times.append(time)

            if t % display_interval == 0 or t == num_avg_step + num_eq_step:
                print t, '\ttime =', time, '\tF =', F
                print '\tQ =', Q, '\t<mu> =', mu_avg
                print '\t<A> =', 0.5 * cheb_quadrature_clencurt(phi_op),
                print '\t[', phi_op.real.min(), ', ', phi_op.real.max(), ']'
                print '\t<wA> =', 0.5 * cheb_quadrature_clencurt(self.w),
                print '\t[', self.w.real.min(), ', ', self.w.real.max(), ']'
                print

            if t % save_interval == 0:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'x': x,
                        'iw_avg': iw_avg,
                        'mu_avg': mu_avg,
                        'mu': mu,
                        'phi_avg': phi_avg,
                        'phi': self.phi,
                        'w': self.w
                    })
                if save_q:
                    savemat(q_file + '_' + str(t), {'q': self.q})

            if t == num_avg_step + num_eq_step:
                savemat(
                    data_file + '_' + str(t), {
                        't': ts,
                        'time': times,
                        'F': Fs,
                        'x': x,
                        'iw_avg': iw_avg,
                        'mu_avg': mu_avg,
                        'mu': mu,
                        'phi_avg': phi_avg,
                        'phi': self.phi,
                        'w': self.w
                    })
                if save_q:
                    savemat(q_file + '_' + str(t), {'q': self.q})
                exit()

            # Update field
            self.phi.imag -= lam * force_phi.imag
            self.w.real -= lam * force_w.real
            self.w.imag -= lam * force_w.imag
            self.w.imag += np.sqrt(2 * lam / dx) * np.random.randn(Lx)
Example #25
0
    def run(self):
        config = self.config
        print 'fA=', self.fA, 'chiN=', self.chiN
        print 'Nt=', self.Nt, 'Nr=', self.Nr
        print 'R=', self.R
        print 'lamA=', self.lamA, 'lamB=', self.lamB, 'lamY=', self.lamY
        config.display()

        display_interval = config.scft.display_interval
        record_interval = config.scft.record_interval
        save_interval = config.scft.save_interval
        save_q = config.scft.is_save_q
        thresh_residual = config.scft.thresh_residual
        data_file = os.path.join(config.scft.base_dir,
                                 config.scft.data_file)
        q_file = os.path.join(config.scft.base_dir,
                                 config.scft.q_file)

        phiA = np.zeros([self.Nt, self.Nr2])
        phiB = np.zeros([self.Nt, self.Nr2])
        tt = np.arange(self.Nt) * 2 * np.pi / self.Nt
        ii = np.arange(self.Nr)
        rr = np.cos(np.pi * ii / (self.Nr - 1))
        r2 = self.R * rr[:self.Nr2]
        rxy, txy = np.meshgrid(r2, tt)
        x, y= rxy*np.cos(txy), rxy*np.sin(txy)
        ts = []
        Fs = []
        errs_residual = []
        errs_phi = []
        times = []
        t_start = clock()
        for t in xrange(1, config.scft.max_iter+1):
            # Solve MDE
            self.qA_solver.solve(self.wA, self.qA[0], self.qA)

            self.qB[0] = self.qA[-1]
            if t % display_interval == 0:
                scft_contourf(x, y, self.qB[0])
                plt.xlabel('qB[0]')
                plt.show()
            self.qB_solver.solve(self.wB, self.qB[0], self.qB)
            if t % display_interval == 0:
                scft_contourf(x, y, self.qB[-1])
                plt.xlabel('qB[-1]')
                plt.show()

            self.qBc_solver.solve(self.wB, self.qBc[0], self.qBc)

            self.qAc[0] = self.qBc[-1]
            if t % display_interval == 0:
                scft_contourf(x, y, self.qAc[0])
                plt.xlabel('qAc[0]')
                plt.show()
            self.qAc_solver.solve(self.wA, self.qAc[0], self.qAc)
            if t % display_interval == 0:
                scft_contourf(x, y, self.qAc[-1])
                plt.xlabel('qAc[-1]')
                plt.show()

            # Calculate Q
            # Q = (1/V) * \int_0^R \int_0^{2\pi} q(x,y,s=1) r dr d\theta
            # V = \pi R^2
            #print np.max(self.qB[-1]), np.min(self.qB[-1])
            Qt = np.mean(self.qB[-1], axis=0) # integrate along \theta
            Qt = np.hstack((Qt, -Qt[::-1]))
            Q = cheb_quadrature_clencurt(rr*Qt)
            Qct = np.mean(self.qAc[-1], axis=0) # integrate along \theta
            Qct = np.hstack((Qct, -Qct[::-1]))
            Qc = cheb_quadrature_clencurt(rr*Qct)

            # Calculate density
            phiA0 = phiA
            phiB0 = phiB
            phiA = calc_density_2d(self.qA, self.qAc, self.ds) / Q
            phiB = calc_density_2d(self.qB, self.qBc, self.ds) / Q
            # Following codes are for strong surface interactions
            #fAy = np.mean(phiA, axis=0)
            #fBy = np.mean(phiB, axis=0)
            #fAy0 = fAy[0]; fAyL = fAy[-1]
            #fBy0 = fBy[0]; fByL = fBy[-1]
            #kaB = -self.kaA * fAy0 / fBy0
            #kbB = -self.kbA * fAyL / fByL
            #self.qB_solver.lbc.beta = kaB
            #self.qB_solver.rbc.beta = kbB
            #self.qB_solver.update()
            #self.qBc_solver.lbc.beta = kaB
            #self.qBc_solver.rbc.beta = kbB
            #self.qBc_solver.update()

            # Calculate energy
            ff = self.chiN*phiA*phiB - self.wA*phiA - self.wB*phiB
            F1t = np.mean(ff, axis=0)
            F1t = np.hstack((F1t,-F1t[::-1]))
            F1 = cheb_quadrature_clencurt(rr*F1t)
            F2 = -np.log(Q)
            F = F1 + F2

            if t % display_interval == 0:
                phiAB = phiA - phiB
                scft_contourf(x, y, phiAB)
                plt.xlabel('phiA-phiB')
                plt.show()
                plt.plot(r2, phiA[self.Nt/2])
                plt.plot(r2, phiB[self.Nt/2])
                plt.show()

            # Estimate error
            #resA = self.chiN*phiB - self.wA + self.yita # For incompressible model
            #resB = self.chiN*phiA - self.wB + self.yita # For incompressible model
            resY = phiA + phiB - 1.0
            resA = self.chiN*phiB + self.yita*resY - self.wA # For compressible model
            resB = self.chiN*phiA + self.yita*resY - self.wB # For compressible model
            err1 = 0.0
            err1 += np.mean(np.abs(resA))
            err1 += np.mean(np.abs(resB))
            #err1 += np.mean(np.abs(resY)) # For incompressible model
            err1 /= 2.
            err2 = 0.0
            err2 += np.linalg.norm(phiA-phiA0)
            err2 += np.linalg.norm(phiB-phiB0)

            if t % record_interval == 0 or err1 < thresh_residual:
                t_end = clock()
                ts.append(t)
                Fs.append(F)
                errs_residual.append(err1)
                errs_phi.append(err2)
                time = t_end - t_start
                times.append(time)
                phiA_meanx = np.mean(phiA, axis=0)
                phiA_meanx = np.hstack((phiA_meanx, -phiA_meanx[::-1]))
                phiA_mean = cheb_quadrature_clencurt(rr*phiA_meanx)
                phiB_meanx = np.mean(phiB, axis=0)
                phiB_meanx = np.hstack((phiB_meanx, -phiB_meanx[::-1]))
                phiB_mean = cheb_quadrature_clencurt(rr*phiB_meanx)
                print t, '\ttime =', time, '\tF =', F
                print '\tQ =', Q, '\tQc =', Qc
                print '\t<A> =', phiA_mean, '\t<B> =', phiB_mean
                print '\t<wA> =', np.mean(self.wA), '\t<wB> =', np.mean(self.wB)
                #print '\tyita =', self.yita
                #print '\tkaB =', self.qB_solver.lbc.beta,
                #print '\tkbB =', self.qB_solver.rbc.beta
                print '\terr1 =', err1, '\terr2 =', err2
                print
            if t % save_interval == 0:
                savemat(data_file+'_'+str(t), {'t':ts, 'time':times,
                                    'F':Fs,
                                    'err_residual':errs_residual,
                                    'err_phi':errs_phi,
                                    'phiA':phiA, 'wA':self.wA,
                                    'phiB':phiB, 'wB':self.wB,
                                    'yita':self.yita})
                if save_q:
                    savemat(q_file+'_'+str(t), {'qA':self.qA, 'qAc':self.qAc,
                                                'qB':self.qB, 'qBc':self.qBc})

            if err1 < thresh_residual:
                savemat(data_file+'_'+str(t), {'t':ts, 'time':times,
                                    'F':Fs,
                                    'err_residual':errs_residual,
                                    'err_phi':errs_phi,
                                    'phiA':phiA, 'wA':self.wA,
                                    'phiB':phiB, 'wB':self.wB,
                                    'yita':self.yita})
                if save_q:
                    savemat(q_file+'_'+str(t), {'qA':self.qA, 'qAc':self.qAc,
                                                'qB':self.qB, 'qBc':self.qBc})
                exit()

            # Update field
            self.wA = self.wA + self.lamA * resA
            self.wB = self.wB + self.lamB * resB