Physics-Informed Neural Networks Explained With a Worked Heat Example

A physics-informed neural network puts the governing PDE into the loss function and gets its derivatives from automatic differentiation. We explain the loss, train one from scratch on 1D transient heat conduction (0.004% error against the exact solution), recover an unknown diffusivity from 40 noisy readings, and set out when PINNs beat a surrogate or a solver, when they fail, and which tools to learn.

Physics-Informed Neural Networks Explained With a Worked Heat Example

A physics-informed neural network (PINN) is a neural network trained to satisfy a differential equation, not just to fit data. Its loss function adds up three kinds of error: how far the network's output is from the initial and boundary conditions, how far it is from any measurements you have, and how badly it violates the governing equation at thousands of random points inside the domain. The derivatives in that equation come from automatic differentiation of the network itself, so no mesh is needed. The method was named by Raissi, Perdikaris and Karniadakis in 2017 preprints and a 2019 paper in the Journal of Computational Physics.

This guide is for mechanical and CAE engineers who know what a PDE and a neural network are but have not trained one against physics. We explain the loss, the role of automatic differentiation, and how a PINN differs from a surrogate model and from FEA or CFD. Then we train one from scratch on 1D transient heat conduction with a numpy-only script you can read, use the same network to recover an unknown thermal diffusivity from noisy data, and finish with when PINNs win, when they lose, and which tools to learn.

In short

  • The defining paper (Raissi, Perdikaris and Karniadakis, J. Comput. Phys. 378, 2019) treats two problems: solving a PDE from its conditions alone (forward) and discovering PDE parameters from data (inverse). Crossref recorded about 21,700 citing works on 30 Nov 2026.
  • Our forward PINN for , a 2-32-32-1 tanh network with 1,185 parameters, reached a relative L2 error of 3.84 × 10⁻⁵ (0.004%) against the exact solution after 3,000 Adam steps and 3,000 L-BFGS iterations, about 75 s on a laptop CPU in numpy (Skill-Lync run, 30 Nov 2026).
  • The same network trained on the initial and boundary points only, with the PDE term switched off, fitted those points to the same loss but was 68.3% wrong in the interior. The physics term is what fills the domain.
  • Inverse run: with 40 interior measurements carrying noise of standard deviation 0.02, the PINN identified the diffusivity as 0.0979 against a true 0.1 (2.13% off), starting from a guess of 0.5.
  • Tools as of 30 Nov 2026: DeepXDE 1.15.1 (2 Nov 2026, LGPL-2.1, five backends) and NVIDIA PhysicsNeMo 2.3.0 (21 Nov 2026, Apache 2.0, PyTorch), with PhysicsNeMo Sym 2.4.0 for PINN workflows.

What is a physics-informed neural network?

A physics-informed neural network is an ordinary dense neural network whose inputs are the coordinates of a problem (position, time, sometimes a design parameter) and whose output is the field you want (temperature, displacement, velocity). It is trained so that the output obeys the governing differential equation, the boundary and initial conditions, and any measured data, all at once. The network becomes the solution, and you can evaluate it at any point without a mesh.

The idea of using a neural network as a trial solution for differential equations goes back at least to Lagaris, Likas and Fotiadis in 1998. The modern form, with the equation enforced through the loss at random collocation points and derivatives from automatic differentiation, was set out by Maziar Raissi, Paris Perdikaris and George Karniadakis in two arXiv preprints on 28 Nov 2017 (Part I, data-driven solutions; Part II, data-driven discovery) and in the 2019 Journal of Computational Physics paper. Their abstract describes networks "trained to solve supervised learning tasks while respecting any given law of physics described by general nonlinear partial differential equations". The wider field, which also covers neural operators and physics-constrained architectures, is called physics-informed machine learning after the 2021 Nature Reviews Physics review by Karniadakis and co-authors.

How does the PINN loss function work?

Write the PDE as a residual that should be zero everywhere. For the 1D heat equation with thermal diffusivity ,

The network has weights and biases . Substituting the network for gives a residual that is also a function of . Training minimises a sum of mean squares:

The four terms are the PDE residual at collocation points scattered through the domain, the initial condition at points on , the boundary condition at points on the edges, and an optional data term at measurement points. Raissi's original formulation has only two terms, for the conditions and data and for the residual; splitting them as above makes it easier to see which part is lagging during training.

