def sparse_grid(H, persis_info, gen_specs, libE_info):
    """
    This generator,  mirrors the Tasmanian
    `sparse grid example <https://github.com/ORNL/TASMANIAN/blob/master/InterfacePython/example_sparse_grids_04.py>`_
    loops over the given precisions, producing a grid of points
    at which the `sim_f` should be evaluated. The points are communicated to the
    manager, who coordinates their evaluation. After function values are
    returned, they are used to update the model; the model is evaluated at a
    point of interest.
    """
    U = gen_specs['user']

    iNumInputs = U['NumInputs']
    iNumOutputs = U['NumOutputs']
    precisions = U['precisions']
    aPointOfInterest = U['x0']

    tag = None

    persis_info['aResult'] = {}

    for prec in precisions:
        # Generate Tasmanian grid
        grid = Tasmanian.makeGlobalGrid(iNumInputs, iNumOutputs, prec,
                                        "iptotal", "clenshaw-curtis")
        aPoints = grid.getNeededPoints()

        # Return the points of that need to be evaluated to the manager
        H0 = np.zeros(len(aPoints), dtype=gen_specs['out'])
        H0['x'] = aPoints

        # Receive values from manager
        tag, Work, calc_in = sendrecv_mgr_worker_msg(libE_info['comm'], H0)
        if tag in [STOP_TAG, PERSIS_STOP]:
            break
        aModelValues = calc_in['f']

        # Update surrogate on grid
        t = aModelValues.reshape((aModelValues.shape[0], iNumOutputs))
        t = t.flatten()
        t = np.atleast_2d(t).T
        grid.loadNeededPoints(t)

        # Evaluate grid
        aResult = grid.evaluate(aPointOfInterest)

        persis_info['aResult'][prec] = aResult

    return H0, persis_info, FINISHED_PERSISTENT_GEN_TAG
def example_10():

    print(
        "\n---------------------------------------------------------------------------------------------------\n"
    )
    print(
        "Example 10: comparison between local polynomial and wavelet grids\n")

    iNumInputs = 2  # using two inputs for testing

    # test the error on a uniform dense grid with 10K points
    iTestGridSize = 100
    dx = np.linspace(-1.0, 1.0, iTestGridSize)  # sample on a uniform grid
    aMeshX, aMeshY = np.meshgrid(dx, dx)
    aTestPoints = np.column_stack([
        aMeshX.reshape((iTestGridSize**2, 1)),
        aMeshY.reshape((iTestGridSize**2, 1))
    ])

    def get_error(grid, model, aTestPoints):
        aGridResult = grid.evaluateBatch(aTestPoints)
        aModelResult = np.empty((aTestPoints.shape[0], 1), np.float64)
        for i in range(aTestPoints.shape[0]):
            aModelResult[i, :] = model(aTestPoints[i, :])
        return np.max(np.abs(aModelResult[:, 0] - aGridResult[:, 0]))

    def sharp_model(aX):
        return np.ones((1, )) * aX[0] / (1.0 + 100.0 * np.exp(-10.0 * aX[1]))

    grid_poly = Tasmanian.makeLocalPolynomialGrid(iNumInputs,
                                                  1,
                                                  3,
                                                  iOrder=1,
                                                  sRule="localp")
    grid_wavelet = Tasmanian.makeWaveletGrid(iNumInputs, 1, 1, 1)

    print("            polynomial              wavelet")
    print("  points         error  points        error")

    fTolerance = 1.E-5
    while ((grid_poly.getNumNeeded() > 0)
           or (grid_wavelet.getNumNeeded() > 0)):
        Tasmanian.loadNeededValues(lambda x, tid: sharp_model(x), grid_poly, 4)
        Tasmanian.loadNeededValues(lambda x, tid: sharp_model(x), grid_wavelet,
                                   4)

        # print the results at this stage
        print("{0:>8d}{1:>14.4e}{2:>8d}{3:>14.4e}".format(
            grid_poly.getNumLoaded(),
            get_error(grid_poly, sharp_model, aTestPoints),
            grid_wavelet.getNumLoaded(),
            get_error(grid_wavelet, sharp_model, aTestPoints)))

        # setting refinement for each grid
        grid_poly.setSurplusRefinement(fTolerance, 0, "fds")
        grid_wavelet.setSurplusRefinement(fTolerance, 0, "fds")
Example #3
0
    def test_transform(self):
        """
        Approximate moments of a Gaussian random vector 
        
            X ~ N([3,4], [[2,1],[1,3]])
            
        by a sparse grid method based on the interval [-1,1]^2 
        """
        #
        # Define Sparse Grid on [-1,1]^2
        #
        dim = 2
        level = 40
        grid = Tasmanian.makeGlobalGrid(dim, 1, level, 'level',
                                        'gauss-legendre')
        n_points = grid.getNumPoints()
        y = grid.getPoints()

        #
        # Transform Points to Z~N(0,I)
        #
        z = norm.ppf(0.5 * y + 0.5)
        dz = 0.5**dim

        #
        # Define Gaussian Field
        #
        K = np.array([[2, 1], [1, 3]])
        m = np.array([3, 4])

        # Eigendecomposition
        lmd, V = np.linalg.eigh(K)
        lmd = lmd[::-1]
        V = V[:, ::-1]
        sqrtD = np.diag(np.sqrt(lmd))

        X = V.dot(sqrtD.dot(z.T))
        Y = X + np.tile(m[:, None], (1, n_points))

        #
        # Recompute mean and covariance matrix
        #
        w = grid.getQuadratureWeights() * dz
        ma = np.zeros(2)
        Ka = 0
        for i in range(n_points):
            ma += Y[:, i] * w[i]
            Ka += X[1, i] * X[0, i] * w[i]
Example #4
0
    def checkPathsVersions(self):
        '''
        Check different ways to specify the library path and check the
        version number.
        '''
        grid = Tasmanian.TasmanianSparseGrid()

        sVersion = "{0:1d}.{1:1d}".format(grid.getVersionMajor(),
                                          grid.getVersionMinor())
        self.assertEqual(sVersion, Tasmanian.__version__, "version mismatch")
        sLicense = grid.getLicense()
        self.assertEqual(sLicense, Tasmanian.__license__, "license mismatch")

        iVM = int(sVersion.split('.')[0])
        iVm = int(sVersion.split('.')[1])
        self.assertEqual(iVM, grid.getVersionMajor(), "version major mismatch")
        self.assertEqual(iVm, grid.getVersionMinor(), "version minor mismatch")
Example #5
0
def example_01():

    print(
        "\n---------------------------------------------------------------------------------------------------\n"
    )
    print("Example 1:  integrate f(x,y) = exp(-x^2) * cos(y),")
    print("            using clenshaw-curtis nodes and grid of type level")

    iNumDimensions = 2
    iLevel = 5

    fExactIntegral = 2.513723354063905e+00  # the exact integral

    grid = Tasmanian.SparseGrid()
    grid.makeGlobalGrid(iNumDimensions, 0, iLevel, "level", "clenshaw-curtis")
    aPoints = grid.getPoints()
    aWeights = grid.getQuadratureWeights()

    fApproximateIntegral = np.sum(aWeights * np.exp(-aPoints[:, 0]**2) *
                                  np.cos(aPoints[:, 1]))

    fError = np.abs(fApproximateIntegral - fExactIntegral)

    print("    at level: {0:1d}".format(iLevel))
    print("    the grid has: {0:1d}".format(grid.getNumPoints()))
    print("    integral: {0:1.14e}".format(fApproximateIntegral))
    print("       error: {0:1.14e}\n".format(fError))

    iLevel = 7

    grid.makeGlobalGrid(iNumDimensions, 0, iLevel, "level", "clenshaw-curtis")
    aPoints = grid.getPoints()
    aWeights = grid.getQuadratureWeights()

    fApproximateIntegral = np.sum(aWeights * np.exp(-aPoints[:, 0]**2) *
                                  np.cos(aPoints[:, 1]))

    fError = np.abs(fApproximateIntegral - fExactIntegral)

    print("    at level: {0:1d}".format(iLevel))
    print("    the grid has: {0:1d}".format(grid.getNumPoints()))
    print("    integral: {0:1.14e}".format(fApproximateIntegral))
    print("       error: {0:1.14e}\n".format(fError))
Example #6
0
    def testListedExceptions(self, llTests):
        grid = Tasmanian.SparseGrid()
        state = DREAM.State(10, 2)
        state.setState(
            DREAM.genGaussianSamples([-1.0, -1.0], [1.0, 1.0], 10,
                                     DREAM.RandomGenerator("minstd_rand", 42)))

        for lTest in llTests:
            try:
                exec(lTest[0])
                self.assertEqual(
                    lTest[1], "notError",
                    "failed to raise exception for invalid '{0:1s}' using test\n '{1:1s}'"
                    .format(lTest[1], lTest[0]))
            except Tasmanian.TasmanianInputError as TSGError:
                self.assertEqual(
                    TSGError.sVariable, lTest[1],
                    "error raising exception for '{0:1s}' using test\n '{1:1s}'\n Error.sVariable = '{2:1s}'"
                    .format(lTest[1], lTest[0], TSGError.sVariable))
Example #7
0
    def test_interpolant(self):
        dim = 1
        level = 3
        grid = Tasmanian.makeGlobalGrid(dim, 1, level, 'level',
                                        'gauss-hermite')
        #f = lambda x: np.exp(-np.abs(x))
        f = lambda x: np.sum(x**3, axis=1)[:, None]

        # Evaluate function at abscissae
        z = grid.getPoints()
        fz = f(z)

        # Store points in grid
        grid.loadNeededPoints(fz)

        # Evaluate on a finer grid
        x = np.linspace(-1, 1, 100)[:, None]
        y = grid.evaluateBatch(x)

        # Check accuracy
        self.assertTrue(np.allclose(y, f(x)))
