Get the arrays and the grid¶
Use this when you want to work on a solution with numpy: find its largest value, take differences, or hand it to a tool of your own.
Steps¶
Index the solution with the unknown for its values:
solution[u], a numpy array with one axis for each coordinate.Take the points of the grid along each axis from
solution.axes. The valuevalues[i, j]belongs to the point(xs[i], ys[j]).Where a formula needs the coordinates of every point, take
solution.mesh(): one array for each coordinate, in the shape of the values.
Example¶
Two charges of opposite sign in the plane:
import numpy as np
import sympy as sp
import pdemagic as pm
x, y = sp.symbols("x y", real=True)
phi = sp.Function("phi")(x, y)
charges = sp.exp(-((x - 1) ** 2 + y**2)) - sp.exp(-((x + 1) ** 2 + y**2))
solution = pm.solve(
pm.Problem(sp.Eq(pm.laplacian(phi), -charges), domain=pm.FreeSpace(x, y))
)
values = solution[phi]
xs, ys = solution.axes
X, Y = solution.mesh()
assert values.shape == (len(xs), len(ys)) == X.shape == Y.shape
assert X[5, 7] == xs[5] and Y[5, 7] == ys[7]
# Where the potential is highest: beside the positive charge at (1, 0).
i, j = np.unravel_index(values.argmax(), values.shape)
assert abs(xs[i] - 1) < 1 and abs(ys[j]) < 0.2
# The values on the half plane x > 0, by a mask.
assert (values[X > 0] > 0).all()
# The field, by differences on the grid.
field_x, field_y = np.gradient(-values, xs, ys)
assert field_x.shape == values.shape
Notes¶
solution["phi"]takes the name in place of the unknown, andsolution.unknownslists the names.For a problem in time the first axis of the values is the time, and
solution.timesholds the recorded times. For an eigenproblem the first axis counts the states, andsolution.eigenvaluesholds the eigenvalues.The points are equally spaced where a direction is free or periodic. Along a periodic direction they stop one step short of the upper end. Between walls they are Chebyshev points, which crowd towards the walls, and in a disk or a ball they are Gauss points along the radius, which do not include the surface.
On a shape in the plane the grid lies over the rectangle that holds the shape, and the points outside the shape hold
nan. Usenp.isfinite(values)as a mask.pdemagic does not give the gradient of a solution yet.
np.gradientis of second order, so the field is less accurate than the potential.For values between the points, see Evaluate a solution at a point. For other tools, see Save and load a solution.
Solutions explains all of it, and the reference lists the attributes.