PINN schematic: inputs x and t enter a two-hidden-layer tanh network with 1,185 parameters that outputs u; automatic differentiation on the same graph gives the heat-equation residual at 2,000 collocation points; the loss sums the residual, initial and boundary terms plus an optional data term, and its gradient updates the weights.
How the PDE enters a neural network: through the loss. The same computational graph that produces also produces and by automatic differentiation.

Two things are worth noticing. The residual term needs no answers: it only asks whether the network's own derivatives satisfy the equation, so you can place as many collocation points as you like at zero cost in data. And the conditions are enforced softly, as penalties, so at the end of training the boundary condition is satisfied to within some small error rather than exactly. Hard-constraint variants exist (DeepXDE calls them hPINN) that build the boundary condition into the output expression instead.

Where does automatic differentiation come in?

Automatic differentiation (AD) is the exact, mechanical application of the chain rule to a computer program. A neural network is a chain of matrix products and activation functions, so a deep-learning framework can differentiate its output with respect to its inputs as easily as with respect to its weights. That is what makes and available at every collocation point without a finite-difference stencil or a mesh. Raissi's reference code uses TensorFlow's tf.gradients for this; in PyTorch the equivalent is torch.autograd.grad with create_graph=True so that the derivative itself can be differentiated again:

u    = net(torch.cat([x, t], dim=1))           # x, t have requires_grad=True
u_t  = torch.autograd.grad(u,   t, torch.ones_like(u),   create_graph=True)[0]
u_x  = torch.autograd.grad(u,   x, torch.ones_like(u),   create_graph=True)[0]
u_xx = torch.autograd.grad(u_x, x, torch.ones_like(u_x), create_graph=True)[0]
residual = u_t - alpha * u_xx
loss = residual.pow(2).mean() + ic_loss + bc_loss   # then loss.backward()

Our numpy script does the same job in two passes you can read line by line. It carries , , and forward through each layer with the tangent rules for a dense layer and a tanh activation, and it carries the gradient of the loss backwards to the 1,185 parameters with a small tape, which is what a framework's autograd does internally. Both passes are checked against finite differences before training starts. If you want to see the reverse pass on a tiny network by hand, our backpropagation calculator steps through it.

For a dense layer followed by , the forward rules are , and ; at the first layer is the row of that multiplies . Nothing more is needed for a second-order PDE in one space dimension.

How is a PINN different from a surrogate model and from FEA or CFD?

A PINN solves one problem by satisfying its equations, a surrogate model learns a pattern from many solved problems, and FEA or CFD solves the equations on a mesh with decades of verification behind it. They are different tools, and a PINN is often slower than the solver on a single forward problem.

PINNData-driven surrogateFEA / CFD solver
What it needsThe governing equation, conditions, optionally sparse dataTens to thousands of solved cases (Ansys says SimAI typically needs 30-100 results; see our SimAI explainer)Geometry, mesh, material, loads, solver settings
Where physics livesIn the loss, as a soft penaltyOnly in the training dataIn discretised equations, satisfied per element or cell
MeshNone; random collocation pointsNone at prediction time; training cases were meshedRequired, with a mesh-independence study
DerivativesAutomatic differentiation, exact for the networkNot available unless trained forFrom shape functions or finite volumes, with discretisation error
Inverse problemsNatural: unknown coefficients become trainable parametersNeeds a separate optimisation loopNeeds an outer optimiser calling the solver repeatedly
Error controlNo a priori error bound; check against a solver or exact caseOnly inside the training range (see our surrogate guide)Convergence theory, mesh refinement, residual monitoring
Typical cost, one forward caseMinutes to hours of trainingSeconds, after a training investmentSeconds to days, depending on size

The Raissi preprints call PINNs "physics-informed surrogate models", so the word surrogate is used for both. The difference that matters is the source of truth: a data-driven surrogate can only be as right as the simulations it saw, while a PINN can be wrong by converging to a poor minimum but is answerable to the equation at every collocation point.

Worked example: a PINN for 1D transient heat conduction

We chose a problem with a known exact solution so that the error can be measured honestly. Everything below comes from pinn_heat.py in our run folder, which uses only numpy and scipy, and from the figures it saved.

The problem

A dimensionless rod occupies . Its ends are held at zero, it starts with a half-sine temperature profile, and heat diffuses with diffusivity for one unit of time (so is the Fourier number scaled by ):

