Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 37 additions & 22 deletions docs/source/_rst/tutorials/tutorial1/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ a toy problem, following the standard API procedure.

Specifically, the tutorial aims to introduce the following topics:

- Explaining how to build **PINA** Problem,
- Showing how to generate data for ``PINN`` straining
- Explaining how to build **PINA** Problems,
- Showing how to generate data for ``PINN`` training

These are the two main steps needed **before** starting the modelling
optimization (choose model and solver, and train). We will show each
step in detail, and at the end, we will solve a simple Ordinary
Differential Equation (ODE) problem busing the ``PINN`` solver.
Differential Equation (ODE) problem using the ``PINN`` solver.

Build a PINA problem
--------------------
Expand Down Expand Up @@ -66,9 +66,8 @@ the tensor. The ``spatial_domain`` variable indicates where the sample
points are going to be sampled in the domain, in this case
:math:`x\in[0,1]`.

What about if our equation is also time dependent? In this case, our
``class`` will inherit from both ``SpatialProblem`` and
``TimeDependentProblem``:
What if our equation is also time-dependent? In this case, our ``class``
will inherit from both ``SpatialProblem`` and ``TimeDependentProblem``:

.. code:: ipython3

Expand All @@ -83,6 +82,13 @@ What about if our equation is also time dependent? In this case, our

# other stuff ...


.. parsed-literal::

Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.
Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.


where we have included the ``temporal_domain`` variable, indicating the
time domain wanted for the solution.

Expand Down Expand Up @@ -157,7 +163,7 @@ returning the difference between subtracting the variable ``u`` from its
gradient (the residual), which we hope to minimize to 0. This is done
for all conditions. Notice that we do not pass directly a ``python``
function, but an ``Equation`` object, which is initialized with the
``python`` function. This is done so that all the computations, and
``python`` function. This is done so that all the computations and
internal checks are done inside **PINA**.

Once we have defined the function, we need to tell the neural network
Expand All @@ -169,25 +175,25 @@ possibilities are allowed, see the documentation for reference).
Finally, it’s possible to define a ``truth_solution`` function, which
can be useful if we want to plot the results and see how the real
solution compares to the expected (true) solution. Notice that the
``truth_solution`` function is a method of the ``PINN`` class, but is
``truth_solution`` function is a method of the ``PINN`` class, but it is
not mandatory for problem definition.

Generate data
-------------

Data for training can come in form of direct numerical simulation
reusults, or points in the domains. In case we do unsupervised learning,
we just need the collocation points for training, i.e. points where we
want to evaluate the neural network. Sampling point in **PINA** is very
easy, here we show three examples using the ``.discretise_domain``
method of the ``AbstractProblem`` class.
results, or points in the domains. In case we perform unsupervised
learning, we just need the collocation points for training, i.e. points
where we want to evaluate the neural network. Sampling point in **PINA**
is very easy, here we show three examples using the
``.discretise_domain`` method of the ``AbstractProblem`` class.

.. code:: ipython3

# sampling 20 points in [0, 1] through discretization in all locations
problem.discretise_domain(n=20, mode='grid', variables=['x'], locations='all')

# sampling 20 points in (0, 1) through latin hypercube samping in D, and 1 point in x0
# sampling 20 points in (0, 1) through latin hypercube sampling in D, and 1 point in x0
problem.discretise_domain(n=20, mode='latin', variables=['x'], locations=['D'])
problem.discretise_domain(n=1, mode='random', variables=['x'], locations=['x0'])

Expand Down Expand Up @@ -301,11 +307,13 @@ If you want to track the metric by yourself without a logger, use
TPU available: False, using: 0 TPU cores
IPU available: False, using: 0 IPUs
HPU available: False, using: 0 HPUs
/Users/alessio/opt/anaconda3/envs/pina/lib/python3.11/site-packages/pytorch_lightning/trainer/connectors/logger_connector/logger_connector.py:67: Starting from v1.9.0, `tensorboardX` has been removed as a dependency of the `pytorch_lightning` package, due to potential conflicts with other packages in the ML ecosystem. For this reason, `logger=True` will use `CSVLogger` as the default logger, unless the `tensorboard` or `tensorboardX` packages are found. Please `pip install lightning[extra]` or one of them to enable TensorBoard support by default
Missing logger folder: /Users/alessio/Downloads/lightning_logs


