## Show code cell source

```
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib_inline
matplotlib_inline.backend_inline.set_matplotlib_formats('svg')
import seaborn as sns
sns.set_context("paper")
sns.set_style("ticks");
!pip show equinox || echo equinox not found. Installing... && pip install equinox 2> /dev/null
```

## Show code cell output

```
Name: equinox
Version: 0.11.2
Summary: Elegant easy-to-use neural networks in JAX.
Home-page:
Author:
Author-email: Patrick Kidger <contact@kidger.site>
License: Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
Location: /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages
Requires: jax, jaxtyping, typing-extensions
Required-by: diffrax, lineax, optimistix, orthojax
Requirement already satisfied: equinox in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (0.11.2)
Requirement already satisfied: jax>=0.4.13 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from equinox) (0.4.19)
Requirement already satisfied: jaxtyping>=0.2.20 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from equinox) (0.2.25)
Requirement already satisfied: typing-extensions>=4.5.0 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from equinox) (4.8.0)
Requirement already satisfied: ml-dtypes>=0.2.0 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (0.3.1)
Requirement already satisfied: numpy>=1.22 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (1.25.2)
Requirement already satisfied: opt-einsum in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (3.3.0)
Requirement already satisfied: scipy>=1.9 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jax>=0.4.13->equinox) (1.11.3)
Requirement already satisfied: typeguard<3,>=2.13.3 in /Users/ibilion/.pyenv/versions/3.11.6/lib/python3.11/site-packages (from jaxtyping>=0.2.20->equinox) (2.13.3)
```

## Show code cell source

```
import jax
import equinox as eqx
class FourierEncoding(eqx.Module):
B: jax.Array
@property
def num_fourier_features(self) -> int:
return self.B.shape[0]
@property
def in_size(self) -> int:
return self.B.shape[1]
@property
def out_size(self) -> int:
return self.B.shape[0] * 2
def __init__(self,
in_size: int,
num_fourier_features: int,
key: jax.random.PRNGKey,
sigma: float = 1.0):
self.B = jax.random.normal(
key, shape=(num_fourier_features, in_size),
dtype=jax.numpy.float32) * sigma
def __call__(self, x: jax.Array, **kwargs) -> jax.Array:
return jax.numpy.concatenate(
[jax.numpy.cos(jax.numpy.dot(self.B, x)),
jax.numpy.sin(jax.numpy.dot(self.B, x))],
axis=0)
def train_pinn(
loss,
fourier_mlp,
key,
optimizer,
filter_spec,
Lx=1.0,
Ly=1.0,
num_collocation_residual=512,
num_iter=10_000,
freq=1,
):
# this is new
def new_loss(diff_model, static_model, x, y):
comb_model = eqx.combine(diff_model, static_model)
return loss(comb_model, x, y)
@eqx.filter_jit
def step(opt_state, model, xs, ys):
# added this line
diff_model, static_model = eqx.partition(model, filter_spec)
# changed the loss to the new loss
value, grads = eqx.filter_value_and_grad(new_loss)(diff_model, static_model, xs, ys)
updates, opt_state = optimizer.update(grads, opt_state)
model = eqx.apply_updates(model, updates)
return model, opt_state, value
opt_state = optimizer.init(eqx.filter(fourier_mlp, eqx.is_inexact_array))
losses = []
for i in range(num_iter):
key1, key2, key = jrandom.split(key, 3)
xb = jrandom.uniform(key1, (num_collocation_residual,), maxval=Lx)
yb = jrandom.uniform(key2, (num_collocation_residual,), maxval=Ly)
fourier_mlp, opt_state, value = step(opt_state, fourier_mlp, xb, yb)
if i % freq == 0:
losses.append(value)
print(f"Step {i}, residual loss {value:.3e}")
return fourier_mlp, losses
```

# Energy Functionals#

In this notebook, we are still working with the steady-state heat equation:

\begin{aligned} -k\Delta u(x, y) &= f(x, y) \quad \text{in} \quad \Omega = [0, L_x]\times [0, L_y], \ u(x, y) &= 0 \quad \text{on} \quad \partial \Omega. \end{aligned}

Before, we parameterized the solution so that it satisfied the boundary conditions. Then, we constructed a loss function using the residual of the PDE.

If we forget about the parameterization for a moment, we can think of the integrated squared residual of the PDE as a function that takes a candidate solution to the PDE and returns a scalar:

