Exemplo n.º 1
0
    def v_all(self, pol='H'):

        assert pol in ['H', 'L']
        ell = self._kern._lengthscale
        mi = cb.PolyBasis().mi_terms(self._input_dim, self._pol_order)
        v_all = np.ones((mi.shape[0], self._X.shape[0]))

        if pol == 'H':
            #print ell
            C = self._kern._var / np.sqrt(2. * np.pi)**(self._input_dim)
            for i in range(mi.shape[0]):
                for j in range(self._X.shape[0]):
                    for l in range(self._input_dim):
                        v_all[i, j] *= self.pi_H(mi[i, l], self._X[j, l],
                                                 ell[l])
                    v_all[i, j] *= C
            return v_all
        else:
            C = self._kern._var / (2**self._input_dim)
            PIs = np.zeros(
                (self._pol_order + 1, self._X.shape[0], self._X.shape[1]))
            order = np.min([self._pol_order, 10])
            quad = cb.QuadratureRule('CC').get_rule(1, order)

            for i in range(self._X.shape[0]):
                for j in range(self._X.shape[1]):
                    PIs[:, i, j] = self.pi_L_quad(self._pol_order, self._X[i,
                                                                           j],
                                                  ell[j], quad[0], quad[1])
            for i in range(mi.shape[0]):
                for j in range(self._X.shape[0]):
                    for l in range(self._X.shape[1]):
                        v_all[i, j] *= PIs[mi[i, l], j, l]
                    v_all[i, j] *= C
            return v_all
Exemplo n.º 2
0
    def u_all(self, pol='H'):

        assert pol in ['H', 'L']
        order = np.min([self._pol_order, 10])

        ell = self._kern._lengthscale
        mi = cb.PolyBasis().mi_terms(self._input_dim, self._pol_order)
        u_all = np.ones(mi.shape[0])
        if pol == 'H':
            C = self._kern._var / (2. * np.pi)**self._input_dim
            for i in range(mi.shape[0]):
                for j in range(mi.shape[1]):
                    u_all[i] *= self.rho_H(mi[i, j], mi[i, j], ell[j])
                u_all[i] *= C
            return u_all
        else:
            quad = cb.QuadratureRule('CC').get_rule(2, order)
            C = self._kern._var / (2.**(2 * self._input_dim))
            for i in range(mi.shape[0]):
                for j in range(mi.shape[1]):
                    u_all[i] *= self.rho_L_quad(mi[i, j], mi[i, j], ell[j],
                                                quad[0], quad[1])
                u_all[i] *= C
            return u_all
Exemplo n.º 3
0
                                                np.dot(np.dot(W, W.T), xi))


dim = 10
np.random.seed(1234)
W = np.random.normal(size=(dim, ))
W = W.reshape(W.shape[0], 1) / np.linalg.norm(W)
print(W)
a = np.random.normal()
b = np.random.normal()
c = np.random.normal()
print(a, b, c)

fig = plt.figure(figsize=(9, 6))
for l in range(1, 4):
    [x, w] = cb.QuadratureRule('GL').get_rule(10, l)
    print('-' * 10 + ' Level ' + str(l) + ' : ' + str(x.shape[0]) +
          ' abscissae')

    out = np.zeros(x.shape[0])
    for i in range(x.shape[0]):
        out[i] = f(x[i, :], a, b, c, W)

    pol = cb.PolyBasis(dim, degree=2, pol_type='L')
    P = pol(x)

    coeffs = np.dot(out * w, P)

    xi = st.uniform(loc=-1., scale=2.).rvs(size=(100, 10))
    out_mc = np.zeros(100)
    for i in range(100):
Exemplo n.º 4
0
import numpy as np 
import chaos_basispy as cb
import matplotlib.pyplot as plt


ker = lambda x: 1/2.
supp = [-1., 1.]

custom = {'pdf': ker, 'supp': supp}

quad = cb.QuadratureRule('custom_pdf')
quad2 = cb.QuadratureRule('GL')