Example #8
0
def hermite_rule(dimension, depth, type='level'):
    """
    Return the quadrature nodes and weights associated with the Hermite rule. 
    
    Parameters
    ----------
    dimension: int, 
        Dimension of the quadrature rule
        
    depth: int, 
        The interpolation 'degree' of the rule
        
    type: {level}, 
        The type of tensorization used 
        
        
    Returns
    -------
    z : double, 
        Quadrature nodes for rule.
        
    w: double, 
        Quadrature weights           
    """
    grid = Tasmanian.TasmanianSparseGrid()
    k = 4
    outputs = 0
    type = 'level'  # can be changed
    rule = 'gauss-hermite'  # appropriate for Gaussian fields
    grid.makeGlobalGrid(dimension, outputs, depth, type, rule)

    # Sample Points
    zzSG = grid.getPoints()
    z = np.sqrt(2) * zzSG  # transform to N(0,1)

    # Quadrature weights
    w = grid.getQuadratureWeights()
    w /= np.sqrt(np.pi)**k  # normalize weights

    return z, w
Example #9
0
    def test_standard_normal(self):
        """
        Test modes of a standard normal density 
        """
        # Initialize sparse grid
        dim = 1
        level = 3
        moments = [1, 0, 1, 0, 3]

        # Define Gauss-Hermite physicist's rule exp(-x**2)
        grid = Tasmanian.makeGlobalGrid(dim, 1, level, "level",
                                        "gauss-hermite")

        #
        # Explicit
        #
        for i in range(len(moments)):
            z = grid.getPoints()  # quadrature nodes
            w = grid.getQuadratureWeights()  # quadrature weights
            y = np.sqrt(2) * z  # transform to N(0,1)
            c_norm = np.sqrt(np.pi)**dim  # normalization constant
            mom_a = np.sum(w * (y[:, 0]**i)) / c_norm
            mom_e = moments[i]
            self.assertAlmostEqual(mom_a, mom_e)

        #
        # Using integrate
        #
        for i in range(len(moments)):
            z = grid.getPoints()  # quadrature nodes
            y = np.sqrt(2) * z  # transform to N(0,1)
            c_norm = np.sqrt(np.pi)**dim  # normalization constant

            grid.loadNeededPoints(y**i)
            mom_a = grid.integrate() / c_norm
            mom_e = moments[i]

            self.assertAlmostEqual(mom_a[0], mom_e)
def example_04():

    print(
        "\n---------------------------------------------------------------------------------------------------\n"
    )
    print(
        "Example 4: interpolate f(x,y) = exp(-x^2) * cos(y), using clenshaw-curtis iptotal rule"
    )

    iNumInputs = 2
    iNumOutputs = 1

    aPointOfInterest = np.array([0.3, 0.7])
    aReferenceSolution = np.exp(-aPointOfInterest[0]**2) * np.cos(
        aPointOfInterest[1])

    for prec in [6, 12]:
        grid = Tasmanian.makeGlobalGrid(iNumInputs, iNumOutputs, prec,
                                        "iptotal", "clenshaw-curtis")
        aPoints = grid.getNeededPoints()

        aModelValues = np.exp(-aPoints[:, 0]**2) * np.cos(aPoints[:, 1])
        grid.loadNeededValues(
            aModelValues.reshape((aModelValues.shape[0], iNumOutputs)))

        # when using multiple points at once, evaluateBatch() is more efficient
        aResult = grid.evaluate(aPointOfInterest)
        fError = np.abs(aResult[0] - aReferenceSolution)

        print("\n    using total degree polynomials: {0:>2d}th degree".format(
            prec))
        print("                      the grid has: {0:1d} points".format(
            grid.getNumPoints()))
        print("          interpolant at (0.3,0.7): {0:1.5e}".format(
            aResult[0]))
        print("                             error: {0:1.5e}".format(fError))
Example #11
0
    def checkLoadNeeded(self):
        '''
        Check the load needed construction procedure.
        '''
        gridA = Tasmanian.SparseGrid()
        gridB = Tasmanian.SparseGrid()

        for i in range(4):
            if i < 2:
                gridA.makeGlobalGrid(2, 1, 3, 'level', 'fejer2')
                gridB.copyGrid(gridA)
                Tasmanian.loadNeededValues(lambda x, i : np.ones((1,)) * np.exp(-np.sum(x**2)), gridA, i)
            else:
                gridA.makeLocalPolynomialGrid(2, 1, 2, 2)
                gridB.copyGrid(gridA)
                gridA.printStats()
                gridA.loadNeededPoints(np.ones((gridA.getNumPoints(), 1)))
                Tasmanian.reloadLoadedPoints(lambda x, i : np.ones((1,)) * np.exp(-np.sum(x**2)), gridA, i - 2)

            ttc.loadExpN2(gridB)
            ttc.compareGrids(gridA, gridB)
def example_08():

    print(
        "\n---------------------------------------------------------------------------------------------------\n"
    )
    print(
        "Example 8: interpolate different functions demonstrating the different"
    )
    print("           local polynomial rules\n")

    iNumInputs = 2  # using two inputs for testing

    # test the error on a uniform dense grid with 10K points
    iTestGridSize = 100
    dx = np.linspace(-1.0, 1.0, iTestGridSize)  # sample on a uniform grid
    aMeshX, aMeshY = np.meshgrid(dx, dx)
    aTestPoints = np.column_stack([
        aMeshX.reshape((iTestGridSize**2, 1)),
        aMeshY.reshape((iTestGridSize**2, 1))
    ])

    def get_error(grid, model, aTestPoints):
        aGridResult = grid.evaluateBatch(aTestPoints)
        aModelResult = np.empty((aTestPoints.shape[0], 1), np.float64)
        for i in range(aTestPoints.shape[0]):
            aModelResult[i, :] = model(aTestPoints[i, :])
        return np.max(np.abs(aModelResult[:, 0] - aGridResult[:, 0]))

    def smooth_model(aX):
        return np.ones((1, )) * np.exp(-aX[0]**2) * np.cos(aX[1])

    iOrder = 2
    grid_localp = Tasmanian.makeLocalPolynomialGrid(iNumInputs, 1, 7, iOrder,
                                                    "localp")
    grid_semilocalp = Tasmanian.makeLocalPolynomialGrid(
        iNumInputs, 1, 7, iOrder, "semi-localp")

    Tasmanian.loadNeededValues(lambda x, tid: smooth_model(x), grid_localp, 4)
    Tasmanian.loadNeededValues(lambda x, tid: smooth_model(x), grid_semilocalp,
                               4)

    print("Using smooth model: f(x, y) = exp(-x*x) * cos(y)")
    print(" rule_localp,     points = {0:1d}   error = {1:1.4e}".format(
        grid_localp.getNumPoints(),
        get_error(grid_localp, smooth_model, aTestPoints)))
    print(" rule_semilocalp, points = {0:1d}   error = {1:1.4e}".format(
        grid_semilocalp.getNumPoints(),
        get_error(grid_semilocalp, smooth_model, aTestPoints)))
    print(" If the model is smooth, rule_semilocalp has an advantage.\n")

    def zero_model(aX):
        return np.ones(
            (1, )) * np.cos(0.5 * np.pi * aX[0]) * np.cos(0.5 * np.pi * aX[1])

    grid_localp0 = Tasmanian.makeLocalPolynomialGrid(iNumInputs, 1, 6, iOrder,
                                                     "localp-zero")

    Tasmanian.reloadLoadedPoints(lambda x, tid: zero_model(x), grid_localp, 4)
    Tasmanian.loadNeededValues(lambda x, tid: zero_model(x), grid_localp0, 4)

    print(
        "Using homogeneous model: f(x, y) = cos(pi * x / 2) * cos(pi * y / 2)")
    print(" rule_localp,  points = {0:1d}   error = {1:1.4e}".format(
        grid_localp.getNumPoints(),
        get_error(grid_localp, zero_model, aTestPoints)))
    print(" rule_localp0, points = {0:1d}   error = {1:1.4e}".format(
        grid_localp0.getNumPoints(),
        get_error(grid_localp0, zero_model, aTestPoints)))
    print(" The rule_localp0 uses basis tuned for models with zero boundary.")
