def tensorized_function_functional_bases(self, h=1): ''' Return a tensap.FunctionalBases object associated with the provided basis or basis function(s) and the Tensorizer object. Parameters ---------- h : tensap.FunctionalBases or tensap.FunctionalBasis or function or list or scalar, optional The function used to generate the basis. The default is the function 1. Returns ------- tensap.FunctionalBases The functional bases. ''' #if isinstance(h, (np.ndarray, list)) or np.isscalar(h): # h = lambda y, h=h: h*np.ones(np.shape(y)) if hasattr(h, '__call__'): h = tensap.UserDefinedFunctionalBasis([h]) h.measure = self.Y.random_variables[0] if isinstance(h, tensap.FunctionalBasis): h = tensap.FunctionalBases.duplicate(h, self.dim) if np.isscalar(h): h = [tensap.PolynomialFunctionalBasis(y.orthonormal_polynomials(), range(h+1)) for y in self.Y.random_variables] h = tensap.FunctionalBases(h) assert isinstance(h, tensap.FunctionalBases), \ 'Wrong type of argument for h.' p = tensap.DiscretePolynomials(tensap.DiscreteRandomVariable( np.reshape(np.arange(self.b), [-1, 1]))) p = tensap.PolynomialFunctionalBasis(p, np.arange(self.b)) bases = [p]*self.d*self.dim + list(h.bases) return tensap.FunctionalBases(bases)
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)) plt.legend(('True function', 'Interpolation')) plt.show() N = 100 ERR_L2, ERR_L_INF = F.test_error(FUN, N, X)
# %% Function to approximate CHOICE = 2 if CHOICE == 1: ORDER = 5 X = tensap.RandomVector(tensap.NormalRandomVariable(), ORDER) def fun(x): return 1 / (10 + x[:, 0] + 0.5 * x[:, 1])**2 elif CHOICE == 2: fun, X = tensap.multivariate_functions_benchmark('borehole') ORDER = X.size # %% Approximation basis DEGREE = 8 BASES = [ tensap.PolynomialFunctionalBasis(X_TRAIN.orthonormal_polynomials(), range(DEGREE + 1)) for X_TRAIN in X.random_variables ] BASES = tensap.FunctionalBases(BASES) # %% Training and test samples NUM_TRAIN = 1000 X_TRAIN = X.random(NUM_TRAIN) Y_TRAIN = fun(X_TRAIN) NUM_TEST = 10000 X_TEST = X.random(NUM_TEST) Y_TEST = fun(X_TEST) # %% Learning in canonical tensor format SOLVER = tensap.CanonicalTensorLearning(ORDER, tensap.SquareLossFunction())
''' import sys import numpy as np sys.path.insert(0, './../../../') import tensap # %% Definitions D = 3 P = 10 F = tensap.UserDefinedFunction('1+x0+(2+x0)/(2+x1)+0.04*(x2-x2**3)', D) F.evaluation_at_multiple_points = True V = tensap.UniformRandomVariable(-1, 1) X = tensap.RandomVector(V, D) BASIS = tensap.PolynomialFunctionalBasis(tensap.LegendrePolynomials(), range(P + 1)) BASES = tensap.FunctionalBases.duplicate(BASIS, D) # %% Sparse tensor product functional basis IND = tensap.MultiIndices.with_bounded_norm(D, 1, P) H = tensap.SparseTensorProductFunctionalBasis(BASES, IND) # %% Interpolation on a magic grid G, _, _ = H.magic_points(X.random(1000)) IF = H.interpolate(F, G) X_TEST = X.random(1000) ERR = np.linalg.norm(F(X_TEST) - IF(X_TEST)) / np.linalg.norm(F(X_TEST)) print('Test error = %2.5e' % ERR) # %% Interpolation on a structured magic grid
X = tensap.UniformRandomVariable(0, 1) Y = tensap.UniformRandomVariable(0, 1) T = tensap.Tensorizer(B, D, 1, X, Y) def FUN(x): return np.sqrt(x) TENSORIZED_FUN = T.tensorize(FUN) TENSORIZED_FUN.fun.evaluation_at_multiple_points = True DEGREE = 4 P = tensap.PolynomialFunctionalBasis(Y.orthonormal_polynomials(), range(DEGREE + 1)) BASES = T.tensorized_function_functional_bases(P) H = tensap.FullTensorProductFunctionalBasis(BASES) GRIDS, _ = BASES.magic_points(BASES.measure.random(100)) G = tensap.FullTensorGrid(GRIDS) FUN_INTERP, _ = H.tensor_product_interpolation(TENSORIZED_FUN, G) TR = tensap.Truncator() TR.tolerance = 1e-9 FUN_INTERP.tensor = TR.ttsvd(FUN_INTERP.tensor) TENSORIZED_FUN_INTERP = tensap.TensorizedFunction(FUN_INTERP, T) X_TEST = X.random(1000) F_X_TEST = TENSORIZED_FUN_INTERP(X_TEST) Y_TEST = FUN(X_TEST)
''' import sys import numpy as np sys.path.insert(0, './../../../') import tensap # %% 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]
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with tensap. If not, see <https://www.gnu.org/licenses/>. ''' import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, './../../../') import tensap # %% Magic points associated with a Functional Basis (1D) P1 = tensap.PolynomialFunctionalBasis(tensap.LegendrePolynomials(), range(21)) DOM = P1.domain() G1 = np.linspace(DOM[0], DOM[1], 200) MAGIC_POINTS, IND, OUTPUT = P1.magic_points(G1) plt.figure() plt.plot(G1, np.zeros(G1.shape), 'k.', markersize=1) plt.plot(MAGIC_POINTS, np.zeros(MAGIC_POINTS.shape), 'ro', fillstyle='none') plt.show() # %% Magic points associated with a FullTensorProductFunctionalBasis # Tensorization of 1D uniform grids for the selection of magic points in # dimension d D = 2 P1 = tensap.PolynomialFunctionalBasis(tensap.LegendrePolynomials(), range(21)) BASES = tensap.FunctionalBases.duplicate(P1, D)
X = tensap.RandomVector(tensap.NormalRandomVariable(), ORDER) def fun(x): return 1 / (10 + x[:, 0] + 0.5 * x[:, 1])**2 elif CHOICE == 2: fun, X = tensap.multivariate_functions_benchmark('borehole') ORDER = X.size else: raise ValueError('Bad function choice.') # %% Approximation basis DEGREE = 8 ORTHONORMAL_BASES = True if ORTHONORMAL_BASES: BASES = [ tensap.PolynomialFunctionalBasis(x.orthonormal_polynomials(), range(DEGREE + 1)) for x in X.random_variables ] else: BASES = [ tensap.PolynomialFunctionalBasis(tensap.CanonicalPolynomials(), range(DEGREE + 1)) for x in X.random_variables ] BASES = tensap.FunctionalBases(BASES) # %% Training and test samples NUM_TRAIN = 100 X_TRAIN = X.random(NUM_TRAIN) Y_TRAIN = fun(X_TRAIN)
''' import sys import numpy as np sys.path.insert(0, './../../../') import tensap # %% Approximation of a function F(X) DIM = 6 FUN = tensap.UserDefinedFunction('x0 + x0*x1 + x0*x2**2 + x3**3 + x4 + x5', DIM) FUN.evaluationAtMultiplePoints = True DEGREE = 3 X = tensap.RandomVector(tensap.NormalRandomVariable(0, 1), DIM) P = tensap.PolynomialFunctionalBasis(tensap.HermitePolynomials(), range(DEGREE+1)) BASES = tensap.FunctionalBases.duplicate(P, DIM) GRIDS = X.random(1000) G = tensap.FullTensorGrid([np.reshape(GRIDS[:, i], [-1, 1]) for i in range(DIM)]) H = tensap.FullTensorProductFunctionalBasis(BASES) F, OUTPUT = H.tensor_product_interpolation(FUN, G) X_TEST = X.random(1000) F_X_TEST = F(X_TEST) Y_TEST = FUN(X_TEST) ERR = np.linalg.norm(Y_TEST-F_X_TEST) / np.linalg.norm(Y_TEST) print('Mean squared error = %2.5e\n' % ERR)
f.evaluation_at_multiple_points = True print('With f.evaluation_at_multiple_points == True, f(x) = \n%s\n' % f(x)) # %% Evaluation on a FullTensorGrid g = tensap.FullTensorGrid(np.linspace(-1, 1, 50), d) fx = fun.eval_on_tensor_grid(g) g.plot_grid(marker='x') # %% Evaluation on a SparseTensorGrid I = tensap.MultiIndices.with_bounded_norm(d, 1, 5) g = tensap.SparseTensorGrid(np.linspace(0, 1, 6), I, d) fx = fun.eval_on_tensor_grid(g) g.plot_grid(marker='x') # %% Functional Bases h = tensap.PolynomialFunctionalBasis(tensap.CanonicalPolynomials(), range(5)) H = tensap.FunctionalBases.duplicate(h, d) grid = tensap.FullTensorGrid(np.linspace(-1, 1, 10), d) x = grid.array() Hx = H.eval(x) # %% Sparse tensor functional basis d = 2 p = 1 m = 4 h = tensap.PolynomialFunctionalBasis(tensap.CanonicalPolynomials(), range(5)) H = tensap.FunctionalBases.duplicate(h, d) I = tensap.MultiIndices.with_bounded_norm(d, p, m) Psi = tensap.SparseTensorProductFunctionalBasis(H, I) print('Multi-indices: \n%s\n' % I.array)