Esempio n. 1
0
def unittest_interpolation(fill='simplex', quadrature=QuadraturePatterson()):
    """Verify interpolation implementation against some function f().
    Plot key - black surface: original, red: reconstruction."""
    dim, level = 2, 5
    sp = SparseGrid(dim, quadrature, level=level, fill=fill)

    def f(x):
        return np.cos(2 * np.pi * x[0]) * np.cos(2 * np.pi * x[1] + 2)

    fval = sp.sample_fn(f)
    sx = np.array(sp.get_nodes().values())
    # Plotting interpolation
    M = 41
    x1 = np.linspace(0, 1, M)
    xy = mylib.meshgrid_flatten(x1, x1)
    X, Y = xy[:, 0].reshape(M, M), xy[:, 1].reshape(M, M)
    # 2d sampling
    F, Fa = np.zeros(xy.shape[0]), np.zeros(xy.shape[0])
    for i, x in enumerate(xy):
        F[i] = f(x)
        Fa[i] = sp.interpolate(x, fval)
        # Plotting
    if plt_loaded:
        from mpl_toolkits.mplot3d import Axes3D
        fig = plt.figure(figsize=(12, 8))
        ax = fig.add_subplot(111, projection='3d')
        ax.plot_wireframe(X, Y, F.reshape(M, M), colors='k')
        ax.plot_wireframe(X, Y, Fa.reshape(M, M), colors='r')
        ax.scatter(sx[:, 0], sx[:, 1], 0, c='k')
        fig.savefig('unittest_interpolation.pdf')
Esempio n. 2
0
def unittest_interpolation(fill='simplex', quadrature=QuadraturePatterson()):
    """Verify interpolation implementation against some function f().
    Plot key - black surface: original, red: reconstruction."""
    dim, level = 2, 5
    sp = SparseGrid(dim, quadrature, level=level, fill=fill)
    def f(x): return np.cos(2*np.pi*x[0])*np.cos(2*np.pi*x[1]+2)
    fval = sp.sample_fn(f)
    sx   = np.array(sp.get_nodes().values())
                                    # Plotting interpolation
    M    = 41
    x1   = np.linspace(0,1,M)
    xy   = mylib.meshgrid_flatten(x1, x1)
    X, Y = xy[:,0].reshape(M,M), xy[:,1].reshape(M,M)
                                    # 2d sampling
    F, Fa   = np.zeros(xy.shape[0]), np.zeros(xy.shape[0])
    for i,x in enumerate(xy):
        F[i]  = f(x)
        Fa[i] = sp.interpolate(x, fval)
                                    # Plotting
    if plt_loaded:
        from mpl_toolkits.mplot3d import Axes3D
        fig = plt.figure(figsize=(12,8))
        ax = fig.add_subplot(111, projection='3d')
        ax.plot_wireframe(X, Y, F.reshape(M,M), colors='k')
        ax.plot_wireframe(X, Y, Fa.reshape(M,M), colors='r')
        ax.scatter(sx[:,0], sx[:,1], 0, c='k') 
        fig.savefig('unittest_interpolation.pdf')
Esempio n. 3
0
 def init_full_factor(self, level):
     """
     Initialize with the full tensor-product (non-sparse) of level level>0.  
     This is just for reference purposes.
     """
     self.I = set([])
     for mi in mylib.meshgrid_flatten(*(range(1, level + 1), ) * self.dim):
         self.I |= set([tuple(mi)])
Esempio n. 4
0
 def __init__(self, quad, levelidx, delta=False):
     i_1d = [quad.idx[l-1] for l in levelidx]
     w = quad.dw if delta else quad.w
     w_1d = [w[l-1] for l in levelidx]
     self.delta    = delta           # Original rule or difference rule
     self.levelidx = levelidx
     self.dim      = len(self.levelidx)
     self.quad     = quad            # 1d quadrature rule
     self.nnodes   = np.array([quad.nnode(l-1) for l in self.levelidx])
     self.i        = mylib.meshgrid_flatten(*i_1d)
     self.w        = mylib.meshprod_flatten(*w_1d)
Esempio n. 5
0
 def __init__(self, quad, levelidx, delta=False):
     i_1d = [quad.idx[l - 1] for l in levelidx]
     w = quad.dw if delta else quad.w
     w_1d = [w[l - 1] for l in levelidx]
     self.delta = delta  # Original rule or difference rule
     self.levelidx = levelidx
     self.dim = len(self.levelidx)
     self.quad = quad  # 1d quadrature rule
     self.nnodes = np.array([quad.nnode(l - 1) for l in self.levelidx])
     self.i = mylib.meshgrid_flatten(*i_1d)
     self.w = mylib.meshprod_flatten(*w_1d)
Esempio n. 6
0
 def init_full_factor(self, l):
     """
     Initialize with the full tensor-product (non-sparse) of level l>0.  This
     is just for reference purposes, this call will be way too expensive in
     high-dimensions, and the implementation of this rule via sparse-grids is
     ridiculously convoluted.
     """
     self.active_to_old(0)
     Itmp = mylib.meshgrid_flatten( *(range(1,l+1),)*self.dim )
     for k in Itmp[1:]:              # 1st entry is already there
         i = self.add(k)
         if max(k) < l: self.active_to_old(i)
Esempio n. 7
0
 def init_full_factor(self, l):
     """
     Initialize with the full tensor-product (non-sparse) of level l>0.  This
     is just for reference purposes, this call will be way too expensive in
     high-dimensions, and the implementation of this rule via sparse-grids is
     ridiculously convoluted.
     """
     self.active_to_old(0)
     Itmp = mylib.meshgrid_flatten(*(range(1, l + 1), ) * self.dim)
     for k in Itmp[1:]:  # 1st entry is already there
         i = self.add(k)
         if max(k) < l: self.active_to_old(i)
Esempio n. 8
0
def plot_testfn():
    """Make contour plots of all 6 test functions in 2d."""
    assert plt_loaded, 'Matplotlib not installed'
    dim = 2
    global c, w
    c = np.array([0.5] * dim); c = c / sum(c) * 9.
    w = np.array([0.5] * dim)

    xi = np.linspace(0., 1., 100)
    xx = mylib.meshgrid_flatten(xi, xi)
    
    fig = plt.figure(figsize=(12, 8))
    for i in range(1, 7):
        fn = get_fn(i)
        ax = fig.add_subplot(2, 3, i)
        F = np.zeros(xx.shape[0])
        for i, x in enumerate(xx):
            F[i] = fn(np.array(x))
        F.reshape(xi.size, xi.size)
        ax.contour(xi, xi, F.reshape(xi.size, xi.size).T)

    fig.savefig('test_genz.contours.pdf')
Esempio n. 9
0
def plot_testfn():
    """Make contour plots of all 6 test functions in 2d."""
    assert plt_loaded, 'Matplotlib not installed'
    dim = 2
    global c, w
    c = np.array([0.5] * dim)
    c = c / sum(c) * 9.
    w = np.array([0.5] * dim)

    xi = np.linspace(0., 1., 100)
    xx = mylib.meshgrid_flatten(xi, xi)

    fig = plt.figure(figsize=(12, 8))
    for i in range(1, 7):
        fn = get_fn(i)
        ax = fig.add_subplot(2, 3, i)
        F = np.zeros(xx.shape[0])
        for i, x in enumerate(xx):
            F[i] = fn(np.array(x))
        F.reshape(xi.size, xi.size)
        ax.contour(xi, xi, F.reshape(xi.size, xi.size).T)

    fig.savefig('test_genz.contours.pdf')