def example_09():

    print("\n---------------------------------------------------------------------------------------------------\n")
    print("Example 9: comparison between local polynomial refinement strategies\n")

    iNumInputs = 2 # using two inputs for testing

    # test the error on a uniform dense grid with 10K points
    iTestGridSize = 100
    dx = np.linspace(-1.0, 1.0, iTestGridSize) # sample on a uniform grid
    aMeshX, aMeshY = np.meshgrid(dx, dx)
    aTestPoints = np.column_stack([aMeshX.reshape((iTestGridSize**2, 1)),
                                   aMeshY.reshape((iTestGridSize**2, 1))])

    def get_error(grid, model, aTestPoints):
        aGridResult = grid.evaluateBatch(aTestPoints)
        aModelResult = np.empty((aTestPoints.shape[0], 1), np.float64)
        for i in range(aTestPoints.shape[0]):
            aModelResult[i,:] = model(aTestPoints[i,:])
        return np.max(np.abs(aModelResult[:,0] - aGridResult[:,0]))

    def sharp_model(aX):
        return np.ones((1,)) * np.exp(-aX[0]) / (1.0 + 100.0 * np.exp(-10.0 * aX[1]))

    grid_classic = Tasmanian.makeLocalPolynomialGrid(iNumInputs, 1, 2,
                                                     iOrder = -1, sRule = "localp")
    grid_fds = Tasmanian.copyGrid(grid_classic)

    print("Using batch refinement:")
    print("               classic                  fds")
    print("  points         error  points        error")

    fTolerance = 1.E-5;
    while((grid_classic.getNumNeeded() > 0) or (grid_fds.getNumNeeded() > 0)):
        Tasmanian.loadNeededPoints(lambda x, tid: sharp_model(x), grid_classic, 4);
        Tasmanian.loadNeededPoints(lambda x, tid: sharp_model(x), grid_fds, 4);

        # print the results at this stage
        print("{0:>8d}{1:>14.4e}{2:>8d}{3:>14.4e}".format(
            grid_classic.getNumLoaded(), get_error(grid_classic, sharp_model, aTestPoints),
            grid_fds.getNumLoaded(), get_error(grid_fds, sharp_model, aTestPoints)))

        # setting refinement for each grid
        grid_classic.setSurplusRefinement(fTolerance, 0, "classic");
        grid_fds.setSurplusRefinement(fTolerance, 0, "fds");

    # reset the grid and repeat using construction
    grid_classic = Tasmanian.makeLocalPolynomialGrid(iNumInputs, 1, 2,
                                                     iOrder = -1, sRule = "localp")
    grid_fds.copyGrid(grid_classic)

    print("\nUsing construction:")
    print("               classic                  fds")
    print("  points         error  points        error")

    iNumThreads = 1
    for budget in range(50, 800, 100):
        Tasmanian.constructSurplusSurrogate(
            lambda x, tid : sharp_model(x.reshape((2,))).reshape((1,1)),
            budget, iNumThreads, 1, grid_classic, fTolerance, "classic")
        Tasmanian.constructSurplusSurrogate(
            lambda x, tid : sharp_model(x.reshape((2,))).reshape((1,1)),
            budget, iNumThreads, 1, grid_fds, fTolerance, "fds")

        print("{0:>8d}{1:>14.4e}{2:>8d}{3:>14.4e}".format(
            grid_classic.getNumLoaded(), get_error(grid_classic, sharp_model, aTestPoints),
            grid_fds.getNumLoaded(), get_error(grid_fds, sharp_model, aTestPoints)))
