Example #1
0
    def __init__(self, b, d, dim=1, X=None, Y=None):
        '''
        Constructor for the class Tensorizer.

        If dim == 1, defines a map t from [0,1] to {0,...,b-1}^d x [0,1]
        t(x) = (i_1, ..., i_d, y) with y in [0,1] and i_k in {0, ..., b-1}
        such that x = (i + y)b^(-d) with i in {0, ..., b^d-1}
        having the following representation in base b:
        i = sum_{k=1}^d i_k b^(d-k) in [0,b^d-1].

        If dim != 1, defines a map t from [0,1]^dim to
        {{0, ..., b-1}^d}^dim x [0,1]^dim if property orderingType == 1,
        or from [0,1]^dim to {{0, ..., b-1}^dim}^d x [0,1]^dim if property
        orderingType == 2.

        Parameters
        ----------
        b : int
        The base of the map.
        d : int
            The resolution of the map.
        dim : int, optional
            The input dimension of the function to be tensorized. The default
            is 1.
        X : tensap.RandomVector, optional
            Random vector used for the map. The default is None a uniform
            random vector on [0, 1]^dim.
        Y : tensap.RandomVector, optional
            Random vector used for the map. The default is None a uniform
            random vector on [0, 1]^dim.
        ordering_type : int
            Integer specifying the ordering type of the variables. 
            The default is 1. 

        Returns
        -------
        None.

        '''
        self.dim = dim
        self.b = b
        self.d = d

        self.ordering_type = 1

        if X is not None:
            if isinstance(X, tensap.RandomVariable):
                X = tensap.RandomVector(X, self.dim)
            self.X = X
        else:
            self.X = tensap.RandomVector(tensap.UniformRandomVariable(0, 1),
                                         self.dim)

        if Y is not None:
            if isinstance(Y, tensap.RandomVariable):
                Y = tensap.RandomVector(Y, self.dim)
            self.Y = Y
        else:
            self.Y = tensap.RandomVector(tensap.UniformRandomVariable(0, 1),
                                         self.dim)
Example #2
0
    def lhs_random(self, n, p=1):
        '''
        Latin Hypercube Sampling of the random variable self of n points in
        dimension p.

        Requires the package pyDOE.

        Parameters
        ----------
        n : int
            Number of points.
        p : int, optional
            The dimension. The default is 1.

        Returns
        -------
        numpy.ndarray
            The coordinates of the Latin Hypercube Sampling in each dimension.

        '''
        from pyDOE import lhs
        A = lhs(p, samples=n)
        U = tensap.UniformRandomVariable(0, 1)
        A = [U.transfer(self, A[:, i]) for i in range(A.shape[1])]
        return np.transpose(np.array(A))
    def shift(self, bias, scaling):
        '''
        Shift the uniform random variable using the provided bias and scaling
        factor.

        The lower bound inf becomes scaling*inf + bias, and the upper bound
        sup becomes scaling*sup + bias.

        Parameters
        ----------
        bias : float
            The bias.
        scaling : float
            The scaling factor.

        Returns
        -------
        shifted_rv : tensap.UniformRandomVariable
            The shifted uniform random variable.

        '''
        shifted_rv = tensap.UniformRandomVariable(self.inf, self.sup)
        shifted_rv.inf = scaling * shifted_rv.inf + bias
        shifted_rv.sup = scaling * shifted_rv.sup + bias
        return shifted_rv
    def get_standard_random_variable():
        '''
        Return the standard uniform random variable on [-1, 1].

        Returns
        -------
        tensap.UniformRandomVariable
            The standard uniform random variable.

        '''
        return tensap.UniformRandomVariable()
Example #5
0
    def __init__(self, n=50):
        '''
        Constructor for the class LegendrePolynomials.

        Parameters
        ----------
        n : int, optional
            The highest degree for which a polynomial can be computed with the
            stored recurrence coefficients. The default is 50.

        Returns
        -------
        None.

        '''
        self.measure = tensap.UniformRandomVariable(-1, 1)

        self._recurrence_coefficients, self._orthogonal_polynomials_norms = \
            self._recurrence(n)