Such a function is called a \emph{functional}.

It turns out that for the steady-state heat equation, there is a much much better functional. It is called the \emph{energy functional} and is defined as:

Here are some good things about this functional:

A function that minimizes \(E[u]\) is a solution to the PDE. We will show this.

Only a first derivative of \(u\) appears in the integrand. This means that our function lives in the Sobolev space \(W^{1, 2}(\Omega)\) instead of \(W^{2, 2}(\Omega)\). This means that we could even use a ReLU network to represent the solution to the PDE.

The functional \(E[u]\) has a unique minimizer in \(W^{1, 2}(\Omega)\), among the functions that satisfy the boundary conditions.

Note

The Sobolev space \(W^{1, 2}(\Omega)\) is the space of functions whose first derivatives are square-integrable. The space \(W^{2, 2}(\Omega)\) is the space of functions whose second derivatives are square-integrable. Learn more about Sobolev spaces here.

To show that a function that minimizes \(E[u]\) is a solution to the PDE, we will use the concept of the functional derivative. A functional derivative is a generalization of the derivative of a function to functionals. It is defined as:

where \(v\) is a function in \(W_0^{1, 2}(\Omega)\). The subscript \(0\) in \(W_0^{1, 2}(\Omega)\) means that the functions in the space are zero on the boundary of \(\Omega\). We also call \(\frac{\delta E[u]}{\delta v}\) the \emph{functional derivative} of \(E[u]\) with respect to \(u\) in the direction of \(v\). Another name for the functional derivative is the \emph{first variation} of \(E[u]\) at \(u\) in the direction of \(v\).

There is a theorem that says that if a function \(u\) minimizes \(E[u]\), then the functional derivative of \(E[u]\) at \(u\) in the direction of \(v\) is zero for all \(v\) in \(W_0^{1, 2}(\Omega)\). We prove this in the lecture. Here, let’s find the first variation of \(E[u]\) at \(u\) in the direction of \(v\). We have:

\begin{align*}
\frac{\delta E[u]}{\delta v} &= \frac{d}{d\epsilon}E[u + \epsilon v] \bigg|*{\epsilon = 0} \
&= \frac{d}{d\epsilon}\int*{\Omega} \left[ \frac{k}{2}|\nabla (u + \epsilon v)|^2 - f(u + \epsilon v) \right] , dx , dy \bigg|*{\epsilon = 0} \
&= \int*{\Omega} \frac{d}{d\epsilon}\left[ \frac{k}{2}|\nabla (u + \epsilon v)|^2 - f(u + \epsilon v) \right]\bigg|*{\epsilon = 0} , dx , dy \
&= \int*{\Omega}
\frac{d}{d\epsilon}\left[ \frac{k}{2}(\nabla u + \epsilon \nabla v)\cdot (\nabla u + \epsilon \nabla v) - f(u + \epsilon v) \right]\bigg|*{\epsilon = 0} , dx , dy \
&= \int*{\Omega}
\frac{d}{d\epsilon}\left[ \frac{k}{2}(\nabla u\cdot \nabla u + 2\epsilon \nabla u\cdot \nabla v + \epsilon^2 \nabla v\cdot \nabla v) - f(u + \epsilon v) \right]\bigg|*{\epsilon = 0} , dx , dy \
&= \int*{\Omega}
\left[ k\nabla u\cdot \nabla v - fv \right] , dx , dy. \
\end{align*}

Now, we integrate by parts to get:

\begin{align*} \frac{\delta E[u]}{\delta v} &= \int_{\Omega} \left[ k\nabla u\cdot \nabla v - fv \right] , dx , dy \ &= \int_{\Omega} \left[ -\nabla \cdot (k\nabla u) - f \right]v , dx , dy \ &= \int_{\Omega} \left[ -k\Delta u - f \right]v , dx , dy. \end{align*}

If this is zero for all \(v\) in \(W_0^{1, 2}(\Omega)\), the part of the integrand that multiplies \(v\) must be zero. So, \(u\) must satisfy the PDE.

To show that the functional \(E[u]\) has a unique minimizer in \(W^{1, 2}(\Omega)\), we would have to find the second variation of \(E[u]\) at \(u\) in the direction of \(v\) and show that it is strongly positive. We will do this in the lecture.

# Non-dimensionalizing the Energy Functional#