[x1, w1] = quad.get_rule(2, 10, custom = custom)

[x2, w2] = quad2.get_rule(2, 11, False)

print(x1.shape, x2.shape)

fig = plt.figure(figsize = (12,5))
ax1 = fig.add_subplot(121)
ax1.plot(x1[:,0], x1[:,1], '.')
ax2 = fig.add_subplot(122)
ax2.plot(x2[:,0], x2[:,1], '.')
plt.show()

Exemplo n.º 5
0
                      -0.13708154, -0.14426375
                  ]])

    term1 = np.dot(a1, xx)
    term2 = np.dot(a2, np.sin(xx))
    term3 = np.dot(a3, np.cos(xx))
    term4 = np.dot(xx.T, np.dot(M, xx))
    return term1 + term2 + term3 + term4


xx = st.norm.rvs(size=(100000, 6))
f = np.zeros(xx.shape[0])
for i in range(xx.shape[0]):
    f[i] = ohagan(xx[i, :].reshape(6, 1))

[xx_quad, ww] = cb.QuadratureRule().get_rule(6, 5)
print(xx_quad.shape)
f_quad = np.zeros(xx_quad.shape[0])
for i in range(f_quad.shape[0]):
    f_quad[i] = ohagan(xx_quad[i, :].reshape(6, 1))
coeffs = cb.PolyChaos().comp_coeffs(xx_quad, f_quad, ww, degree=5)
print(coeffs.shape)

pol = cb.PolyBasis(6, 5, 'H')
P = pol(xx)
f_pc = np.dot(P, coeffs)

plt.hist(f, bins=100, density=True)
plt.hist(f_pc, bins=100, density=True)
plt.show()
Exemplo n.º 6
0
import numpy as np 
import chaos_basispy as cb
import matplotlib.pyplot as plt 

quad = cb.QuadratureRule('CC')
chaos = cb.PolyChaos()

[x2, w2] = quad.get_rule(2, 2)
[x3, w3] = quad.get_rule(2, 3)
[x4, w4] = quad.get_rule(2, 4)
[x5, w5] = quad.get_rule(2, 5)
[x6, w6] = quad.get_rule(2, 6)
[x7, w7] = quad.get_rule(2, 7)
[x8, w8] = quad.get_rule(2, 8)

x_quads = [x2, x3, x4, x5, x6, x7, x8]
w_quads = [w2, w3, w4, w5, w6, w7, w8]

loc_x, loc_y = -1, -1 # The spatial location of the QoI

u2 = np.load('u_quad_lev_2.npy')[loc_x,loc_y,:]
u3 = np.load('u_quad_lev_3.npy')[loc_x,loc_y,:]
u4 = np.load('u_quad_lev_4.npy')[loc_x,loc_y,:]
u5 = np.load('u_quad_lev_5.npy')[loc_x,loc_y,:]
u6 = np.load('u_quad_lev_6.npy')[loc_x,loc_y,:]
u7 = np.load('u_quad_lev_7.npy')[loc_x,loc_y,:]
u8 = np.load('u_quad_lev_8.npy')[loc_x,loc_y,:]

u_quads = [u2, u3, u4, u5, u6, u7, u8]

nx = u2.shape[0]
Exemplo n.º 7
0
        #if __name__ == '__main__':
        #    viewer.plot()
        #if step == 14 or step == 29 or step == 44 or  step == 59:
        #    dl = phi()[0]
        #    dr = phi()[nx-1]
        #    ul = phi()[nx**2 - nx]
        #    ur = phi()[nx**2 - 1]
        #    print phi().shape
        #    data = np.hstack([data, np.array([dl, dr, ul, ur])])

    #if __name__ == '__main__':
    #    raw_input("Transient diffusion with source term. Press <return> to proceed")

    return phi().reshape(nx, nx)