Example #14
0
    def performExceptionsTest(self):
        grid = Tasmanian.SparseGrid()

        # The list llTest contains list-of-lists (could make into tuples)
        # Each sub-list (tuple) has two entries, one is the command that should raise the exception,
        # the second is the "sError" variable in the exception class.
        # notError tests here are needed to ensure that the multi-statement commands fail for the correct function.
        llTests = [
            [
                "grid.makeGlobalGrid(-1, 1,  4, 'level', 'clenshaw-curtis')",
                "iDimension"
            ],
            [
                "grid.makeGlobalGrid(2, -1,  4, 'level', 'clenshaw-curtis')",
                "iOutputs"
            ],
            [
                "grid.makeGlobalGrid(2,  1, -4, 'level', 'clenshaw-curtis')",
                "iDepth"
            ],
            [
                "grid.makeGlobalGrid(2,  1,  4, 'wrong', 'clenshaw-curtis')",
                "sType"
            ],
            [
                "grid.makeGlobalGrid(2,  1,  4, 'level', 'clenshaw-wrong')",
                "sRule"
            ],
            [
                "grid.makeGlobalGrid(2,  1,  4, 'level', 'clenshaw-curtis', [1,2,3])",
                "liAnisotropicWeights"
            ],
            [
                "grid.makeGlobalGrid(2,  1,  4, 'level', 'clenshaw-curtis', [1,2], liLevelLimits = [1, 2, 3])",
                "liLevelLimits"
            ],
            [
                "grid.makeGlobalGrid(2,  1,  4, 'level', 'clenshaw-curtis', [1,2], liLevelLimits = [1, 2])",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(-1, 1,  4, 'level', 'leja')",
                "iDimension"
            ],
            ["grid.makeSequenceGrid(2, -1,  4, 'level', 'leja')", "iOutputs"],
            ["grid.makeSequenceGrid(2,  1, -4, 'level', 'leja')", "iDepth"],
            ["grid.makeSequenceGrid(2,  1,  4, 'wrong', 'leja')", "sType"],
            ["grid.makeSequenceGrid(2,  1,  4, 'level', 'weja')", "sRule"],
            [
                "grid.makeSequenceGrid(2,  1,  4, 'level', 'leja', [1, 2, 3])",
                "liAnisotropicWeights"
            ],
            [
                "grid.makeSequenceGrid(2,  1,  4, 'level', 'leja', [1, 2], [1, 2, 3])",
                "liLevelLimits"
            ],
            [
                "grid.makeSequenceGrid(2,  1,  4, 'level', 'leja', liLevelLimits = [1, 2])",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(-1, 1,  4,  2, 'localp')",
                "iDimension"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, -1,  4,  2, 'localp')",
                "iOutputs"
            ],
            [
                "grid.makeLocalPolynomialGrid(2,  1, -4,  2, 'localp')",
                "iDepth"
            ],
            [
                "grid.makeLocalPolynomialGrid(2,  1,  4, -2, 'localp')",
                "iOrder"
            ],
            [
                "grid.makeLocalPolynomialGrid(2,  1,  4,  2, 'lowrong')",
                "sRule"
            ],
            [
                "grid.makeLocalPolynomialGrid(2,  1,  4,  2, 'localp', [1, 2, 3])",
                "liLevelLimits"
            ],
            [
                "grid.makeLocalPolynomialGrid(2,  1,  4,  2, 'localp', [1, 2])",
                "notError"
            ],
            ["grid.makeWaveletGrid(-1, 1,  4,  1)", "iDimension"],
            ["grid.makeWaveletGrid(2, -1,  4,  1)", "iOutputs"],
            ["grid.makeWaveletGrid(2,  1, -4,  3)", "iDepth"],
            ["grid.makeWaveletGrid(2,  1,  4,  2)", "iOrder"],
            [
                "grid.makeWaveletGrid(2,  1,  4,  1, [1, 2, 3])",
                "liLevelLimits"
            ],
            ["grid.makeWaveletGrid(2,  1,  4,  1, [2, 1])", "notError"],
            ["grid.makeFourierGrid(-1, 1,  4, 'level')", "iDimension"],
            ["grid.makeFourierGrid(2, -1,  4, 'level')", "iOutputs"],
            ["grid.makeFourierGrid(2,  1, -4, 'level')", "iDepth"],
            ["grid.makeFourierGrid(2,  1,  4, 'wrong')", "sType"],
            [
                "grid.makeFourierGrid(2,  1,  4, 'level', [1, 2, 3])",
                "liAnisotropicWeights"
            ],
            [
                "grid.makeFourierGrid(2,  1,  4, 'level', [1, 2], [1, 2, 3])",
                "liLevelLimits"
            ],
            [
                "grid.makeFourierGrid(2,  1,  4, 'level', liLevelLimits = [1, 2])",
                "notError"
            ],
            ["grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja')", "notError"],
            ["grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev')", "notError"],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2]))",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateGlobalGrid(1,'iptotal')",
                "updateGlobalGrid"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev'); grid.updateGlobalGrid(-1,'iptotal')",
                "iDepth"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev'); grid.updateGlobalGrid(4,'wrong')",
                "sType"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev'); grid.updateGlobalGrid(4,'iptotal',[1,2,3])",
                "liAnisotropicWeights"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev'); grid.updateGlobalGrid(4,'iptotal',liLevelLimits = [1,2,3])",
                "liLevelLimits"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev'); grid.updateGlobalGrid(4,'iptotal',liLevelLimits = [1,2])",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'rleja'); grid.updateSequenceGrid(4,'iptotal')",
                "updateSequenceGrid"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateSequenceGrid(-1,'iptotal')",
                "iDepth"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateSequenceGrid(4,'wrong')",
                "sType"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateSequenceGrid(4,'iptotal',[1,2,3])",
                "liAnisotropicWeights"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateSequenceGrid(4,'iptotal',liLevelLimits = [1,2,3])",
                "liLevelLimits"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateSequenceGrid(4,'iptotal',liLevelLimits = [2,3])",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.updateFourierGrid(3,'level')",
                "updateFourierGrid"
            ],
            [
                "grid.makeFourierGrid(2, 1, 2, 'level'); grid.updateFourierGrid(-3,'level')",
                "iDepth"
            ],
            [
                "grid.makeFourierGrid(2, 1, 2, 'level'); grid.updateFourierGrid(3,'wrong')",
                "sType"
            ],
            [
                "grid.makeFourierGrid(2, 1, 2, 'level'); grid.updateFourierGrid(3,'iptotal',[1])",
                "liAnisotropicWeights"
            ],
            [
                "grid.makeFourierGrid(2, 1, 2, 'level'); grid.updateFourierGrid(3,'iptotal',liLevelLimits = [4])",
                "liLevelLimits"
            ],
            [
                "grid.makeFourierGrid(2, 1, 2, 'level'); grid.updateFourierGrid(3,'iptotal', [4, 3], [4, 3])",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); aW = grid.getInterpolationWeights(np.array([1,2,3]))",
                "lfX"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); aW = grid.getInterpolationWeightsBatch(np.array([1,2,3]))",
                "llfX"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); aW = grid.getInterpolationWeightsBatch(np.array([[1,2,3],[1,2,3]]))",
                "llfX"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([1,]))",
                "llfVals"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,3]))",
                "llfVals"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([5,2]))",
                "llfVals"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.loadNeededPoints(np.ones([5,2]))",
                "llfVals"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.evaluate(np.zeros([1,2]))",
                "evaluate"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.evaluateThreadSafe(np.zeros(np.array([1,2])))",
                "evaluateThreadSafe"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.evaluate(np.zeros([1,3]))",
                "lfX"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.evaluate(np.zeros([3]))",
                "lfX"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.evaluateThreadSafe(np.zeros([1,3]))",
                "lfX"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.evaluateThreadSafe(np.zeros([3]))",
                "lfX"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.evaluateBatch(np.zeros([1,2]))",
                "evaluateBatch"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.evaluateBatch(np.zeros([1,3]))",
                "llfX"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.loadNeededPoints(np.zeros([6,2])); grid.evaluateBatch(np.zeros([2,]))",
                "llfX"
            ],
            [
                "grid.makeSequenceGrid(2, 2, 2, 'level', 'rleja'); grid.integrate()",
                "integrate"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'gauss-legendre'); grid.setDomainTransform(np.zeros([2,]))",
                "llfTransform"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'gauss-legendre'); grid.setDomainTransform(np.zeros([2,1]))",
                "llfTransform"
            ],
            [
                "grid.makeGlobalGrid(3, 1, 2, 'level', 'gauss-legendre'); grid.setDomainTransform(np.zeros([2,2]))",
                "llfTransform"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'gauss-legendre')",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(3, 1, 2, 'level', 'gauss-legendre'); grid.setDomainTransform(np.zeros([3,2]))",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(3, 1, 2, 'level', 'clenshaw-curtis');",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(3, 1, 2, 'level', 'clenshaw-curtis'); grid.setConformalTransformASIN(np.array([0,2,4]))",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(3, 1, 2, 'level', 'clenshaw-curtis'); grid.setConformalTransformASIN(np.array([0,2]))",
                "liTruncation"
            ],
            [
                "grid.makeGlobalGrid(3, 1, 2, 'level', 'clenshaw-curtis'); grid.setConformalTransformASIN(np.array([[0,2,3],[1,2,3]]))",
                "liTruncation"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'rleja'); grid.setAnisotropicRefinement('iptotal', 10, 1);",
                "setAnisotropicRefinement"
            ],
            [
                "grid.makeGlobalGrid(2, 0, 2, 'level', 'clenshaw-curtis'); grid.setAnisotropicRefinement('iptotal', 10, 1);",
                "setAnisotropicRefinement"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'fejer2'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', -2, 1);",
                "iMinGrowth"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, -1);",
                "iOutput"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, 0);",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, 0, [2, 3]);",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, 0, [2, 3, 3]);",
                "liLevelLimits"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, -1);",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, -2);",
                "iOutput"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, 5);",
                "iOutput"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('wrong', 10, 0);",
                "sType"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, -1, [3, 4]);",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.setAnisotropicRefinement('iptotal', 10, -1, [3, 4, 5]);",
                "liLevelLimits"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'rleja'); grid.estimateAnisotropicCoefficients('iptotal', 1);",
                "estimateAnisotropicCoefficients"
            ],
            [
                "grid.makeGlobalGrid(2, 0, 2, 'level', 'clenshaw-curtis'); grid.estimateAnisotropicCoefficients('iptotal', 1);",
                "estimateAnisotropicCoefficients"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); ttc.loadExpN2(grid); grid.estimateAnisotropicCoefficients('iptotal', -1);",
                "iOutput"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.estimateAnisotropicCoefficients('iptotal', -1);",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.estimateAnisotropicCoefficients('ipcurved', -1);",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.estimateAnisotropicCoefficients('iptotal', -2);",
                "iOutput"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.estimateAnisotropicCoefficients('iptotal', 5);",
                "iOutput"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 3, 'iptotal', 'leja'); ttc.loadExpN2(grid); grid.estimateAnisotropicCoefficients('wrong', 0);",
                "sType"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); grid.setSurplusRefinement(1.E-4, 0, 'classic');",
                "setSurplusRefinement"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); grid.setSurplusRefinement(1.E-4, 0, 'classic');",
                "setSurplusRefinement"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); ttc.loadExpN2(grid); grid.setSurplusRefinement(-1.E-4, 0, 'classic');",
                "fTolerance"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic');",
                "sCriteria"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0);",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, '', [2, 3, 4]);",
                "liLevelLimits"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, '', [2, 3]);",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0);",
                "sCriteria"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'class');",
                "sCriteria"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic');",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic', [2, 3, 4]);",
                "liLevelLimits"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic', [], np.ones([3]));",
                "llfScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic', [], np.ones([grid.getNumPoints() - 1, 1]));",
                "llfScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic', [], np.ones([grid.getNumPoints(), 2]));",
                "llfScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 2, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, -1, 'classic', [], np.ones([grid.getNumPoints(), 2]));",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 2, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, -1, 'classic', [], np.ones([grid.getNumPoints(), 3]));",
                "llfScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.setSurplusRefinement(1.E-4, 0, 'classic', [2, 3]);",
                "notError"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); grid.removePointsByHierarchicalCoefficient(1.E-4, 0);",
                "removePointsByHierarchicalCoefficient"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.removePointsByHierarchicalCoefficient(-1.E-4, 0);",
                "fTolerance"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.removePointsByHierarchicalCoefficient(1.E-4, -2);",
                "iOutput"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.removePointsByHierarchicalCoefficient(1.E-4, 3);",
                "iOutput"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.removePointsByHierarchicalCoefficient(1.E-4, 0);",
                "removePointsByHierarchicalCoefficient"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); ttc.loadExpN2(grid); grid.removePointsByHierarchicalCoefficient(1.E-4, 0);",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, -1, np.ones([3,]));",
                "aScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, -1, np.ones([10,]));",
                "aScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, -1, np.ones([11,2]));",
                "aScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, -1, np.ones([13,2]));",
                "aScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, -1, np.ones([13,3]));",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, 0,  np.ones([13,3]));",
                "aScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, 0,  np.ones([11,]));",
                "aScaleCorrection"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 3, 2, 1, 'localp'); grid.loadNeededPoints(np.ones([grid.getNumNeeded(), grid.getNumOutputs()])); grid.removePointsByHierarchicalCoefficient(1.E-4, 0,  np.ones([13,]));",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); grid.evaluateHierarchicalFunctions(np.array([[1.0, 1.0], [0.5, 0.3]]));",
                "notError"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); grid.evaluateHierarchicalFunctions(np.array([[1.0,], [0.5,]]));",
                "llfX"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis'); grid.evaluateHierarchicalFunctions(np.array([1.0, 1.0]));",
                "llfX"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.evaluateSparseHierarchicalFunctions(np.array([[1.0, 1.0], [0.5, 0.3]]));",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.evaluateSparseHierarchicalFunctions(np.array([[1.0,], [0.5,]]));",
                "llfX"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.evaluateSparseHierarchicalFunctions(np.array([1.0, 1.0]));",
                "llfX"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.setHierarchicalCoefficients(np.array([1.0, 1.0]));",
                "llfCoefficients"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 2, 1, 'localp'); grid.setHierarchicalCoefficients(np.array([[1.0, 1.0],]));",
                "llfCoefficients"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.setHierarchicalCoefficients(np.array([[1.0, 1.0],[1.0, 1.0],[1.0, 1.0],[1.0, 1.0],[1.0, 1.0],]));",
                "llfCoefficients"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.setHierarchicalCoefficients(np.array([[1.0,],[1.0,],[1.0,],[1.0,],[1.0,]]));",
                "notError"
            ],
            [
                "grid.makeFourierGrid(2, 1, 1, 'level'); grid.setHierarchicalCoefficients(np.array([[1.0,],[1.0,],[1.0,],[1.0,],[1.0,]]));",
                "llfCoefficients"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 3, 'level', 'rleja'); grid.getCandidateConstructionPoints('level', -1);",
                "getCandidateConstructionPoints"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 3, 'level', 'rleja'); grid.beginConstruction(); grid.getCandidateConstructionPoints('lev', -1);",
                "sType"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 3, 'level', 'rleja'); grid.beginConstruction(); grid.getCandidateConstructionPoints('level', [0]);",
                "liAnisotropicWeightsOrOutput"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 3, 'level', 'rleja'); grid.beginConstruction(); grid.getCandidateConstructionPoints('level', 'string');",
                "liAnisotropicWeightsOrOutput"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 3, 'level', 'rleja'); grid.beginConstruction(); grid.getCandidateConstructionPoints('level', -1, [2]);",
                "liLevelLimits"
            ],
            [
                "grid.makeGlobalGrid(2, 1, 3, 'level', 'rleja'); grid.beginConstruction(); grid.getCandidateConstructionPoints('level', -1, [2, 1]);",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.getCandidateConstructionPointsSurplus(1.E-5, 'classic');",
                "getCandidateConstructionPointsSurplus"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.getCandidateConstructionPointsSurplus(1.E-5, 'classic', 0, [2]);",
                "liLevelLimits"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.getCandidateConstructionPointsSurplus(1.E-5, 'classic', -1, [2, 3]);",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([0.0, 0.0], [1.0]);",
                "notError"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.loadConstructedPoint([0.0, 0.0], [1.0]);",
                "loadConstructedPoint"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([0.0], [1.0]);",
                "lfX"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([0.0, 0.0], [1.0, 2.0]);",
                "lfY"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([[0.0, 0.0], [1.0, 0.0]], [1.0, 2.0]);",
                "lfY"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([[0.0,], [1.0,]], [[1.0,], [2.0,]]);",
                "lfX"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([[0.0, 0.0], [1.0, 0.0]], [[1.0, 2.0], [1.0, 2.0]]);",
                "lfY"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([[0.0, 0.0], [1.0, 0.0]], [[1.0,], [2.0,], [3.0,]]);",
                "lfY"
            ],
            [
                "grid.makeLocalPolynomialGrid(2, 1, 1, 1, 'localp'); grid.beginConstruction(); grid.loadConstructedPoint([[[0.0, 0.0], [1.0, 0.0]],], [[1.0,], [2.0,]]);",
                "lfX"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); grid.enableAcceleration('gpu-wrong');",
                "sAccelerationType"
            ],
            [
                "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja'); grid.enableAcceleration('gpu-default');",
                "notError"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.isAccelerationAvailable('cpu-wrong');",
                "sAccelerationType"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.isAccelerationAvailable('cpu-blas');",
                "notError"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.getGPUMemory(-1);",
                "iGPUID"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.getGPUMemory(1000000);",
                "iGPUID"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.getGPUMemory(grid1.getNumGPUs());",
                "iGPUID"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.getGPUName(-1);",
                "iGPUID"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.getGPUName(1000000);",
                "iGPUID"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.getGPUName(grid1.getNumGPUs());",
                "iGPUID"
            ],
            ["grid1 = Tasmanian.SparseGrid(); grid1.setGPUID(-1);", "iGPUID"],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.setGPUID(1000000);",
                "iGPUID"
            ],
            [
                "grid1 = Tasmanian.SparseGrid(); grid1.setGPUID(grid1.getNumGPUs());",
                "iGPUID"
            ],
        ]

        for lTest in llTests:
            try:
                exec(lTest[0])
                self.assertEqual(
                    lTest[1], "notError",
                    "failed to raise exception for invalid '{0:1s}' using test\n '{1:1s}'"
                    .format(lTest[1], lTest[0]))
            except Tasmanian.TasmanianInputError as TSGError:
                self.assertEqual(
                    TSGError.sVariable, lTest[1],
                    "error raising exception for '{0:1s}' using test\n '{1:1s}'\n Error.sVariable = '{2:1s}'"
                    .format(lTest[1], lTest[0], TSGError.sVariable))