Separation of variables gives the exact solution

You can check it in one line: and , so . At the peak has decayed to . If you want to see the same physics solved by finite differences on a grid, our 2D heat conduction solver does that interactively.

The setup

ItemValue in our run
NetworkInputs , two hidden layers of 32 tanh units, one linear output: 1,185 parameters, Glorot-normal initialisation
Collocation points2,000, uniform random in
Condition points100 on , 100 on each end and
Loss weightsAll 1 (no tuning)
OptimiserAdam, learning rate 0.003, 3,000 steps, then L-BFGS, 3,000 iterations (the Adam-then-L-BFGS sequence Raissi's code uses)
Error measureRelative L2 norm of on a 101 × 101 grid

What training looked like

Adam took the total loss from 0.45 at the first step to 1.07 × 10⁻³ at step 1,000 and 9.48 × 10⁻⁵ at step 3,000. L-BFGS, which uses curvature information and suits the smooth PINN loss, then drove it to 3.61 × 10⁻⁸ in 3,000 more iterations. The PDE residual term stayed the largest of the three throughout, which is typical: the conditions are easy to fit, the equation is where the work is.

Training loss on a log scale against optimiser iteration: the total loss falls from about 0.5 to 3.6e-8 over 3,000 Adam steps and 3,000 L-BFGS iterations, with the PDE residual term the largest of the three components and the final relative L2 error 0.004 percent.
Training history of the forward PINN. The vertical line marks the switch from Adam to L-BFGS. Skill-Lync run, 30 Nov 2026.

The result

The trained network matched the exact solution with a relative L2 error of 3.84 × 10⁻⁵ (0.004%) and a maximum absolute error of 8.43 × 10⁻⁵ on a field whose peak value is 1. Training took 37 s for Adam and 38 s for L-BFGS on a laptop CPU, with no GPU and no deep-learning framework. For a single linear problem like this a finite-difference solver would be faster by orders of magnitude, which is the right expectation to carry into the rest of this guide.

Temperature profiles against x at t = 0, 0.25, 0.5 and 1: on the left the PINN markers sit on the exact curves with a relative L2 error of 0.004 percent; on the right the same network trained only on initial and boundary data matches t = 0 and the ends but keeps the t = 0 shape at every time, giving 68.3 percent error.
Left: PINN against the exact solution. Right: the same network, same condition points, PDE term switched off. Without the physics it has no reason to let the profile decay.

What happens if you drop the physics term?

This is the experiment that explains what the word physics-informed buys. We retrained the same network from the same initial weights on the same 300 initial and boundary points, with the residual term removed. It fitted those points to a loss of 3.56 × 10⁻⁸, as low as the PINN's, and was 68.3% wrong in relative L2 norm with a maximum absolute error of 0.669. The right-hand panel shows why: it reproduces the half-sine and the zero ends, then simply keeps that shape at every later time because nothing in its loss says temperature should decay. The 2,000 collocation points, which carry no temperature values at all, are what turn a curve-fitter into a solver.

Can a PINN discover an unknown parameter? The inverse problem

Yes, and this is where PINNs are most useful in practice. Make the unknown coefficient a trainable parameter alongside the weights, add a data term for the measurements, keep the residual term, and train. The residual term now contains the unknown, so its gradient pulls the coefficient towards the value that makes the data and the equation agree. Raissi's Part II preprint shows this for the Navier-Stokes equations, learning two coefficients from noisy velocity data around a cylinder at Reynolds number 100 and recovering the pressure field even though no pressure data were used.

In our run we pretended not to know . We took 40 interior temperature readings at random positions and times, added Gaussian noise with standard deviation 0.02 (2% of the peak temperature), started from a deliberately wrong guess of , and trained with the same schedule as before.

Left: the diffusivity estimate starts at 0.5, drops within the first few hundred Adam steps and converges to 0.0979 against a true value of 0.1, a 2.13 percent error. Right: the exact temperature field as a colour map with the 40 noisy measurement points marked.
Inverse PINN: the thermal diffusivity as one extra trainable parameter. Adam does the coarse work in the first few hundred evaluations; L-BFGS refines it.

The identified diffusivity was 0.0979, 2.13% below the true 0.1, and the reconstructed field was within 0.80% of the exact one in relative L2 norm. One check worth doing on any inverse run: the final data term was 4.52 × 10⁻⁴, close to the noise variance 0.02² = 4.0 × 10⁻⁴. The network stopped fitting the data at the noise floor instead of chasing it, because the physics term would not let it bend the field to pass through noisy points. The same code would work for a non-uniform conductivity or a boundary heat-transfer coefficient.

When do PINNs win?

PINNs are worth their training cost when the problem is awkward for a conventional solver or when you need the solution as a smooth, differentiable function. Four situations recur:

  • Inverse problems. Identifying a diffusivity, a damping coefficient, a source term or a boundary condition from measurements is a single training run, as above, instead of an outer optimisation loop calling a solver dozens of times.
  • Sparse or noisy data. The physics term regularises the fit, which is why our inverse run settled at the noise floor rather than overfitting 40 points. This is the "hidden physics" use that Raissi's Navier-Stokes example demonstrates by reconstructing pressure from velocity.
  • Mesh-free and geometry-light problems. Collocation points are random samples, so a complex domain needs only a function that says whether a point is inside. DeepXDE builds such domains with constructive solid geometry and point clouds instead of a mesh generator.
  • Parametric and differentiable solutions. Add a design variable (a thickness, a Reynolds number) as an input and one network covers a family of cases, with gradients with respect to that variable available for free. This is what makes PINNs attractive inside optimisation, where our topology optimization guide shows how much sensitivities matter.

When do PINNs lose?

PINNs lose to a conventional solver on most well-posed forward problems, and they can fail outright on stiff, multiscale or high-frequency ones. The failures are documented by the same community that invented the method, and knowing them saves weeks of unexplained non-convergence.

  • Training cost. Our 1D linear problem took 75 s and 6,000 optimiser iterations to reach 0.004% error; a finite-difference solve on the same grid takes milliseconds. Raissi's Burgers example used 10,000 collocation points and about 60 s on a Titan X GPU for one case. The cost does not pay back unless you reuse the network (parametric or inverse use) or have no solver for the problem.
  • Stiff and multiscale PDEs. Krishnapriyan and co-authors (NeurIPS 2021) showed that PINNs "can learn simple problems well but often fail on slightly more complex ones", including convection, reaction and diffusion problems with larger coefficients, and traced it to an ill-conditioned loss landscape rather than to the network being too small. Their remedies, curriculum training and sequence-to-sequence learning in time, cut the error by one to two orders of magnitude but add engineering.
  • Unbalanced loss terms. Wang, Teng and Perdikaris (SIAM J. Sci. Comput. 2021) showed that stiffness in the gradient flow makes the gradient of one loss term swamp the others, so the boundary condition or the residual is quietly ignored. Their learning-rate annealing, which reweights the terms from gradient statistics, improved accuracy by a reported 50-100×. Our run used unit weights and got away with it only because the problem is benign.
  • Spectral bias. Dense networks are biased towards low-frequency functions (Rahaman and co-authors, ICML 2019). Sharp fronts, boundary layers and high-mode oscillations are learned last or not at all, which is why DeepXDE ships multi-scale Fourier feature networks as a workaround.
  • No error guarantees. A low loss means the residual is small at the collocation points you sampled. It does not bound the error elsewhere, and there is no mesh-refinement theorem to lean on. Validate against an exact case or a trusted solver, as we did, before you trust a PINN on a problem without one.
  • Soft constraints. The boundary condition is satisfied to a tolerance, not exactly. For problems where a flux balance must close, that tolerance may matter.

Which PINN tools should a mechanical engineer learn?

Learn PyTorch first, then a PINN library on top of it. The two open-source libraries below are the ones that appear in papers and job descriptions; the third row is a commercial product that is often mentioned in the same breath but is not a PINN.

ToolVersion (as of 30 Nov 2026)What it gives youLicence
DeepXDE (Lu Lu, Yale; started under Karniadakis at Brown)1.15.1, released 2 Nov 2026, Python ≥ 3.9PINNs for forward and inverse ODEs/PDEs, hard-constraint hPINN, gradient-enhanced gPINN, fractional fPINN, residual-based adaptive sampling, DeepONet operator learning, CSG geometry without meshing, three AD modes; backends TensorFlow 1.x and 2.x, PyTorch, JAX and PaddlePaddle. Reference paper: SIAM Review 63(1), 2021.LGPL-2.1
NVIDIA PhysicsNeMo (formerly Modulus)2.3.0, released 21 Nov 2026, Python 3.11-3.14; PhysicsNeMo Sym 2.4.0 (9 Mar 2026) for the symbolic PINN workflowAn open-source PyTorch framework for physics ML: PINNs, Fourier neural operators and other neural operators, multi-GPU training, CFD and weather recipes. NVIDIA's product page says Ansys is integrating it into its SeaScape platform and Siemens Energy reports a 10,000× speed-up on grid asset simulation with it.Apache 2.0
Ansys SimAI2026 R1 tiers (SimAI Pro, SimAI Premium); see our SimAI guideNot a PINN. A data-driven, physics-agnostic surrogate trained on your past simulation results, typically 30-100 of them, predicting fields for new geometry.Commercial

Our numpy script exists to show the mechanism; for real work use a library, which handles the sampling, loss bookkeeping, Fourier features and multi-GPU training you would otherwise rewrite.

Where are PINNs used in India, and what should you learn?

In India, PINNs are a research and early-adoption topic rather than a production CAE tool, and the honest place to meet them is in a research group, a CAE team's methods work or a capstone project. Reviews and methods papers now come from Indian universities (for example a 2024 review with an emphasis on CFD applications from BML Munjal University, Gurugram), and the commercial route runs through the vendors Indian CAE teams already use: Ansys with SimAI and its PhysicsNeMo integration, and NVIDIA's open-source stack. We could not find a published Indian industrial case study with numbers we could verify, so we do not quote one.

What you need to learn is more conventional than the name suggests:

  1. The PDEs you want to solve. Heat conduction, linear elasticity, Navier-Stokes. If you cannot write the residual, you cannot write the loss. Our FEA guide and the CFD programme cover the equations a PINN would be asked to satisfy.
  2. Python and numpy, to the level of the script in this post. The Python for Mechanical Engineers course is built for this.
  3. The maths of training: gradients, the chain rule, Adam and L-BFGS. The maths behind ML course covers it; our machine learning for mechanical engineers guide shows what a data-driven model looks like before you add physics.
  4. PyTorch, then DeepXDE or PhysicsNeMo. Start with the Machine Learning Fundamentals course, then reproduce the heat equation above in DeepXDE in under 50 lines.
  5. A validation habit. Every PINN result you present should sit next to an exact solution or a converged solver result, exactly as the figures here do.

A good second exercise is the damped mass-spring-damper system. Train a PINN on with the analytical solution from our mass-spring-damper calculator as the reference, then hide and recover it from a noisy displacement trace. It is the vibration engineer's version of the inverse run above.

Frequently asked questions

Is a PINN more accurate than FEA?

Usually not, for a well-posed forward problem. Our PINN reached 0.004% error on a linear heat problem, but a finite-difference solver gets there in milliseconds with a convergence theory behind it. PINNs earn their place on inverse problems, sparse noisy data and parametric families, where a solver has to be wrapped in an optimisation loop.

Do PINNs need training data?

Not for a forward problem. Our forward run used only the equation, 100 initial-condition points and 200 boundary points; the 2,000 collocation points carry no temperature values. Data enter when you have measurements to assimilate or an unknown parameter to identify, and then even 40 noisy points were enough to recover the diffusivity to 2%.

Why does my PINN loss go down but the solution is wrong?

Three usual causes: one loss term is dominating the gradient (rebalance the weights or use learning-rate annealing), the problem is stiff or has sharp fronts the network cannot represent yet (try curriculum training in time or Fourier features), or your collocation points are too few where the solution changes fastest (use residual-based adaptive sampling). Always compare with a reference case before trusting the loss value.

Which is better for a beginner, DeepXDE or PhysicsNeMo?

DeepXDE, for a first PINN. It is a small library with a clear API, five backends and worked examples for forward and inverse problems. PhysicsNeMo is a larger PyTorch framework aimed at multi-GPU training, neural operators and industrial CFD recipes; move to it when the problem outgrows a laptop.

Can a PINN replace a CFD or FEA engineer?

No. Writing the residual, choosing the conditions, judging the collocation density and validating the result are simulation-engineering skills. What PINNs change is the question an engineer can ask: not only "what is the field for these inputs" but "what properties explain these measurements".

Sources and further reading

Want this on your résumé?

Talk to a counsellor.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.