Example #6
0
    def gauss_integration_rule(self, nb_pts):
        '''
        Return the nb_pts-points gauss integration rule associated with the
        measure of self, using Golub-Welsch algorithm.

        Parameters
        ----------
        nb_pts : int
            The number of integration points.

        Returns
        -------
        tensap.IntegrationRule
            The integration rule associated with the measure of self.

        '''
        RV = tensap.UniformRandomVariable(self.a, self.b)
        I = RV.gauss_integration_rule(nb_pts)
        I.weights = I.weights * self.mass()

        return I
Example #7
0
    def lhs_random(self, n):
        '''
        Latin Hypercube Sampling of the RandomVector of n points.

        Requires the package pyDOE.

        Parameters
        ----------
        n : int
            Number of points.

        Returns
        -------
        list
            List containing the coordinates of the Latin Hypercube Sampling in
            each dimension.

        '''
        from pyDOE import lhs
        A = lhs(self.size, samples=n)
        A = RandomVector(tensap.UniformRandomVariable(0, 1),
                         self.size).transfer(self, A)
        return [A[:, k] for k in range(self.size)]
import sys
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, './../../../')
import tensap

# %% Interpolation on a polynomial space using Chebyshev Points
def FUN(x):
    # Function to approximate
    return np.cos(10*x)


FUN = tensap.UserDefinedFunction(FUN, 1)
FUN.evaluation_at_multiple_points = True
X = tensap.UniformRandomVariable(-1, 1)

# Interpolation basis and points
P = 30
H = tensap.PolynomialFunctionalBasis(X.orthonormal_polynomials(), range(P+1))
X_CP = tensap.chebyshev_points(H.cardinal(), [-1, 1])

# Interpolation of the function
F = H.interpolate(FUN, X_CP)

# Displays and error
print('Interpolation on a polynomial space using Chebyshev Points')
plt.figure()
X_PLOT = np.linspace(-1, 1, 100)
plt.plot(X_PLOT, FUN(X_PLOT))
plt.plot(X_PLOT, F(X_PLOT))
'''

import sys
from time import time
import numpy as np
import matplotlib.pyplot as plt
sys.path.insert(0, './../../../')
import tensap

# %% Function to approximate: identification of a function f(x) with a function
# g(i1,...,id,y) (see also tutorial_TensorizedFunction)
R = 4  # Resolution
B = 5  # Scaling factor
ORDER = R + 1

X = tensap.UniformRandomVariable(0, 1)
Y = tensap.UniformRandomVariable(0, 1)

CHOICE = 1
if CHOICE == 1:

    def FUN(x):
        return np.sin(10 * np.pi *
                      (2 * x + 0.5)) / (4 * x + 1) + (2 * x - 0.5)**4
elif CHOICE == 2:

    def FUN(x):
        return (np.sin(4*np.pi*x) + 0.2*np.cos(16*np.pi*x))**(x < 0.5) + \
            (2*x-1)*(x >= 0.5)
else:
    raise ValueError('Bad function choice.')
Example #10
0
'''

from time import time
import numpy as np
from scipy.stats import multivariate_normal
import tensap

# %% Function to approximate: multivariate gaussian distribution
ORDER = 6
# Covariance matrix
S = np.array([[2, 0, 0.5, 1, 0, 0.5], [0, 1, 0, 0, 0.5, 0],
              [0.5, 0, 2, 0, 0, 1], [1, 0, 0, 3, 0, 0], [0, 0.5, 0, 0, 1, 0],
              [0.5, 0, 1, 0, 0, 2]])
# Reference measure
REF = tensap.RandomVector(
    [tensap.UniformRandomVariable(-x, x) for x in 5 * np.diag(S)])


# Density, defined with respect to the reference measure
def U(x):
    return multivariate_normal.pdf(x, np.zeros(ORDER), S) * \
        np.prod(2*5*np.diag(S))