.. parsed-literal::

Epoch 1499: : 1it [00:00, 272.55it/s, v_num=3, x0_loss=7.71e-6, D_loss=0.000734, mean_loss=0.000371]
Epoch 1499: | | 1/? [00:00<00:00, 167.08it/s, v_num=0, x0_loss=1.07e-5, D_loss=0.000792, mean_loss=0.000401]

.. parsed-literal::

Expand All @@ -314,7 +322,7 @@ If you want to track the metric by yourself without a logger, use

.. parsed-literal::

Epoch 1499: : 1it [00:00, 167.14it/s, v_num=3, x0_loss=7.71e-6, D_loss=0.000734, mean_loss=0.000371]
Epoch 1499: | | 1/? [00:00<00:00, 102.49it/s, v_num=0, x0_loss=1.07e-5, D_loss=0.000792, mean_loss=0.000401]


After the training we can inspect trainer logged metrics (by default
Expand All @@ -332,8 +340,8 @@ loss can be accessed by ``trainer.logged_metrics``

.. parsed-literal::

{'x0_loss': tensor(7.7149e-06),
'D_loss': tensor(0.0007),
{'x0_loss': tensor(1.0674e-05),
'D_loss': tensor(0.0008),
'mean_loss': tensor(0.0004)}


Expand All @@ -347,8 +355,13 @@ quatitative plots of the solution.
pl.plot(solver=pinn)


.. parsed-literal::

.. image:: tutorial_files/tutorial_23_0.png
Intel MKL WARNING: Support of Intel(R) Streaming SIMD Extensions 4.2 (Intel(R) SSE4.2) enabled only processors has been deprecated. Intel oneAPI Math Kernel Library 2025.0 will require Intel(R) Advanced Vector Extensions (Intel(R) AVX) instructions.



.. image:: tutorial_files/tutorial_23_1.png



Expand All @@ -375,14 +388,16 @@ could train for longer
What’s next?
------------

Nice you have completed the introductory tutorial of **PINA**! There are
multiple directions you can go now:
Congratulations on completing the introductory tutorial of **PINA**!
There are several directions you can go now:

1. Train the network for longer or with different layer sizes and assert
the finaly accuracy

2. Train the network using other types of models (see ``pina.model``)

3. GPU trainining and benchmark the speed
3. GPU training and speed benchmarking

4. Many more…


Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion pina/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
__project__ = "PINA"
__title__ = "pina"
__author__ = "PINA Contributors"
__copyright__ = "Copyright 2021-2024, PINA Contributors"
__copyright__ = "2021-2024, PINA Contributors"
__license__ = "MIT"
__version__ = "0.1.0"
__mail__ = "demo.nicola@gmail.com, dario.coscia@sissa.it" # TODO
Expand Down
76 changes: 50 additions & 26 deletions tutorials/tutorial1/tutorial.ipynb

Large diffs are not rendered by default.

32 changes: 17 additions & 15 deletions tutorials/tutorial1/tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
#
# Specifically, the tutorial aims to introduce the following topics:
#
# * Explaining how to build **PINA** Problem,
# * Showing how to generate data for `PINN` straining
# * Explaining how to build **PINA** Problems,
# * Showing how to generate data for `PINN` training
#
# These are the two main steps needed **before** starting the modelling optimization (choose model and solver, and train). We will show each step in detail, and at the end, we will solve a simple Ordinary Differential Equation (ODE) problem busing the `PINN` solver.
# These are the two main steps needed **before** starting the modelling optimization (choose model and solver, and train). We will show each step in detail, and at the end, we will solve a simple Ordinary Differential Equation (ODE) problem using the `PINN` solver.

# ## Build a PINA problem

Expand Down Expand Up @@ -47,7 +47,7 @@
#
# Notice that we define `output_variables` as a list of symbols, indicating the output variables of our equation (in this case only $u$), this is done because in **PINA** the `torch.Tensor`s are labelled, allowing the user maximal flexibility for the manipulation of the tensor. The `spatial_domain` variable indicates where the sample points are going to be sampled in the domain, in this case $x\in[0,1]$.
#
# What about if our equation is also time dependent? In this case, our `class` will inherit from both `SpatialProblem` and `TimeDependentProblem`:
# What if our equation is also time-dependent? In this case, our `class` will inherit from both `SpatialProblem` and `TimeDependentProblem`:
#

# In[1]:
Expand Down Expand Up @@ -122,24 +122,24 @@ def truth_solution(self, pts):
problem = SimpleODE()


# After we define the `Problem` class, we need to write different class methods, where each method is a function returning a residual. These functions are the ones minimized during PINN optimization, given the initial conditions. For example, in the domain $[0,1]$, the ODE equation (`ode_equation`) must be satisfied. We represent this by returning the difference between subtracting the variable `u` from its gradient (the residual), which we hope to minimize to 0. This is done for all conditions. Notice that we do not pass directly a `python` function, but an `Equation` object, which is initialized with the `python` function. This is done so that all the computations, and internal checks are done inside **PINA**.
# After we define the `Problem` class, we need to write different class methods, where each method is a function returning a residual. These functions are the ones minimized during PINN optimization, given the initial conditions. For example, in the domain $[0,1]$, the ODE equation (`ode_equation`) must be satisfied. We represent this by returning the difference between subtracting the variable `u` from its gradient (the residual), which we hope to minimize to 0. This is done for all conditions. Notice that we do not pass directly a `python` function, but an `Equation` object, which is initialized with the `python` function. This is done so that all the computations and internal checks are done inside **PINA**.
#
# Once we have defined the function, we need to tell the neural network where these methods are to be applied. To do so, we use the `Condition` class. In the `Condition` class, we pass the location points and the equation we want minimized on those points (other possibilities are allowed, see the documentation for reference).
#
# Finally, it's possible to define a `truth_solution` function, which can be useful if we want to plot the results and see how the real solution compares to the expected (true) solution. Notice that the `truth_solution` function is a method of the `PINN` class, but is not mandatory for problem definition.
# Finally, it's possible to define a `truth_solution` function, which can be useful if we want to plot the results and see how the real solution compares to the expected (true) solution. Notice that the `truth_solution` function is a method of the `PINN` class, but it is not mandatory for problem definition.
#

# ## Generate data
#
# Data for training can come in form of direct numerical simulation reusults, or points in the domains. In case we do unsupervised learning, we just need the collocation points for training, i.e. points where we want to evaluate the neural network. Sampling point in **PINA** is very easy, here we show three examples using the `.discretise_domain` method of the `AbstractProblem` class.
# Data for training can come in form of direct numerical simulation results, or points in the domains. In case we perform unsupervised learning, we just need the collocation points for training, i.e. points where we want to evaluate the neural network. Sampling point in **PINA** is very easy, here we show three examples using the `.discretise_domain` method of the `AbstractProblem` class.

# In[3]:


# sampling 20 points in [0, 1] through discretization in all locations
problem.discretise_domain(n=20, mode='grid', variables=['x'], locations='all')

# sampling 20 points in (0, 1) through latin hypercube samping in D, and 1 point in x0
# sampling 20 points in (0, 1) through latin hypercube sampling in D, and 1 point in x0
problem.discretise_domain(n=20, mode='latin', variables=['x'], locations=['D'])
problem.discretise_domain(n=1, mode='random', variables=['x'], locations=['x0'])

Expand Down Expand Up @@ -168,7 +168,7 @@ def truth_solution(self, pts):

# To visualize the sampled points we can use the `.plot_samples` method of the `Plotter` class

# In[6]:
# In[5]:


from pina import Plotter
Expand All @@ -181,7 +181,7 @@ def truth_solution(self, pts):

# Once we have defined the problem and generated the data we can start the modelling. Here we will choose a `FeedForward` neural network available in `pina.model`, and we will train using the `PINN` solver from `pina.solvers`. We highlight that this training is fairly simple, for more advanced stuff consider the tutorials in the ***Physics Informed Neural Networks*** section of ***Tutorials***. For training we use the `Trainer` class from `pina.trainer`. Here we show a very short training and some method for plotting the results. Notice that by default all relevant metrics (e.g. MSE error during training) are going to be tracked using a `lightining` logger, by default `CSVLogger`. If you want to track the metric by yourself without a logger, use `pina.callbacks.MetricTracker`.

# In[7]:
# In[6]:


from pina import Trainer
Expand Down Expand Up @@ -210,7 +210,7 @@ def truth_solution(self, pts):

# After the training we can inspect trainer logged metrics (by default **PINA** logs mean square error residual loss). The logged metrics can be accessed online using one of the `Lightinig` loggers. The final loss can be accessed by `trainer.logged_metrics`

# In[8]:
# In[7]:


# inspecting final loss
Expand All @@ -219,7 +219,7 @@ def truth_solution(self, pts):

# By using the `Plotter` class from **PINA** we can also do some quatitative plots of the solution.

# In[9]:
# In[8]:


# plotting the solution
Expand All @@ -228,7 +228,7 @@ def truth_solution(self, pts):

# The solution is overlapped with the actual one, and they are barely indistinguishable. We can also plot easily the loss:

# In[10]:
# In[9]:


pl.plot_loss(trainer=trainer, label = 'mean_loss', logy=True)
Expand All @@ -238,12 +238,14 @@ def truth_solution(self, pts):

# ## What's next?
#
# Nice you have completed the introductory tutorial of **PINA**! There are multiple directions you can go now:
# Congratulations on completing the introductory tutorial of **PINA**! There are several directions you can go now:
#
# 1. Train the network for longer or with different layer sizes and assert the finaly accuracy
#
# 2. Train the network using other types of models (see `pina.model`)
#
# 3. GPU trainining and benchmark the speed
# 3. GPU training and speed benchmarking
#
# 4. Many more...

#
4 changes: 2 additions & 2 deletions tutorials/tutorial2/tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@
"source": [
"After the problem, the feed-forward neural network is defined, through the class `FeedForward`. This neural network takes as input the coordinates (in this case $x$ and $y$) and provides the unkwown field of the Poisson problem. The residual of the equations are evaluated at several sampling points (which the user can manipulate using the method `CartesianDomain_pts`) and the loss minimized by the neural network is the sum of the residuals.\n",
"\n",
"In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs with a learning rate of 0.006 and $l_2$ weight regularization set to $10^{-7}$. These parameters can be modified as desired. We use the `MetricTracker` class to track the metrics during training."
"In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs with a learning rate of 0.006 and $l_2$ weight regularization set to $10^{-8}$. These parameters can be modified as desired. We use the `MetricTracker` class to track the metrics during training."
]
},
{
Expand Down Expand Up @@ -561,7 +561,7 @@
"source": [
"## What's next?\n",
"\n",
"Nice you have completed the two dimensional Poisson tutorial of **PINA**! There are multiple directions you can go now:\n",
"Congratulations on completing the two dimensional Poisson tutorial of **PINA**! There are multiple directions you can go now:\n",
"\n",
"1. Train the network for longer or with different layer sizes and assert the finaly accuracy\n",
"\n",
Expand Down
4 changes: 2 additions & 2 deletions tutorials/tutorial2/tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def poisson_sol(self, pts):

# After the problem, the feed-forward neural network is defined, through the class `FeedForward`. This neural network takes as input the coordinates (in this case $x$ and $y$) and provides the unkwown field of the Poisson problem. The residual of the equations are evaluated at several sampling points (which the user can manipulate using the method `CartesianDomain_pts`) and the loss minimized by the neural network is the sum of the residuals.
#
# In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs with a learning rate of 0.006 and $l_2$ weight regularization set to $10^{-7}$. These parameters can be modified as desired. We use the `MetricTracker` class to track the metrics during training.
# In this tutorial, the neural network is composed by two hidden layers of 10 neurons each, and it is trained for 1000 epochs with a learning rate of 0.006 and $l_2$ weight regularization set to $10^{-8}$. These parameters can be modified as desired. We use the `MetricTracker` class to track the metrics during training.

# In[3]:

Expand Down Expand Up @@ -252,7 +252,7 @@ def forward(self, x):

# ## What's next?
#
# Nice you have completed the two dimensional Poisson tutorial of **PINA**! There are multiple directions you can go now:
# Congratulations on completing the two dimensional Poisson tutorial of **PINA**! There are multiple directions you can go now:
#
# 1. Train the network for longer or with different layer sizes and assert the finaly accuracy
#
Expand Down
Loading