Example #15
0
    def checkConstruction(self):
        gridA = Tasmanian.SparseGrid()
        gridB = Tasmanian.SparseGrid()

        for i in range(12):
            if i < 2:
                gridA.makeGlobalGrid(2, 1, 3, 'level', 'fejer2')
                gridB.copyGrid(gridA)
                Tasmanian.constructAnisotropicSurrogate(
                    lambda x, i: np.ones((1, 1)) * np.exp(-np.sum(x**2)),
                    gridA.getNumPoints(), i, 1, gridA, "hyperbolic", 0)
            elif i < 4:
                gridA.makeGlobalGrid(2, 1, 3, 'level', 'min-lebesgue')
                gridB.copyGrid(gridA)
                Tasmanian.constructAnisotropicSurrogate(
                    lambda x, y, i: np.ones((1, 1)) * np.exp(-np.sum(x**2)),
                    gridA.getNumPoints(),
                    i - 2,
                    1,
                    gridA,
                    "ipcurved", (6, 5, 1, 1),
                    bUseInitialGuess=True,
                    sCheckpointFilename="cpf_addons")
                os.remove("cpf_addons")
            elif i < 6:
                gridA.makeGlobalGrid(2,
                                     1,
                                     3,
                                     'level',
                                     'min-delta',
                                     liLevelLimits=(5, 5))
                gridB.copyGrid(gridA)
                gridA.clearLevelLimits()
                Tasmanian.constructAnisotropicSurrogate(lambda x, i: np.ones(
                    (1, 1)) * np.exp(-np.sum(x**2)),
                                                        gridA.getNumPoints(),
                                                        i - 4,
                                                        1,
                                                        gridA,
                                                        "iplevel", (1, 2),
                                                        liLevelLimits=(5, 5),
                                                        bUseInitialGuess=False)
            elif i < 8:
                gridA.makeGlobalGrid(2,
                                     1,
                                     3,
                                     'level',
                                     'min-delta',
                                     liLevelLimits=(10, 10))
                gridB.copyGrid(gridA)
                gridA.clearLevelLimits()
                Tasmanian.constructAnisotropicSurrogate(
                    lambda x, y, i: np.ones((1, 1)) * np.exp(-np.sum(x**2)),
                    gridA.getNumPoints(),
                    i - 6,
                    1,
                    gridA,
                    "iplevel",
                    0,
                    liLevelLimits=(10, 10),
                    bUseInitialGuess=True)
            elif i < 10:
                gridA.makeLocalPolynomialGrid(2, 1, 2, 2, liLevelLimits=(7, 7))
                gridB.copyGrid(gridA)
                gridA.clearLevelLimits()
                Tasmanian.constructSurplusSurrogate(lambda x, y, i: np.ones(
                    (1, 1)) * np.exp(-np.sum(x**2)),
                                                    gridA.getNumPoints(),
                                                    i - 8,
                                                    1,
                                                    gridA,
                                                    1.E-5,
                                                    "stable",
                                                    -1,
                                                    liLevelLimits=(7, 7),
                                                    bUseInitialGuess=True)
            elif i < 12:
                gridA.makeLocalPolynomialGrid(2, 1, 2, 3)
                gridB.copyGrid(gridA)
                Tasmanian.constructSurplusSurrogate(
                    lambda x, i: np.ones((1, 1)) * np.exp(-np.sum(x**2)),
                    gridA.getNumPoints(),
                    i - 10,
                    1,
                    gridA,
                    1.E-5,
                    "fds",
                    0,
                    bUseInitialGuess=False,
                    sCheckpointFilename="cpf_addons")
                os.remove("cpf_addons")

            ttc.loadExpN2(gridB)
            gridA.finishConstruction()
            ttc.compareGrids(gridA, gridB)
Example #16
0
# set input record
inpRec = dict()
inpRec['restart'] = False
inpRec['method'] = 'NVE'
inpRec['N_per'] = 3
inpRec['M'] = np.reshape(M, (M.size, ))  # units = amu
inpRec['Temp'] = Temp  # units = K
inpRec['dt'] = 0.1  # units = fs
inpRec['Tfinal'] = Tfinal  # units = fs
# need bounds since domains must be on same scale within the MD simulator
inpRec['bounds'] = [[-180, 180], [-180, 180], [-180, 180], [1.1, 2.5],
                    [90, 270]]  # units = GIC
inpRec['Gamma'] = 0.001  # units = fs^(-1)