# %% Training and test samples
NUM_TRAIN = 1e5  # Training sample size
X_TRAIN = multivariate_normal.rvs(np.zeros(ORDER), S, int(NUM_TRAIN))

NUM_TEST = 1e4  # Test sample size
X_TEST = multivariate_normal.rvs(np.zeros(ORDER), S, int(NUM_TEST))
Example #11
0
# %% Choice of the function to approximate
CHOICE = 2
if CHOICE == 1:
    print('Henon-Heiles')
    D = 5
    FUN, X = tensap.multivariate_functions_benchmark('henon_heiles', D)

    DEGREE = 4
    BASES = [tensap.PolynomialFunctionalBasis(x.orthonormal_polynomials(),
                                              range(DEGREE+1)) for
             x in X.random_variables]

elif CHOICE == 2:
    print('Anisotropic function')
    D = 6
    X = tensap.RandomVector(tensap.UniformRandomVariable(-1, 1), D)

    def FUN(x):
        return 1/(10 + 2*x[:, 0] + x[:, 2] + 2*x[:, 3] - x[:, 4])**2

    DEGREE = 13
    BASES = [tensap.PolynomialFunctionalBasis(x.orthonormal_polynomials(),
                                              range(DEGREE+1)) for
             x in X.random_variables]

elif CHOICE == 3:
    print('Sinus of a sum')
    D = 10
    X = tensap.RandomVector(tensap.UniformRandomVariable(-1, 1), D)

    def FUN(x):
    G1 = np.linspace(DOM[0], DOM[1], 100)
    G = tensap.FullTensorGrid(G1, D).array()
else:
    G1 = np.linspace(DOM[0], DOM[1], 1000)
    M1 = P1.magic_points(G1)[0]
    G = tensap.FullTensorGrid(np.ravel(M1), D).array()

MAGIC_POINTS, IND, OUTPUT = P.magic_points(G)

if D == 2:
    plt.figure()
    plt.plot(G[:, 0], G[:, 1], 'k.', markersize=1)
    plt.plot(MAGIC_POINTS[:, 0], MAGIC_POINTS[:, 1], 'ro', fillstyle='none')
    plt.show()

# %% Interpolation of a function using magic points
D = 2


def F(x):
    return np.cos(x[:, 0]) + x[:, 1]**6 + x[:, 0]**2*x[:, 1]


IF = P.interpolate(F, MAGIC_POINTS)

X = tensap.RandomVector(tensap.UniformRandomVariable(), D)
N_TEST = 1000
X_TEST = X.random(N_TEST)
ERR = np.linalg.norm(IF(X_TEST) - F(X_TEST)) / np.linalg.norm(F(X_TEST))
print('Test error = %2.5e' % ERR)
    NotImplementedError
        If the function is not implemented.

    Returns
    -------
    function
        The asked function.
    tensap.RandomVector
        Input random variables.

    '''
    if case == 'borehole':
        X = np.empty(8, dtype=object)
        X[0] = tensap.NormalRandomVariable(0.1, 0.0161812)
        X[1] = tensap.NormalRandomVariable(0, 1)
        X[2] = tensap.UniformRandomVariable(63070, 115600)
        X[3] = tensap.UniformRandomVariable(990, 1110)
        X[4] = tensap.UniformRandomVariable(63.1, 116)
        X[5] = tensap.UniformRandomVariable(700, 820)
        X[6] = tensap.UniformRandomVariable(1120, 1680)
        X[7] = tensap.UniformRandomVariable(9855, 12045)
        X = tensap.RandomVector(X)

        def fun(x):
            return 2 * np.pi * x[:, 2] * (x[:, 3] - x[:, 5]) / \
                (np.log(np.exp(7.71 + 1.0056*x[:, 1]) / x[:, 0]) *
                 (1 + 2 * x[:, 6] * x[:, 2] /
                  np.log(np.exp(7.71 + 1.0056 * x[:, 1]) / x[:, 0]) /
                  x[:, 0]**2 / x[:, 7] + x[:, 2] / x[:, 4]))

    elif case == 'ishigami':