Solutions

pm.solve returns a solution: the values of every unknown on a grid, with the plan that produced them and the diagnostics of the solve. This page says how to get at the values, on the grid and between its points, and how a solution is kept in a file.

import tempfile
from pathlib import Path

import numpy as np
import sympy as sp
import pdemagic as pm
from pdemagic import curves

x, y, t = sp.symbols("x y t", real=True)
u = sp.Function("u")(x, y)

Arrays and the grid they live on

Index a solution with an unknown for its values, a numpy array with one axis for each coordinate. solution.axes holds the points of the grid along each axis, and solution.mesh() the coordinates of every point, as arrays of the shape of the values. A membrane under an even load:

box = pm.Box({x: (0, 1), y: (0, 1)})
membrane = pm.Problem(sp.Eq(-pm.laplacian(u), 1), domain=box, boundary=sp.Eq(u, 0))
sagging = pm.solve(membrane)

values = sagging[u]
xs, ys = sagging.axes
X, Y = sagging.mesh()
assert values.shape == (len(xs), len(ys)) == X.shape
assert sagging.unknowns == ("u",)
assert (sagging["u"] == values).all()

The grid is the one that the method solved on, so it depends on the domain:

  • Free directions. A uniform grid over a box that the planner chose, which includes both ends.

  • Periodic directions. The points start at the lower end of the period and stop one step short of the upper end, which is the same point.

  • Between walls. Chebyshev points, which include both walls and crowd towards them.

  • Disks and balls. Gauss points along the radius, which lie inside, and equally spaced points around the axis. The rim is not a point of the grid.

  • Cylinders. With vacuum outside, the centres of the cells. With boundary conditions, a grid whose points along the axis include the two caps.

  • Shapes in the plane. A uniform grid over the rectangle that holds the shape. A point outside the shape holds no number: nan.

assert xs[0] == 0.0 and xs[-1] == 1.0
assert xs[1] - xs[0] < xs[len(xs) // 2] - xs[len(xs) // 2 - 1]

On a shape, use the functions of numpy that skip nan, such as np.nanmax, or the mask np.isfinite(values):

shield = curves.Circle((0, 0), 1, name="shield")
core = curves.Circle((0, 0), 0.5, name="core")
cable = pm.Problem(
    sp.Eq(pm.laplacian(u), 0),
    domain=pm.Region(x, y, shield, core),
    boundary={shield: sp.Eq(u, 0), core: sp.Eq(u, 1)},
)
between = pm.solve(cable)

assert between[u].shape == (129, 129)
assert np.isnan(between[u][0, 0])  # a corner of the rectangle
assert np.isnan(between[u][64, 64])  # the centre, inside the core
assert np.nanmax(between[u]) <= 1.0 + 1e-12

There the grid does not affect the accuracy. It is an entry of the plan, plan.grid.shape: ask for more points or fewer.

Values at any point

Call the solution with coordinates for its value anywhere in the domain, also between the points of the grid. The value is not interpolated from the neighbours of the point. It comes from the sum of waves or polynomials that the method solved with, and is as accurate as the values on the grid:

middle = sagging(0.5, 0.5)
along_a_line = sagging(np.linspace(0, 1, 7), 0.25)
assert along_a_line.shape == (7,)
assert np.isnan(sagging(1.5, 0.5))  # outside the box

assert abs(between(1.0, 0.0)) < 1e-10  # on the shield
assert abs(between(0.0, 0.75) - np.log(0.75) / np.log(0.5)) < 1e-10

Arrays work as numbers do, and are broadcast against each other. A point outside the domain gives nan, and on a periodic domain a point outside the period is taken into it.

This works on domains that are periodic in every direction, on boxes, on disks, rings and cylinders with boundary conditions, in their own coordinates, and on shapes in the plane. Along a direction that is free it does not yet, because the grid is a cut out of all of space there, and in a ball it does not either.

solution.integral() is the integral of an unknown over the domain, by the weights of the same points. On a disk that is the integral over its area, and in a ball and a cylinder over the volume: the coordinates of the domain bring their own measure.

assert abs(sagging.integral() - 0.0351442537) < 1e-9

Several times

For a problem in time the first axis of the values is the time, and solution.times holds the recorded times. A call and an integral return one value for each of them:

T = sp.Function("T")(x, t)
rod = pm.Problem(
    sp.Eq(T.diff(t), T.diff(x, 2)),
    domain=pm.Box({x: (0, 1)}),
    time=(t, 0, 0.2),
    initial={T: sp.sin(sp.pi * x)},
    boundary=sp.Eq(T, 0),
)
cooling = pm.solve(rod)

assert cooling[T].shape == (len(cooling.times), len(cooling.axes[0]))
assert cooling(0.5).shape == cooling.times.shape
assert abs(cooling(0.5)[-1] - np.exp(-0.2 * np.pi**2)) < 1e-11

A stationary solution has times of None.

Several unknowns, and eigenvalues

A solution of a system holds every unknown: solution.unknowns names them, and solution[E] picks one. Where one unknown is meant, it is named: solution.plot(E), solution.integral(E), solution(0, 0, unknown=E). A plot without a name draws the first unknown. A call and an integral without one are refused.

A solution of an eigenproblem has solution.eigenvalues, from the lowest. The first axis of the values counts the eigenfunctions, as it counts the times of a problem in time.

Every solution carries solution.plan, the plan that produced it, and solution.diagnostics, which the page on accuracy explains. With bodies it has solution.bodies as well.

Saving and loading

A solution is written to a file with save, and read back with pm.load:

folder = Path(tempfile.mkdtemp())
written = cooling.save(folder / "rod")
assert written.name == "rod.npz"

kept = pm.load(written)
assert (kept[T] == cooling[T]).all()
assert kept.plan.to_json() == cooling.plan.to_json()
assert kept.diagnostics == cooling.diagnostics
assert kept(0.5)[-1] == cooling(0.5)[-1]

The file holds the values, the recorded times, the plan and the diagnostics, so the solution that comes back is indexed, plotted and called for values as the one that was saved. It is a numpy archive that numpy.load opens too, with the unknown T under "field/T", and loading it executes nothing: a file from somebody else is safe to open.

Of the problem the file keeps the domain and what the solver read, not the sympy expressions. kept.problem says so, and cannot be solved again: for that, keep the script.

assert repr(kept.problem) == "SavedProblem(domain=Box, time=(t, 0.0, 0.2))"

For other tools there are two more ways out. solution.to_xarray() returns an xarray.Dataset, with the unknowns over the coordinates by their names. It needs xarray, an optional dependency: pip install "pdemagic[xarray]". solution.to_vtk(path) writes VTK files, which ParaView opens: one file for a stationary solution, and for a solution in time one file for each recorded time with one more, ending in .pvd, that lists them.

dataset = cooling.to_xarray()
assert dataset["T"].dims == ("t", "x")

listed = cooling.to_vtk(folder / "rod")
assert listed.name == "rod.pvd"

See also