# PES
sg_energy = tsg.SparseGrid()
sg_energy.makeGlobalGrid(5, 1, 12, 'iptotal', 'clenshaw-curtis')
sg_energy.setDomainTransform(
    np.asarray([[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]))
N_poly = len(sg_energy.getPoints())

dataE = ev2ieu * np.loadtxt('%s/energy.dat' % state_folder)
dataE = np.reshape(dataE, (N_poly, 1))
sg_energy.loadNeededPoints(dataE)

inpRec['UQ'] = lambda Q: sg_energy.evaluate(pbcfun(Q, inpRec['N_per']))
inpRec['dUdQ'] = lambda Q: eval_grad(pbcfun(Q, inpRec['N_per']), sg=sg_energy)

# Cartesian geometry
sg_geom = tsg.SparseGrid()
sg_geom.makeGlobalGrid(5, 3 * N_atom, 12, 'iptotal', 'clenshaw-curtis')
 def make_grid(iPrecision, sRule):
     grid = Tasmanian.makeGlobalGrid(4, 0, iPrecision, "qptotal", sRule)
     grid.setDomainTransform(
         np.array([[-5.0, 5.0], [-5.0, 5.0], [-2.0, 3.0], [-2.0, 3.0]]))
     return grid
Example #18
0
import unittest
import Tasmanian
DREAM = Tasmanian.DREAM
import numpy as np

import testCommon

ttc = testCommon.TestTasCommon()

# tests should pass when errors are raised, thus suppress the verbose error messages
# to avoid confusing a verbose message with a real error (i.e., failed test)
Tasmanian.useVerboseErrors(False)

class TestTasClass(unittest.TestCase):
    '''
    Test the python exceptions, create a bunch of incorrect faults and
    check whether the correct exception is raised.
    '''
    def __init__(self):
        unittest.TestCase.__init__(self, "testNothing")

    def testNothing(self):
        pass

    def getSparseGridTests(self):
        # The list llTest contains list-of-lists (could make into tuples)
        # Each sub-list (tuple) has two entries, one is the command that should raise the exception,
        # the second is the "sError" variable in the exception class.
        # notError tests here are needed to ensure that the multi-statement commands fail for the correct function.
        return    [["grid.makeGlobalGrid(-1, 1,  4, 'level', 'clenshaw-curtis')", "iDimension"],
                   ["grid.makeGlobalGrid(2, -1,  4, 'level', 'clenshaw-curtis')", "iOutputs"],
Example #19
0
def example_05():

    print(
        "\n---------------------------------------------------------------------------------------------------\n"
    )
    print(
        "Example 5: interpolate f(x,y) = exp(-x^2) * cos(y), using leja rule")
    print(
        "           employ adaptive refinement to increase accuracy per samples"
    )

    iNumInputs = 2
    iNumOutputs = 1

    def model(aX):
        return np.ones((1, )) * np.exp(-aX[0] * aX[0]) * np.cos(aX[1])

    iTestGridSize = 33
    dx = np.linspace(-1.0, 1.0, iTestGridSize)  # sample on a uniform grid
    aMeshX, aMeshY = np.meshgrid(dx, dx)
    aTestPoints = np.column_stack([
        aMeshX.reshape((iTestGridSize**2, 1)),
        aMeshY.reshape((iTestGridSize**2, 1))
    ])
    aReferenceValues = np.exp(-aTestPoints[:, 0]**2) * np.cos(aTestPoints[:,
                                                                          1])
    aReferenceValues = aReferenceValues.reshape((aReferenceValues.shape[0], 1))

    def testGrid(grid, aTestPoints, aReferenceValues):
        aResult = grid.evaluateBatch(aTestPoints)
        for i in range(20):
            aX = aTestPoints[i, :]
        return np.max(np.abs(aResult - aReferenceValues))

    iInitialLevel = 5

    grid_isotropic = Tasmanian.SparseGrid()
    grid_iptotal = Tasmanian.SparseGrid()
    grid_icurved = Tasmanian.SparseGrid()
    grid_surplus = Tasmanian.SparseGrid()
    grid_isotropic.makeGlobalGrid(iNumInputs, iNumOutputs, iInitialLevel,
                                  "level", "leja")
    grid_iptotal.copyGrid(grid_isotropic)
    grid_icurved.copyGrid(grid_isotropic)
    grid_surplus.copyGrid(grid_isotropic)

    iNumThreads = 1
    iBudget = 100
    print("{0:>22s}{1:>22s}{2:>22s}{3:>22s}".format("isotropic", "iptotal",
                                                    "ipcurved", "surplus"))
    print(
        "{0:>8s}{1:>14s}{0:>8s}{1:>14s}{0:>8s}{1:>14s}{0:>8s}{1:>14s}".format(
            "points", "error"))

    bBelowBudget = True
    while (bBelowBudget):
        sInfo = ""
        if (grid_isotropic.getNumLoaded() < iBudget):
            Tasmanian.loadNeededPoints(lambda x, tid: model(x), grid_isotropic,
                                       iNumThreads)
            sInfo += "{0:>8d}{1:>14s}".format(
                grid_isotropic.getNumLoaded(), "{0:1.4e}".format(
                    testGrid(grid_isotropic, aTestPoints, aReferenceValues)))

            iLevel = 0
            while (grid_isotropic.getNumNeeded() == 0):
                grid_isotropic.updateGlobalGrid(iLevel, "level")
                iLevel += 1
        else:
            sInfo += "{0:>22s}".format("")

        if (grid_iptotal.getNumLoaded() < iBudget):
            Tasmanian.loadNeededPoints(lambda x, tid: model(x), grid_iptotal,
                                       iNumThreads)
            sInfo += "{0:>8d}{1:>14s}".format(
                grid_iptotal.getNumLoaded(), "{0:1.4e}".format(
                    testGrid(grid_iptotal, aTestPoints, aReferenceValues)))

            grid_iptotal.setAnisotropicRefinement("iptotal", 10, 0)
        else:
            sInfo += "{0:>22s}".format("")

        if (grid_icurved.getNumLoaded() < iBudget):
            Tasmanian.loadNeededPoints(lambda x, tid: model(x), grid_icurved,
                                       iNumThreads)
            sInfo += "{0:>8d}{1:>14s}".format(
                grid_icurved.getNumLoaded(), "{0:1.4e}".format(
                    testGrid(grid_icurved, aTestPoints, aReferenceValues)))

            grid_icurved.setAnisotropicRefinement("ipcurved", 10, 0)
        else:
            sInfo += "{0:>22s}".format("")

        if (grid_surplus.getNumLoaded() < iBudget):
            Tasmanian.loadNeededPoints(lambda x, tid: model(x), grid_surplus,
                                       iNumThreads)
            sInfo += "{0:>8d}{1:>14s}".format(
                grid_surplus.getNumLoaded(), "{0:1.4e}".format(
                    testGrid(grid_surplus, aTestPoints, aReferenceValues)))

            grid_surplus.setSurplusRefinement(1.E-8, 0)
        else:
            sInfo += "{0:>22s}".format("")

        print(sInfo)
        bBelowBudget = (grid_isotropic.getNumLoaded() < iBudget
                        or grid_icurved.getNumLoaded() < iBudget
                        or grid_icurved.getNumLoaded() < iBudget
                        or grid_surplus.getNumLoaded() < iBudget)
Example #20
0
# set input record
inpRec = dict();
inpRec['restart'] = False
inpRec['method'] = 'langevin'
inpRec['N_per'] = 3
inpRec['M'] = np.reshape(M,(M.size,))   # units = amu
inpRec['Temp'] = Temp                   # units = K
inpRec['dt'] = 0.05                     # units = fs
inpRec['Tfinal'] = Tfinal               # units = fs
# need bounds since domains must be on same scale within the MD simulator
inpRec['bounds'] = [[-180,180], [-180,180], [-180,180], [1.1, 2.5], [90, 270]]  # units = GIC
inpRec['Gamma'] = 0.01                  # units = fs^(-1)

# make sparse grids for PES
sg_poly_energy = tsg.SparseGrid()
sg_poly_energy.makeGlobalGrid(2,1,8,'iptotal','clenshaw-curtis')
sg_poly_energy.setDomainTransform(np.asarray([[0, 1], [0,1]]))
N_poly = len(sg_poly_energy.getPoints())

sg_trig_energy = tsg.SparseGrid()
sg_trig_energy.makeFourierGrid(3,N_poly,5,'iptotal',[1, 2, 2])
sg_trig_energy.setDomainTransform(np.asarray([[0, 1], [0,1], [0, 1]]))
N_trig = len(sg_trig_energy.getPoints())

dataE = ev2ieu * np.loadtxt('%s/energy.dat' % state_folder)
dataE = np.reshape(dataE,(N_trig,N_poly))
sg_trig_energy.loadNeededPoints(dataE)

inpRec['UQ'] = lambda Q : eval_mixed(Q, sg_trig=sg_trig_energy, sg_poly=sg_poly_energy, ndof=1)
inpRec['dUdQ'] = lambda Q : eval_mixed_grad(Q, sg_trig=sg_trig_energy, sg_poly=sg_poly_energy, ndof=1)
Example #21
0
import numpy as np

# imports specifically needed by the examples
import math
from random import uniform
from datetime import datetime

bFastTests = False
if (len(sys.argv) > 1):
    bFastTests = True

print("Tasmanian version: {0:s}".format(Tasmanian.__version__))
print("Tasmanian license: {0:s}".format(Tasmanian.__license__))

grid = Tasmanian.SparseGrid()

iDim = 2
iLevel = 6

# EXAMPLE 1: integrate: f(x,y) = exp(-x^2) * cos(y) over [-1,1] x [-1,1]
# using classical Smolyak grid with Clenshaw-Curtis points and weights
grid = Tasmanian.SparseGrid()

print("\n-------------------------------------------------------------------------------------------------")
print("Example 1:  integrate f(x,y) = exp(-x^2) * cos(y), using clenshaw-curtis level nodes")

iDim = 2
iLevel = 6

grid.makeGlobalGrid(iDim, 0, iLevel, "level", "clenshaw-curtis")
Example #22
0
    def checkUpdate(self):
        '''
        Check the update and make working together.
        '''
        grid = Tasmanian.SparseGrid()
        for iI in range(2):
            if (iI == 0):
                sMake = "grid.makeGlobalGrid(2, 1, 2, 'level', 'leja', [2, 1])"
                sUpda1 = "grid.updateGlobalGrid(2, 'level', [2, 1])"
                sUpda2 = "grid.updateGlobalGrid(3, 'level', [2, 1])"
                sUpda3 = "grid.updateGlobalGrid(4, 'ipcurved', [20, 10, 0, 7])"
            else:
                sMake = "grid.makeSequenceGrid(2, 1, 2, 'level', 'leja', [2, 1])"
                sUpda1 = "grid.updateSequenceGrid(2, 'level', [2, 1])"
                sUpda2 = "grid.updateSequenceGrid(3, 'level', [2, 1])"
                sUpda3 = "grid.updateSequenceGrid(4, 'ipcurved', [20, 10, 0, 7])"
            exec(sMake)
            iNN = grid.getNumNeeded()
            iNL = grid.getNumLoaded()
            iNP = grid.getNumPoints()
            self.assertEqual(iNN, 4, "num needed")
            self.assertEqual(iNL, 0, "num loaded")
            self.assertEqual(iNP, iNN, "num points")
            ttc.loadExpN2(grid)
            iNN = grid.getNumNeeded()
            iNL = grid.getNumLoaded()
            iNP = grid.getNumPoints()
            self.assertEqual(iNN, 0, "num needed")
            self.assertEqual(iNL, 4, "num loaded")
            self.assertEqual(iNP, iNL, "num points")
            exec(sUpda1)
            iNN = grid.getNumNeeded()
            iNL = grid.getNumLoaded()
            iNP = grid.getNumPoints()
            self.assertEqual(iNN, 0, "num needed")
            self.assertEqual(iNL, 4, "num loaded")
            self.assertEqual(iNP, iNL, "num points")
            exec(sUpda2)
            iNN = grid.getNumNeeded()
            iNL = grid.getNumLoaded()
            iNP = grid.getNumPoints()
            self.assertEqual(iNN, 2, "num needed")
            self.assertEqual(iNL, 4, "num loaded")
            self.assertEqual(iNP, iNL, "num points")
            aA = np.array([[0.0, 0.0], [0.0, 1.0], [0.0, -1.0], [1.0, 0.0]])
            aP = grid.getPoints()
            np.testing.assert_equal(aA, aP, "Update Global not equal", True)
            aP = grid.getLoadedPoints()
            np.testing.assert_equal(aA, aP, "Update Global not equal", True)
            aA = np.array([[0.0, np.sqrt(1.0/3.0)], [1.0, 1.0]])
            aP = grid.getNeededPoints()
            np.testing.assert_equal(aA, aP, "Update Global not equal", True)
            ttc.loadExpN2(grid)
            iNN = grid.getNumNeeded()
            iNL = grid.getNumLoaded()
            iNP = grid.getNumPoints()
            self.assertEqual(iNN, 0, "num needed")
            self.assertEqual(iNL, 6, "num loaded")
            self.assertEqual(iNP, iNL, "num points")
            exec(sUpda3)
            iNN = grid.getNumNeeded()
            iNL = grid.getNumLoaded()
            iNP = grid.getNumPoints()
            self.assertEqual(iNN, 1, "num needed")
            self.assertEqual(iNL, 6, "num loaded")
            self.assertEqual(iNP, iNL, "num points")
            aA = np.array([[-1.0, 0.0]])
            aP = grid.getNeededPoints()
            np.testing.assert_equal(aA, aP, "Update Global not equal", True)

        grid.makeFourierGrid(2, 1, 2, "level")
        ttc.loadExpN2(grid)
        grid.updateFourierGrid(3, "level")
        self.assertEqual(grid.getNumNeeded(), 60, "failed at updateFourierGrid()")
Example #23
0
    def checkDefaults(self):
        '''
        Test that default values are set correctly for alpha/beta/order,
        empty returns, empty copy.
        '''
        grid = Tasmanian.SparseGrid()
        for sRule in TasmanianSG.lsTsgLocalRules:
            grid.makeLocalPolynomialGrid(3, 1, 3, 0, sRule)
            self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
            self.assertEqual(grid.getBeta(), 0.0, "failed beta")
            self.assertEqual(grid.getOrder(), 0, "failed order")
            grid.makeLocalPolynomialGrid(3, 1, 3, 1, sRule)
            self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
            self.assertEqual(grid.getBeta(), 0.0, "failed beta")
            self.assertEqual(grid.getOrder(), 1, "failed order")
            grid.makeLocalPolynomialGrid(3, 1, 3, 2, sRule)
            self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
            self.assertEqual(grid.getBeta(), 0.0, "failed beta")
            self.assertEqual(grid.getOrder(), 2, "failed order")

        grid = Tasmanian.makeWaveletGrid(3, 1, 2, 1)
        self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
        self.assertEqual(grid.getBeta(), 0.0, "failed beta")
        self.assertEqual(grid.getOrder(), 1, "failed order")
        grid.makeWaveletGrid(3, 1, 2, 3)
        self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
        self.assertEqual(grid.getBeta(), 0.0, "failed beta")
        self.assertEqual(grid.getOrder(), 3, "failed order")

        try:
            grid.copyGrid([])
            self.assertTrue(False, "failed to raise exception on copy grid")
        except Tasmanian.InputError as TsgError:
            with open(os.devnull, 'w') as devnul:
                sys.stdout = devnul
                TsgError.printInfo() # Miro: silence this for a release
                sys.stdout = sys.__stdout__

        # default alpha/beta and order
        grid.makeGlobalGrid(2, 0, 2, 'level', 'leja', [2, 1])
        self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
        self.assertEqual(grid.getBeta(), 0.0, "failed beta")
        self.assertEqual(grid.getOrder(), -1, "failed order")
        grid.makeGlobalGrid(1, 0, 4, 'level', 'gauss-hermite', [], 2.0)
        self.assertEqual(grid.getAlpha(), 2.0, "failed alpha")
        self.assertEqual(grid.getBeta(), 0.0, "failed beta")
        self.assertEqual(grid.getOrder(), -1, "failed order")
        grid.makeGlobalGrid(1, 0, 4, 'level', 'gauss-jacobi', [], 3.0, 2.0)
        self.assertEqual(grid.getAlpha(), 3.0, "failed alpha")
        self.assertEqual(grid.getBeta(), 2.0, "failed beta")
        self.assertEqual(grid.getOrder(), -1, "failed order")

        grid.makeSequenceGrid(2, 1, 1, 'level', 'leja', [2, 1])
        self.assertEqual(grid.getAlpha(), 0.0, "failed alpha")
        self.assertEqual(grid.getBeta(), 0.0, "failed beta")
        self.assertEqual(grid.getOrder(), -1, "failed order")

        # test empty returns
        dummy_ans = np.empty([0, 0], np.float64)
        grid_dummy = Tasmanian.SparseGrid()
        aX = np.empty([0,], np.float64)
        np.testing.assert_equal(dummy_ans, grid_dummy.getPoints(), "Empty read", True)
        np.testing.assert_equal(dummy_ans, grid_dummy.getNeededPoints(), "Empty read", True)
        np.testing.assert_equal(dummy_ans, grid_dummy.getLoadedPoints(), "Empty read", True)
        dummy_ans = np.empty([0,], np.float64)
        np.testing.assert_equal(dummy_ans, grid_dummy.getQuadratureWeights(), "Empty read", True)
        np.testing.assert_equal(dummy_ans, grid_dummy.getInterpolationWeights(aX), "Empty read", True)
        dummy_ans = np.empty([0, 0], np.float64)
        aX = np.empty([0, 0], np.float64)
        np.testing.assert_equal(dummy_ans, grid_dummy.getInterpolationWeightsBatch(aX), "Empty read", True)
        aX = np.empty([1, 0], np.float64)
        np.testing.assert_equal(dummy_ans, grid_dummy.getInterpolationWeightsBatch(aX), "Empty read", True)
        grid.makeGlobalGrid(2, 1, 2, 'level', 'chebyshev')
        ttc.loadExpN2(grid)
        dummy_ans = np.empty([0, 1], np.float64)
        aX = np.empty([0, 2], np.float64)
        np.testing.assert_equal(dummy_ans, grid.evaluateBatch(aX), "Empty batch eval", True)
Example #24
0
    def checkLevelLimits(self):
        '''
        Check setting level limits.
        '''
        grid = Tasmanian.SparseGrid()

        # Level Limits
        grid.makeGlobalGrid(2, 1, 2, 'level', 'clenshaw-curtis', liLevelLimits = [1, 4])
        aPoints = grid.getPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [-1.0, 1.0], lMustNotHave = [1.0/np.sqrt(2.0), -1.0/np.sqrt(2.0)])
        ttc.checkPoints(aPoints[:,1], lMustHave = [-1.0, 1.0, 1.0/np.sqrt(2.0), -1.0/np.sqrt(2.0)], lMustNotHave = [])
        ttc.loadExpN2(grid)
        grid.setAnisotropicRefinement('iptotal', 20, 0, [1, 4])
        self.assertTrue(grid.getNumNeeded() > 0, 'did not refine')
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [], lMustNotHave = [1.0/np.sqrt(2.0), -1.0/np.sqrt(2.0)])

        grid.makeSequenceGrid(3, 1, 3, 'level', 'leja', liLevelLimits = [3, 2, 1])
        aPoints = grid.getPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [0.0, -1.0, 1.0, 1.0/np.sqrt(3.0)], lMustNotHave = [])
        ttc.checkPoints(aPoints[:,1], lMustHave = [0.0, -1.0, 1.0], lMustNotHave = [1.0/np.sqrt(3.0)])
        ttc.checkPoints(aPoints[:,2], lMustHave = [0.0, 1.0], lMustNotHave = [-1.0, 1.0/np.sqrt(3.0)])
        ttc.loadExpN2(grid)
        grid.setAnisotropicRefinement('iptotal', 5, 0)
        self.assertTrue(grid.getNumNeeded() > 0, 'did not refine')
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,1], lMustHave = [], lMustNotHave = [1.0/np.sqrt(3.0)])
        ttc.checkPoints(aPoints[:,2], lMustHave = [], lMustNotHave = [-1.0, 1.0/np.sqrt(3.0)])
        grid.clearRefinement()
        grid.setAnisotropicRefinement('iptotal', 10, 0, [3, 2, 2])
        self.assertTrue(grid.getNumNeeded() > 0, 'did not refine')
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,1], lMustHave = [], lMustNotHave = [1.0/np.sqrt(3.0)])
        ttc.checkPoints(aPoints[:,2], lMustHave = [1.0], lMustNotHave = [1.0/np.sqrt(3.0)])
        grid.clearRefinement()
        grid.setSurplusRefinement(1.E-8, 0, '', [3, 2, 1])
        self.assertTrue(grid.getNumNeeded() > 0, 'did not refine')
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,1], lMustHave = [], lMustNotHave = [1.0/np.sqrt(3.0)])
        ttc.checkPoints(aPoints[:,2], lMustHave = [], lMustNotHave = [-1.0, 1.0/np.sqrt(3.0)])

        # check that nodes from level 2 (+-0.5) and 3 (+-0.25, +-0.75) appear only in the proper dimension
        grid.makeLocalPolynomialGrid(3, 1, 3, 1, 'localp', [1, 2, 3])
        aPoints = grid.getPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [0.0, -1.0, 1.0], lMustNotHave = [0.5, -0.5, -0.75, -0.25, 0.25, 0.75])
        ttc.checkPoints(aPoints[:,1], lMustHave = [0.0, -1.0, 1.0, 0.5, -0.5], lMustNotHave = [-0.75, -0.25, 0.25, 0.75])
        ttc.checkPoints(aPoints[:,2], lMustHave = [0.0, -1.0, 1.0, 0.5, -0.5, -0.75, -0.25, 0.25, 0.75], lMustNotHave = [])
        ttc.loadExpN2(grid)
        grid.setSurplusRefinement(1.E-8, 0, 'classic')
        self.assertTrue(grid.getNumNeeded() > 0, 'did not refine')
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [], lMustNotHave = [0.5, -0.5, -0.75, -0.25, 0.25, 0.75])
        ttc.checkPoints(aPoints[:,1], lMustHave = [], lMustNotHave = [-0.75, -0.25, 0.25, 0.75])
        ttc.checkPoints(aPoints[:,2], lMustHave = [], lMustNotHave = [])
        grid.clearRefinement()
        grid.setSurplusRefinement(1.E-8, 0, 'classic', [2, 2, 3])
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [0.5, -0.5], lMustNotHave = [-0.75, -0.25, 0.25, 0.75])
        ttc.checkPoints(aPoints[:,1], lMustHave = [], lMustNotHave = [-0.75, -0.25, 0.25, 0.75])

        grid.makeWaveletGrid(2, 1, 3, 1, [0, 2])
        aPoints = grid.getPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [0.0, -1.0, 1.0], lMustNotHave = [-0.5, 0.5])
        ttc.checkPoints(aPoints[:,1], lMustHave = [0.0, -1.0, 1.0, -0.5, 0.5, -0.75, -0.25, 0.25, 0.75], lMustNotHave = [-0.125, 0.125])
        ttc.loadExpN2(grid)
        grid.setSurplusRefinement(1.E-8, 0, 'classic') # grid is effectively full tensor, cannot refine within the level limits
        self.assertTrue((grid.getNumNeeded() == 0), 'added points even though it should not have');
        grid.setSurplusRefinement(1.E-8, 0, 'classic', [1, 2])
        aPoints = grid.getNeededPoints()
        ttc.checkPoints(aPoints[:,0], lMustHave = [0.5, -0.5], lMustNotHave = [-0.75, -0.25, 0.25, 0.75])
        ttc.checkPoints(aPoints[:,1], lMustHave = [], lMustNotHave = [-0.125, 0.125])

        # level limits I/O
        grid.makeLocalPolynomialGrid(3, 1, 3, 1, 'localp', [1, 2, 3])
        aLimits = grid.getLevelLimits()
        np.testing.assert_almost_equal(aLimits, np.array([1, 2, 3]), 14, "Could not read level limits", True)

        grid.clearLevelLimits()
        aLimits = grid.getLevelLimits()
        np.testing.assert_almost_equal(aLimits, np.array([-1, -1, -1]), 14, "Could not read level limits", True)