We scale everything like we did before:

\begin{align*} x &\mapsto \tilde{x} = \frac{x}{L_x}, \ y &\mapsto \tilde{y} = \frac{y}{L_y}, \ u &\mapsto \tilde{u} = \frac{u}{u_s}, \ f &\mapsto \tilde{f} = \frac{f}{f_s}. \ \end{align*}

We can now directly make the change on the energy functional:

\begin{align*} E[u] &= L_xL_y\int_{\tilde{\Omega}} \left{ \frac{1}{2}\left[\frac{ku_s^2}{L_x^2}\left(\frac{\partial \tilde{u}}{\partial \tilde{x}}\right)^2 + \frac{ku_s^2}{L_y^2}\left(\frac{\partial \tilde{u}}{\partial \tilde{y}}\right)^2\right] - f_su_s\tilde{f}\tilde{u} \right} , d\tilde{x} , d\tilde{y} \ &= L_xL_yf_su_s \int_{\tilde{\Omega}} \left{ \frac{1}{2}\left[\frac{ku_s}{L_x^2f_s}\left(\frac{\partial \tilde{u}}{\partial \tilde{x}}\right)^2 + \frac{ku_s}{L_y^2f_s}\left(\frac{\partial \tilde{u}}{\partial \tilde{y}}\right)^2\right] - \tilde{f}\tilde{u} \right} , d\tilde{x} , d\tilde{y} \ &= L_xL_yf_su_s \int_{\tilde{\Omega}} \left{ \frac{1}{2}\left[k_x\left(\frac{\partial \tilde{u}}{\partial \tilde{x}}\right)^2 + k_y\left(\frac{\partial \tilde{u}}{\partial \tilde{y}}\right)^2\right] - \tilde{f}\tilde{u} \right} , d\tilde{x} , d\tilde{y}, \ &= L_xL_yf_su_s \tilde{E}[\tilde{u}], \end{align*}

where we have defined \(k_x = \frac{ku_s}{L_x^2f_s}\) and \(k_y = \frac{ku_s}{L_y^2f_s}\).

We pick

Now, we will pick \(u_s\) to make the two terms inside \(\tilde{E}[\tilde{u}]\) have the same order of magnitude. So, we pick:

\begin{align*}
&\left|k_x\left(\frac{\partial \tilde{u}}{\partial \tilde{x}}\right)^2+ k_y\left(\frac{\partial \tilde{u}}{\partial \tilde{y}}\right)^2\right|*{\infty} = |\tilde{f}\tilde{u}|*{\infty}, \
&\implies
\frac{ku_s}{f_s} \left|\left(L_x^{-2}\frac{\partial \tilde{u}}{\partial \tilde{x}}\right)^2+ L_y^{-2}\left(\frac{\partial \tilde{u}}{\partial \tilde{y}}\right)^2\right|*{\infty} = |\tilde{f}\tilde{u}|*{\infty}, \
&\implies
u_s = \frac{f_s}{k}|\tilde{f}\tilde{u}|*{\infty}\left|L_x^{-2}\left(\frac{\partial \tilde{u}}{\partial \tilde{x}}\right)^2+ L_y^{-2}\left(\frac{\partial \tilde{u}}{\partial \tilde{y}}\right)^2\right|*{\infty}^{-1}.
\end{align*}

At the same time, we want to make both terms to be of order one. This can be achieved by picking:

or

Okay, let’s do it.

Start with our problem definition:

```
import jax.numpy as jnp
u0 = 500 # degrees Kelvin
k = 10.0 # thermal conductivity in W/mK
Lx = 0.1 # meters
Ly = 1.0 # meters
f = lambda x, y: 2.0 * jnp.pi ** 2 * k * u0 * (
-Lx ** 2 * jnp.sin(jnp.pi * x / Lx) ** 2 * jnp.cos(2.0 * jnp.pi * y / Ly)
-Ly ** 2 * jnp.sin(jnp.pi * y / Ly) ** 2 * jnp.cos(2.0 * jnp.pi * x / Lx)
) / (Lx ** 2 * Ly ** 2)
```

Some of the scaling:

```
to_x = lambda xt: xt * Lx
to_y = lambda yt: yt * Ly
to_xt = lambda x: x / Lx
to_yt = lambda y: y / Ly
```

For \(u_s\), we need to parameterize the field:

```
# Make our model
import jax
import jax.random as jrandom
key = jrandom.PRNGKey(0)
key1, key2, key = jrandom.split(key, 3)
num_fourier_features = 100
width = 256
depth = 4
model = eqx.nn.Sequential([
FourierEncoding(2, num_fourier_features, key1),
eqx.nn.MLP(2 * num_fourier_features, 'scalar', width, depth, jax.nn.tanh, key=key2),
])
ut = lambda xt, yt, model: xt * (1 - xt) * yt * (1 - yt) * model(jnp.array([xt, yt]))
```

Some code to calculate infinity norms of functions using points:

```
jit_vmap = lambda g: jit(vmap(g, in_axes=(0, 0)))
infinity_norm = lambda g, xs, ys: jnp.max(jnp.abs(jit_vmap(g)(xs, ys)))
```

Now, we can find \(f_s\):

```
from jax import vmap, jit
xs = jnp.linspace(0, Lx, 100)
ys = jnp.linspace(0, Ly, 100)
X, Y = jnp.meshgrid(xs, ys)
Xt = to_xt(X)
Yt = to_yt(Y)
Xt_flat = Xt.flatten()
Yt_flat = Yt.flatten()
fs = infinity_norm(lambda xt, yt: f(to_x(xt), to_y(yt)) * ut(xt, yt, model), Xt_flat, Yt_flat)
# The scaled version of the source
ft = lambda xt, yt: f(to_x(xt), to_y(yt)) / fs
print(f"fs = {fs:.3e}")
```

```
fs = 1.364e+04
```

And we can find \(u_s\):

```
term1 = jit(vmap(lambda xt, yt: jnp.abs(ft(xt, yt) * ut(xt, yt, model)), in_axes=(0, 0)))(Xt_flat, Yt_flat).max()
from jax import grad
ut_x = grad(ut, 0)
ut_y = grad(ut, 1)
term2 = infinity_norm(lambda xt, yt: ut_x(xt, yt, model) ** 2 / Lx ** 2 + ut_y(xt, yt, model) **2 / Ly ** 2, Xt_flat, Yt_flat)
us = (fs * term1) / (k * term2)
print(f"us = {us:.3e}")
```

```
us = 6.414e+04
```

Now, we can define the scaled energy thermal conductivity:

```
kx = (k * us) / (Lx ** 2 * fs)
ky = (k * us) / (Ly ** 2 * fs)
print(f"kx = {kx:.3e}, ky = {ky:.3e}")
```

```
kx = 4.702e+03, ky = 4.702e+01
```

Let’s verify that we have the proper scaling:

```
tE_term1 = jit(vmap(lambda xt, yt: 0.5 * (kx * ut_x(xt, yt, model) ** 2 + kx * ut_y(xt, yt, model) ** 2), in_axes=(0, 0)))
tE_term2 = jit(vmap(lambda xt, yt: ft(xt, yt) * ut(xt, yt, model), in_axes=(0, 0)))
fig, ax = plt.subplots(1,2)
trm1 = tE_term1(Xt_flat, Yt_flat).reshape(X.shape)
c = ax[0].contourf(Xt, Yt, trm1, cmap='viridis')
fig.colorbar(c, ax=ax[0])
ax[0].set_xlabel(r'$\tilde{x}$')
ax[0].set_ylabel(r'$\tilde{y}$')
ax[0].set_title('Term 1')
trm2 = tE_term2(Xt_flat, Yt_flat).reshape(X.shape)
c = ax[1].contourf(Xt, Yt, trm2, cmap='viridis')
fig.colorbar(c, ax=ax[1])
ax[1].set_xlabel(r'$\tilde{x}$')
ax[1].set_ylabel(r'$\tilde{y}$')
ax[1].set_title('Term 2')
sns.despine(trim=True)
plt.tight_layout();
```

We will take this. It looks good. Notice that the scaling is completely different from before.

## Training the Network#

Let’s make our new loss:

```
energy_loss = vmap(
lambda xt, yt, model: 0.5 * (kx * ut_x(xt, yt, model) ** 2 + ky * ut_y(xt, yt, model) ** 2) - ft(xt, yt) * ut(xt, yt, model),
in_axes=(0, 0, None),
)
pinn_loss = lambda model, xt, yt: jnp.mean(energy_loss(xt, yt, model))
```