#plt.plot(x_quad[:,0], x_quad[:,1], '*')
#plt.show()
max_lev = 8
for l in range(2, max_lev + 1):
    print('-' * 5 + 'Running model at quadrature rule level ' + str(l) +
          ' points.' + '-' * 5)
    [x_quad, w_quad] = cb.QuadratureRule('CC').get_rule(2, l)

    u_quad = np.zeros((51, 51, x_quad.shape[0]))

    for i in range(x_quad.shape[0]):
        print('Run ' + str(i + 1))
        u_quad[:, :, i] = forward((x_quad[i, :] + np.ones(2)) / 2)

    np.save('u_quad_lev_' + str(l) + '.npy', u_quad)
Exemplo n.º 8
0
import chaos_basispy as cb
import numpy as np
import matplotlib.pyplot as plt

# Initialize a QuadratureRule object for each rule and generate a 2d sparse grid with level 4
rules = ['GH', 'GL', 'NC', 'CC', 'GLag']
dim = 2
lev = 4

fig = plt.figure(figsize=(10, 6))
for i in xrange(5):
    quadr = cb.QuadratureRule(rule=rules[i])
    [X, w] = quadr.get_rule(dim, lev)
    ax = fig.add_subplot(2, 3, i + 1)
    ax.plot(X[:, 0], X[:, 1], 'o', ms=3, alpha=0.8)
    ax.set_title(rules[i], fontsize=12)

plt.show()
Exemplo n.º 9
0
v = var * pi.T / np.sqrt(2 * np.pi)
cov = rbf.cov(X)
L = np.linalg.cholesky(cov)
scaled_data = np.linalg.solve(L.T, np.linalg.solve(L, Y[:, 0])).flatten()
m = np.dot(v, scaled_data)
T = np.linalg.solve(L, v.T)
print T.shape
C1 = var * rho / (2 * np.pi)
#print np.dot(T.T, T).shape
C = C1 - np.diag(np.dot(T.T, T))

print C

import chaos_basispy as cb
[quad_x, w] = cb.QuadratureRule('GH').get_rule(1, 3)
print quad_x.shape
sin_quad = np.sin(quad_x).flatten()

coeffs = cb.PolyChaos().comp_coeffs(quad_x, sin_quad, w, Q - 1)
#print coeffs.shape

pol = cb.PolyBasis(1, Q - 1)
xi = np.linspace(-4., 4., 100).reshape(100, 1)
P = pol(xi)
sinxi = np.sin(xi)
q_bayes = np.dot(P, m)
q_quad = np.dot(P, coeffs)

import matplotlib.pyplot as plt
Exemplo n.º 10
0
import chaos_basispy as cb
import numpy as np
import matplotlib.pyplot as plt


dim = 5
[x, w] = cb.QuadratureRule().get_rule(dim, 6, False)
xi = np.random.normal(size = (100000,5))

pol = cb.PolyBasis(dim, 5)
P_quad = pol(x)
P_MC = pol(xi)
n2_quad = np.dot(w, P_quad**2)
n2_MC = np.std(P_MC, axis = 0)

fig = plt.figure(figsize = (9,7))
ax1 = fig.add_subplot(221)
ax1.plot(x[:,0], x[:,1], 'o', ms = 3, alpha = 0.6)
ax1.set_title('G-H Quadrature ('+str(x.shape[0])+' points)', fontsize = 12)
ax2 = fig.add_subplot(222)
ax2.plot(xi[:,0], xi[:,1], 'o', ms = 2, alpha = 0.3)
ax2.set_title('Monte Carlo ('+r'$10^5$'+' points)', fontsize = 12)
ax3 = fig.add_subplot(223)
ax3.plot(n2_quad, '.', ms = 1.5)
ax3.set_ylim([-0.1,1.2])
ax3.set_xlabel('# of coefficient', fontsize = 12)
ax3.set_ylabel('L2 norm', fontsize = 12)
ax4 = fig.add_subplot(224)
ax4.plot(n2_MC, '.', ms = 1.5)
ax4.set_xlabel('# of coefficient', fontsize = 12)
plt.show()