Example #25
0
 def create_surrogate(lambda_fn):
     grid = Tasmanian.makeGlobalGrid(1, 1, nref, "level", "gauss-legendre")
     grid.loadNeededValues(np.apply_along_axis(lambda_fn, 1, grid.getNeededPoints()))
     return grid
Example #26
0
    def checkMakeAgainstKnown(self):
        '''
        Make grids and check against pen-and-paper answers, check weights too.
        '''
        grid = Tasmanian.makeGlobalGrid(1, 0, 4, 'level', 'gauss-hermite', [], 2.0)
        aW = grid.getQuadratureWeights()
        self.assertTrue(np.abs(sum(aW) - 0.5 * np.sqrt(np.pi)) < 1.E-14, "Gauss-Hermite Alpha")

        grid.makeGlobalGrid(2, 0, 2, 'level', 'leja', [2, 1])
        aA = np.array([[0.0, 0.0], [0.0, 1.0], [0.0, -1.0], [1.0, 0.0]])
        aP = grid.getPoints()
        np.testing.assert_equal(aA, aP, 'Anisotropy Global not equal', True)

        grid.makeGlobalGrid(2, 0, 4, 'ipcurved', 'leja', [20, 10, 0, 7])
        aA = np.array([[0.0, 0.0], [0.0, 1.0], [0.0, -1.0], [0.0, np.sqrt(1.0/3.0)], [1.0, 0.0], [1.0, 1.0], [-1.0, 0.0]])
        aP = grid.getPoints()
        np.testing.assert_almost_equal(aA, aP, 12, 'Anisotropy Global not equal', True)

        grid.makeSequenceGrid(2, 1, 2, 'level', 'leja', [2, 1])
        aA = np.array([[0.0, 0.0], [0.0, 1.0], [0.0, -1.0], [1.0, 0.0]])
        aP = grid.getPoints()
        np.testing.assert_equal(aA, aP, 'Anisotropy Sequence not equal', True)

        grid = Tasmanian.makeSequenceGrid(2, 1, 4, 'ipcurved', 'leja', [20, 10, 0, 7])
        aA = np.array([[0.0, 0.0], [0.0, 1.0], [0.0, -1.0], [0.0, np.sqrt(1.0/3.0)], [1.0, 0.0], [1.0, 1.0], [-1.0, 0.0]])
        aP = grid.getPoints()
        np.testing.assert_almost_equal(aA, aP, 12, 'Anisotropy Sequence not equal', True)

        grid = Tasmanian.makeFourierGrid(2, 1, 2, 'level', [1, 2])
        aA = np.array([[0.0, 0.0], [0.0, 1.0/3.0], [0.0, 2.0/3.0], [1.0/3.0, 0.0], [2.0/3.0, 0.0], [1.0/9.0, 0.0], [2.0/9.0, 0.0], [4.0/9.0, 0.0], [5.0/9.0, 0.0], [7.0/9.0, 0.0], [8.0/9.0, 0.0]])
        aP = grid.getPoints()
        np.testing.assert_almost_equal(aA, aP, 12, 'Anisotropy Fourier not equal', True)

        # this is a very important test, checks the curved rule and covers the non-lower-set index selection code
        grid.makeGlobalGrid(2, 1, 1, 'ipcurved', 'rleja', [10, 10, -21, -21])
        aA = np.array([[0.0, 0.0], [0.0, 1.0], [0.0, 0.5], [0.0, 0.25], [0.0, 0.75], [0.0, 0.125],
                       [1.0, 0.0], [1.0, 1.0], [1.0, 0.5], [1.0, 0.25], [1.0, 0.75], [1.0, 0.125],
                       [0.5, 0.0], [0.5, 1.0], [0.5, 0.5], [0.5, 0.25], [0.5, 0.75], [0.5, 0.125],
                       [0.25, 0.0], [0.25, 1.0], [0.25, 0.5], [0.25, 0.25], [0.25, 0.75],
                       [0.75, 0.0], [0.75, 1.0], [0.75, 0.5], [0.75, 0.25],
                       [0.125, 0.0], [0.125, 1.0], [0.125, 0.5]])
        aA = np.cos(np.pi * aA)
        aP = grid.getPoints()
        np.testing.assert_almost_equal(aA, aP, 12, 'Anisotropy heavily curved not equal', True) # 12 is the number of dec places

        # test weights
        aX = np.array([[0.0, -0.3], [-0.44, 0.7], [0.82, -0.01]])
        grid.makeGlobalGrid(2, 0, 4, 'level', 'chebyshev')
        aW = grid.getInterpolationWeightsBatch(aX)
        aX1 = aX[0,:].reshape([2,])
        aX2 = aX[1,:].reshape([2,])
        aX3 = aX[2,:].reshape([2,])
        aW1 = grid.getInterpolationWeights(aX1)
        aW2 = grid.getInterpolationWeights(aX2)
        aW3 = grid.getInterpolationWeights(aX3)
        aWW = np.row_stack([aW1, aW2, aW3])
        np.testing.assert_equal(aW, aWW, "Batch weights", True)

        grid.makeGlobalGrid(3, 0, 1, 'level', 'chebyshev')
        aTrans = np.array([[-1.0, -4.0], [2.0, 5.0], [-3.0, 5]])
        grid.setDomainTransform(aTrans)
        aA = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 1.0], [0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
        aB = np.array([[-2.5, 3.5, 1.0], [-2.5, 3.5, -3.0], [-2.5, 3.5, 5.0], [-2.5,  2.0, 1.0], [-2.5, 5.0, 1.0], [-1.0, 3.5, 1.0], [-4.0, 3.5, 1.0]])
        np.testing.assert_equal(aB, grid.getPoints(), "Original equal", True)
        grid.clearDomainTransform()
        np.testing.assert_equal(aA, grid.getPoints(), "Tansformed equal", True)

        grid.makeGlobalGrid(3, 0, 1, 'level', 'fejer2')
        aA = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, -0.707106781186548], [0.0, 0.0, 0.707106781186548], [0.0, -0.707106781186548, 0.0], [0.0, 0.707106781186548, 0.0], [-0.707106781186548, 0.0, 0.0], [0.707106781186548, 0.0, 0.0]])
        np.testing.assert_almost_equal(aA, grid.getPoints(), 14, "Original equal", True)
        grid.setConformalTransformASIN(np.array([4, 6, 3]))
        aA = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, -0.60890205], [0.0, 0.0, 0.60890205], [0.0, -0.57892643, 0.0], [0.0, 0.57892643, 0.0], [-0.59587172, 0.0, 0.0], [0.59587172, 0.0, 0.0]])
        np.testing.assert_almost_equal(aA, grid.getPoints(), 7, "Transformed equal", True)
        grid.clearConformalTransform()
        aA = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, -0.707106781186548], [0.0, 0.0, 0.707106781186548], [0.0, -0.707106781186548, 0.0], [0.0, 0.707106781186548, 0.0], [-0.707106781186548, 0.0, 0.0], [0.707106781186548, 0.0, 0.0]])
        np.testing.assert_almost_equal(aA, grid.getPoints(), 14, "Original equal", True)

        # number of points
        grid = Tasmanian.makeLocalPolynomialGrid(2, 1, 2, 2, "localp")
        iNN = grid.getNumNeeded()
        iNL = grid.getNumLoaded()
        iNP = grid.getNumPoints()
        self.assertEqual(iNN, 13, "num needed")
        self.assertEqual(iNL, 0, "num loaded")
        self.assertEqual(iNP, iNN, "num points")
        ttc.loadExpN2(grid)
        iNN = grid.getNumNeeded()
        iNL = grid.getNumLoaded()
        iNP = grid.getNumPoints()
        self.assertEqual(iNN, 0, "num needed")
        self.assertEqual(iNL, 13, "num loaded")
        self.assertEqual(iNP, iNL, "num points")
        grid.setSurplusRefinement(0.10, 0, "classic")
        iNN = grid.getNumNeeded()
        iNL = grid.getNumLoaded()
        iNP = grid.getNumPoints()
        self.assertEqual(iNN, 8, "num needed")
        self.assertEqual(iNL, 13, "num loaded")
        self.assertEqual(iNP, iNL, "num points")
        grid.setSurplusRefinement(0.05, 0, "classic")
        iNN = grid.getNumNeeded()
        iNL = grid.getNumLoaded()
        iNP = grid.getNumPoints()
        self.assertEqual(iNN, 16, "num needed")
        self.assertEqual(iNL, 13, "num loaded")
        self.assertEqual(iNP, iNL, "num points")
        ttc.loadExpN2(grid)
        iNN = grid.getNumNeeded()
        iNL = grid.getNumLoaded()
        iNP = grid.getNumPoints()
        self.assertEqual(iNN,  0, "num needed")
        self.assertEqual(iNL, 29, "num loaded")
        self.assertEqual(iNP, iNL, "num points")