Source code for simulai.backup.Network.test_deeponet

# (C) Copyright IBM Corp. 2019, 2020, 2021, 2022.

#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at

#           http://www.apache.org/licenses/LICENSE-2.0

#     Unless required by applicable law or agreed to in writing, software
#     distributed under the License is distributed on an "AS IS" BASIS,
#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#     See the License for the specific language governing permissions and
#     limitations under the License.

import numpy as np
from unittest import TestCase
import matplotlib.pyplot as plt

from simulai.math.integration import RK4
from simulai.regression import DenseNetwork
from simulai.models import DeepONet
from simulai.metrics import L2Norm
from simulai.math.spaces import GaussianRandomFields

# Nonlinear ODE system used for generating test data
[docs]class NonlinearODE: def __init__(self): pass def __call__(self, data): s = data[:, 0] u = data[:, 1] return -(s**2) + u
# Antiderivative operator
[docs]class Antiderivative: def __init__(self): pass def __call__(self, u): return u
# Some forcing terms used
[docs]def sinx_forcing(x): return np.sin(np.pi*x)
[docs]def sin2x_forcing(x): return np.sin(2*np.pi*x)
[docs]def x_forcing(x): return x
[docs]def solver(x_interval=None, N=None, x=None, dx=None, u=x_forcing): if x is None and (N is not None and x_interval is not None): x = np.linspace(0, 1, N) dx = (x_interval[1] - x_interval[0])/N elif isinstance(x, np.ndarray): assert dx, "dx must be provided." N = u.shape[0] else: raise Exception("Case not covered.") initial_state = np.array([0])[None, :] if callable(u): forcings = u(x)[:, None] elif isinstance(u, np.ndarray): assert u.shape[0] == x.shape[0] forcings = u else: raise Exception(f'It is expected a callable or np.ndarray, but received {u}') nonlinear_ODE = NonlinearODE() integrator = RK4(right_operator=nonlinear_ODE) output_array = integrator(initial_state=initial_state, epochs=N, dt=dx, forcings=forcings) return output_array, forcings, x[:, None]
[docs]class TestDeepONet(TestCase):
[docs] def setUp(self) -> None: self.enable_plots = False
[docs] def generate_GRF_data(self, x_interval, N_tot, n_features): points = np.linspace(*x_interval, N_tot) # Positions for sampling u data generator = GaussianRandomFields(x_interval=(0, 1), kernel='RBF', length_scale=.2, N=N_tot, interp='cubic') features = generator.random_u(n_features=n_features) u_exec = generator.generate_u(features, points) dx = (x_interval[1] - x_interval[0]) / N_tot outputs_list = list() for ff in range(n_features): s, _, _ = solver(N=N_tot, dx=dx, x=points, u=u_exec[:, ff][:, None]) outputs_list.append(s) print(f"Executed test with the forcing {ff}") outputs_data = np.hstack(outputs_list) return outputs_data, u_exec, points[:, None]
# Baseline execution test
[docs] def test_deeponet_scalar_scattered(self): N_samples = 1000 N_tot = int(1e4) forcings = [x_forcing, sinx_forcing, sin2x_forcing] sample_indices = np.random.choice(N_tot, N_samples, replace=False) for forcing in forcings: s, u, x = solver(x_interval=[0, 1], N=N_tot, u=forcing) s_sampled = s[sample_indices] u_sampled = u[sample_indices] x_sampled = x[sample_indices] p = 100 trunk_architecture = [40, 40, 40] trunk_setup = { 'architecture': trunk_architecture, 'dropouts_rates_list': [0, 0, 0], 'activation_function': 'relu', 'input_dim': 1, 'output_dim': p } branches_architecture = [40, 40] branches_setup = { 'architecture': branches_architecture, 'dropouts_rates_list': [0, 0, 0], 'activation_function': 'relu', 'input_dim': 1, 'output_dim': p } trunk_net = DenseNetwork(architecture=trunk_architecture, config=trunk_setup, concat_output_tensor=True, concat_input_tensor=True) branch_net = DenseNetwork(architecture=branches_architecture, config=branches_setup, concat_output_tensor=True, concat_input_tensor=True) optimizers_config = {"Adam": {"maxiter": 10000}} operator = DeepONet(trunk_network=trunk_net, branch_network=branch_net, optimizers_config=optimizers_config, model_id='nonlinear_ode') operator.fit(x_sampled, u_sampled, s_sampled, shuffle=True) s_evaluated = operator.eval(trunk_data=x, branch_data=u) l2_norm = L2Norm() error = l2_norm(data=s_evaluated, reference_data=s, relative_norm=True) print(f'Approximation error for forcing {forcing.__name__} is {100*error} %') if self.enable_plots: plt.plot(x, s_evaluated, label="Approximation") plt.plot(x, s, label="Exact") plt.scatter(x_sampled, s_sampled) plt.grid(True) plt.legend() plt.xlabel("x") plt.ylabel("s") plt.show()
# Generating data using Gaussian Random Fields