```
import optax
import jax.tree_util as jtu
# Here, I am actually optimizing the Fourier coefficients
filter_spec = jtu.tree_map(lambda _: True, model)
key, subkey = jax.random.split(key)
optimizer = optax.adam(1e-3)
trained_model, losses = train_pinn(
pinn_loss, model, subkey, optimizer, filter_spec,
num_collocation_residual=256, num_iter=5_000, freq=100, Lx=1.0, Ly=1.0)
```

```
Step 0, residual loss 1.035e-01
Step 100, residual loss -2.370e-01
Step 200, residual loss -2.250e-01
Step 300, residual loss -1.002e-01
Step 400, residual loss -3.273e-01
Step 500, residual loss -2.182e-01
Step 600, residual loss -1.557e-01
Step 700, residual loss -2.311e-01
Step 800, residual loss -2.145e-01
Step 900, residual loss -2.937e-01
Step 1000, residual loss -3.032e-02
Step 1100, residual loss -3.340e-01
Step 1200, residual loss -2.046e-01
Step 1300, residual loss -1.865e-01
Step 1400, residual loss -1.772e-01
Step 1500, residual loss -3.224e-01
Step 1600, residual loss -3.415e-01
Step 1700, residual loss -1.926e-01
Step 1800, residual loss -2.110e-01
Step 1900, residual loss -3.176e-01
Step 2000, residual loss -4.067e-01
Step 2100, residual loss -2.817e-01
Step 2200, residual loss -2.407e-01
Step 2300, residual loss -2.483e-01
Step 2400, residual loss -3.020e-01
Step 2500, residual loss -2.907e-01
Step 2600, residual loss -2.233e-01
Step 2700, residual loss -1.766e-01
Step 2800, residual loss -2.577e-01
Step 2900, residual loss -5.195e-01
Step 3000, residual loss -2.384e-01
Step 3100, residual loss -1.722e-01
Step 3200, residual loss -2.518e-01
Step 3300, residual loss -2.413e-01
Step 3400, residual loss -4.015e-01
Step 3500, residual loss -3.214e-01
Step 3600, residual loss -4.055e-01
Step 3700, residual loss -2.391e-01
Step 3800, residual loss -1.856e-01
Step 3900, residual loss -1.745e-01
Step 4000, residual loss -3.876e-01
Step 4100, residual loss -2.380e-01
Step 4200, residual loss -1.656e-01
Step 4300, residual loss -2.280e-01
Step 4400, residual loss -2.837e-01
Step 4500, residual loss -2.168e-01
Step 4600, residual loss -1.857e-01
Step 4700, residual loss -3.263e-01
Step 4800, residual loss -2.783e-01
Step 4900, residual loss -3.873e-01
```

Let’s look at the evolution of the energy functional during training:

```
fig, ax = plt.subplots()
ax.plot(losses)
ax.set_xlabel('Iteration x 100')
ax.set_ylabel('Energy loss')
sns.despine(trim=True);
```

```
u_true = u0 * jnp.sin(jnp.pi * X / Lx) ** 2 * jnp.sin(jnp.pi * Y / Ly) ** 2
vtu = jit(vmap(lambda xt, yt: ut(xt, yt, trained_model)))
u_pred = vtu(Xt_flat, Yt_flat).reshape(X.shape) * us
fig, ax = plt.subplots(1,2)
c = ax[0].contourf(X, Y, u_pred, cmap='viridis',
levels=jnp.linspace(-1, 510.0, 10))
fig.colorbar(c, ax=ax[0])
ax[0].set_xlabel('x')
ax[0].set_ylabel('y')
ax[0].set_title('Trained solution')
sns.despine(trim=True);
c = ax[1].contourf(X, Y, u_true, cmap='viridis',
levels=jnp.linspace(-1, 510.0, 10))
fig.colorbar(c, ax=ax[1])
ax[1].set_xlabel('x')
ax[1].set_ylabel('y')
ax[1].set_title('Scaled true solution')
sns.despine(trim=True)
plt.tight_layout();
```

```
fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Trained solution')
c = ax.contourf(to_xt(X), to_yt(Y), jnp.abs(u_pred - u_true), cmap='viridis')
plt.colorbar(c, ax=ax)
sns.despine(trim=True);
```

It is actually not as accurate as the residual loss. It probably needs more iterations to converge. The structure and optimization parameters were optimized for the integrated residual loss.