Save and load a solution

Use this when a solution should outlive the session: to plot it tomorrow, to send it to somebody, or to open it in another tool.

Steps

  1. Write the solution to a file: solution.save(path). It returns the path of the file, which ends in .npz.

  2. Read it back with pm.load(path).

  3. Use what comes back as a solution: index it, call it for values, plot it, read its plan and its diagnostics.

Example

import tempfile
from pathlib import Path

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

x, y = sp.symbols("x y", real=True)
u = sp.Function("u")(x, y)
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))
solution = pm.solve(membrane)

folder = Path(tempfile.mkdtemp())
written = solution.save(folder / "membrane")
assert written.name == "membrane.npz"

kept = pm.load(written)
kept.plot()

assert (kept[u] == solution[u]).all()
assert kept(0.5, 0.5) == solution(0.5, 0.5)
assert kept.plan.to_json() == solution.plan.to_json()
assert kept.diagnostics == solution.diagnostics

# The file is a numpy archive, with the unknown u under "field/u".
with np.load(written) as archive:
    assert (archive["field/u"] == solution[u]).all()
The figure that the example above draws. The figure that the example above draws.

Notes

  • The file holds the values, the recorded times, the plan and the diagnostics. Loading it executes nothing, so 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 is a SavedProblem, and cannot be solved again. For that, keep the script, and the plan if you changed it: see Reuse a plan.

  • The values of data fields are not in the file.

  • 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.

  • Solutions explains what a solution holds, and the reference describes pm.load.