"""
The FDTD operator: a CSX model and the FDTD settings lowered onto the
rectilinear Yee grid, as openEMS does it.
The fields are kept as edge voltages and currents (V = E dl on the primary
edges, I = H dl' on the dual edges), so the update needs no geometry at run
time:
I -= iv * (loop sum of V around the primary face)
iv = dt l' / (mu A)
V = vv * V + vi * (loop sum of I around the dual face)
vv, vi from the edge's C = eps A' / l, G = kappa A' / l
Arrays are (3, Nx, Ny, Nz): component, then the node (i, j, k). E_x[i, j, k] is
the edge from line i to i+1 at y_j, z_k; H_x[i, j, k] sits at x_i, y_j+1/2,
z_k+1/2. Indices past the last edge hold zero coefficients.
op = build(csx, fdtd) # fdtd: dict(bc=[6], f0, fc, nr_ts, end_crit,
# oversampling)
Materials are sampled at cell centres (highest priority wins) and averaged over
the four quarter cells around each edge. Metals take the edges whose midpoint is
in a primitive; flat primitives snap to the nearest mesh line. Metal is PEC; a
ConductingSheet on a flat primitive is openEMS's conducting-sheet model
(gfdtd.sheet: a conductance and two R-L branches per edge, fitted to the sheet's
skin-effect impedance up to f0 + fc), PEC on other primitives and next to the
boundaries, as openEMS's. A rough sheet (roughness > 0, gfdtd's) takes a
wideband fit of its rough impedance instead: more R-L branches. Lumped elements
spread their R / L / C over the edges in their box (parallel, or series RLC on
each edge), with metal caps; soft E excitations add exc_val x signal to their
edges.
Debye materials: each pole is a polarisation current i on the edges, tau di/dt +
i = C_p dV/dt (C_p = eps0 eps_delta A' / l), integrated with the trapezoidal
rule at the E update's time, which folds part of it into vv and vi:
unconditionally stable, for any tau. A conducting sheet's R-L branches are poles
too, L di/dt + R i = V, integrated the same way: i' = ka i + kb (V' - sg V), sg
1 for Debye, -1 for R-L. PML_n: the n outermost cells of a side are a
convolutional PML (CPML, kappa 1, no alpha) with a cubic conductivity grading,
ending in PEC. Dumps: DumpBox regions at the cell centres (openEMS's dump mode
2), worked out by the engine.
"""
import copy, hashlib, json, os, threading
from collections import defaultdict
import numpy as np
from . import csx as C
from .constants import EPS0, MU0, C0
# time step: this fraction of the stability limit (C0, the shortest neighbouring
# cells)
SAFETY = 0.95
PML_GRADING = 3 # PML conductivity ~ depth^m
# PML: the reflection of a normal wave through it and back, in theory
PML_R0 = 1e-6
[docs]
class Operator:
"""What the engine needs: the grid (m), dt, the coefficient arrays and the
sparse extensions."""
def __init__(self):
self.notes = []
def _snap(lines, v):
return float(lines[int(np.argmin(np.abs(lines - v)))])
def _flat(shape, a, i, j, k):
return ((a * shape[0] + i) * shape[1] + j) * shape[2] + k
[docs]
class Grid:
"""Lines (drawing units and metres), primary / dual lengths, and the points
the tests run on."""
def __init__(self, g):
self.lines = [np.asarray(g.lines[a], float) for a in range(3)]
for a in range(3):
if len(self.lines[a]) < 2:
raise ValueError(
f"gfdtd: the grid needs at least two {C.AXES[a]} lines")
self.unit = g.delta_unit
self.m = [l * self.unit for l in self.lines]
self.d = [np.diff(l) for l in self.m]
# at the nodes: half cells at the ends
self.dual = [np.r_[d / 2, 0] + np.r_[0, d / 2] for d in self.d]
self.shape = tuple(len(l) for l in self.lines)
# cell centres, drawing units
self.mid = [0.5 * (l[1:] + l[:-1]) for l in self.lines]
self.tol = [1e-6 * max(np.min(np.diff(l)), 1e-12) for l in self.lines]
# ---- primitives: which points of a tensor grid are inside -------------------
def _range_mask(coord, lo, hi, tol):
return (coord >= lo - tol) & (coord <= hi + tol)
[docs]
def inside(q, pts, grid, flat_snap=True):
"""Boolean mask (len X, len Y, len Z) of the tensor-grid points pts = [X, Y,
Z] inside primitive q (boundary included). Flat primitives sit on their
nearest mesh line (flat_snap)."""
import shapely
shape = tuple(len(x) for x in pts)
if (getattr(q, 'transform', None) is not None and q.HasTransform()
or isinstance(q, C.RotPoly)):
return _inside_transformed(q, pts, grid)
if isinstance(q, C.Polygon): # Polygon / LinPoly, normal n
n = q.norm_dir
u, v = (n + 1) % 3, (n + 2) % 3 # CSXCAD's X1, X2 (cyclic)
if isinstance(q, C.LinPoly) and abs(q.length) > 0:
lo, hi = sorted((q.elevation, q.elevation + q.length))
else:
lo = hi = (_snap(grid.lines[n], q.elevation)
if flat_snap else q.elevation)
mn = _range_mask(pts[n], lo, hi, grid.tol[n])
poly = shapely.Polygon(np.asarray(q.points).T)
poly = poly if poly.is_valid else poly.buffer(0)
x0, y0, x1, y1 = poly.bounds
mu = _range_mask(pts[u], x0, x1, grid.tol[u])
mv = _range_mask(pts[v], y0, y1, grid.tol[v])
out = np.zeros(shape, bool)
if not (mn.any() and mu.any() and mv.any()):
return out
iu, iv = np.nonzero(mu)[0], np.nonzero(mv)[0]
U, V = np.meshgrid(pts[u][iu], pts[v][iv], indexing='ij')
inp = shapely.intersects_xy(poly, U.ravel(), V.ravel()).reshape(U.shape)
plane = np.zeros((shape[u], shape[v]), bool)
plane[np.ix_(iu, iv)] = inp
if u > v: # (the plane's axes in their order in the grid)
plane = plane.T
return (np.broadcast_to(np.expand_dims(plane, n), shape)
& mn.reshape([-1 if b == n else 1 for b in range(3)]))
if isinstance(q, C.Box):
m = []
for a in range(3):
lo, hi = sorted((q.start[a], q.stop[a]))
if hi - lo < grid.tol[a] and flat_snap:
lo = hi = _snap(grid.lines[a], lo)
m.append(_range_mask(pts[a], lo, hi, grid.tol[a]))
return m[0][:, None, None] & m[1][None, :, None] & m[2][None, None, :]
if isinstance(q, C.Curve):
# a wire: on the edges of its path (find_path)
return np.zeros(shape, bool)
if isinstance(q, C.Cylinder):
p0, p1 = np.asarray(q.start), np.asarray(q.stop)
ax = p1 - p0
L2 = float(ax @ ax)
rout = (
q.radius +
(q.shell_width / 2 if isinstance(q, C.CylindricalShell) else 0.0))
lo, hi = np.minimum(p0, p1) - rout, np.maximum(p0, p1) + rout
m = [_range_mask(pts[a], lo[a], hi[a], grid.tol[a]) for a in range(3)]
out = np.zeros(shape, bool)
idx = [np.nonzero(x)[0] for x in m]
if not all(len(i) for i in idx) or L2 == 0:
return out
P = (np.stack(
np.meshgrid(*[pts[a][idx[a]]
for a in range(3)], indexing='ij'), -1) - p0)
t = (P @ ax) / L2
r2 = ((P - t[..., None] * ax) ** 2).sum(-1)
tol = max(grid.tol) * 10
if isinstance(q, C.CylindricalShell):
sub = ((t >= -1e-9) & (t <= 1 + 1e-9) &
(np.abs(np.sqrt(r2) - q.radius) <= q.shell_width / 2 + tol))
else:
sub = (t >= -1e-9) & (t <= 1 + 1e-9) & (r2 <= (q.radius + tol) ** 2)
out[np.ix_(*idx)] = sub
return out
if isinstance(q, C.Sphere):
c = np.asarray(q.center, float)
rout = q.radius + (q.shell_width / 2
if isinstance(q, C.SphericalShell) else 0.0)
m = [_range_mask(pts[a], c[a] - rout, c[a] + rout, grid.tol[a])
for a in range(3)]
out = np.zeros(shape, bool)
idx = [np.nonzero(x)[0] for x in m]
if not all(len(i) for i in idx):
return out
P = np.stack(np.meshgrid(*[pts[a][idx[a]] for a in range(3)],
indexing='ij'), -1) - c
r = np.sqrt((P ** 2).sum(-1))
tol = max(grid.tol) * 10
sub = (np.abs(r - q.radius) <= q.shell_width / 2 + tol
if isinstance(q, C.SphericalShell) else r <= q.radius + tol)
out[np.ix_(*idx)] = sub
return out
raise ValueError(f"gfdtd: primitive {type(q).__name__} not supported")
def _local_bounds(q):
"""(lo, hi): primitive q's box in its own coordinates."""
if isinstance(q, C.RotPoly):
n, ra = q.norm_dir, q.rot_axis
P = np.zeros((3, q.points.shape[1]))
P[(n + 1) % 3], P[(n + 2) % 3] = q.points[0], q.points[1]
rp = 3 - n - ra
R = float(np.abs(P[rp]).max())
lo, hi = np.full(3, -R), np.full(3, R)
lo[ra], hi[ra] = P[ra].min(), P[ra].max()
return lo, hi
if isinstance(q, C.Box):
return np.minimum(q.start, q.stop), np.maximum(q.start, q.stop)
if isinstance(q, C.Sphere):
r = q.radius + (q.shell_width / 2
if isinstance(q, C.SphericalShell) else 0.0)
return np.asarray(q.center) - r, np.asarray(q.center) + r
if isinstance(q, C.Cylinder):
r = q.radius + (q.shell_width / 2
if isinstance(q, C.CylindricalShell) else 0.0)
p0, p1 = np.asarray(q.start), np.asarray(q.stop)
return np.minimum(p0, p1) - r, np.maximum(p0, p1) + r
if isinstance(q, C.Polygon):
n = q.norm_dir
u, v = (n + 1) % 3, (n + 2) % 3 # CSXCAD's X1, X2 (cyclic)
lo, hi = np.zeros(3), np.zeros(3)
lo[u], hi[u] = q.points[0].min(), q.points[0].max()
lo[v], hi[v] = q.points[1].min(), q.points[1].max()
h = q.length if isinstance(q, C.LinPoly) else 0.0
lo[n], hi[n] = sorted((q.elevation, q.elevation + h))
return lo, hi
raise ValueError(f"gfdtd: a transformed {type(q).__name__} is not "
"supported")
def _inside_local(q, P, tol, flat_tol=None):
"""Whether the points P (N x 3, q's own coordinates) are inside q; along a
flat primitive's zero thickness flat_tol (a fraction of a cell) instead of
tol."""
import shapely
flat_tol = tol if flat_tol is None else flat_tol
if isinstance(q, C.RotPoly):
return _inside_rotpoly(q, P, tol)
if isinstance(q, C.Box):
lo, hi = _local_bounds(q)
t = np.where(hi - lo < 1e-12, flat_tol, tol)
return ((P >= lo - t) & (P <= hi + t)).all(1)
if isinstance(q, C.Sphere):
r = np.linalg.norm(P - np.asarray(q.center), axis=1)
if isinstance(q, C.SphericalShell):
return np.abs(r - q.radius) <= q.shell_width / 2 + tol
return r <= q.radius + tol
if isinstance(q, C.Cylinder):
p0, p1 = np.asarray(q.start), np.asarray(q.stop)
ax = p1 - p0
t = ((P - p0) @ ax) / float(ax @ ax)
r = np.linalg.norm(P - p0 - t[:, None] * ax, axis=1)
ok = (t >= -1e-9) & (t <= 1 + 1e-9)
if isinstance(q, C.CylindricalShell):
return ok & (np.abs(r - q.radius) <= q.shell_width / 2 + tol)
return ok & (r <= q.radius + tol)
if isinstance(q, C.Polygon):
n = q.norm_dir
u, v = (n + 1) % 3, (n + 2) % 3 # CSXCAD's X1, X2 (cyclic)
lo, hi = _local_bounds(q)
poly = shapely.Polygon(np.asarray(q.points).T)
poly = poly if poly.is_valid else poly.buffer(0)
tn = flat_tol if hi[n] - lo[n] < 1e-12 else tol
within = (P[:, n] >= lo[n] - tn) & (P[:, n] <= hi[n] + tn)
out = np.zeros(len(P), bool)
if within.any():
out[within] = shapely.intersects_xy(
poly.buffer(tol), P[within, u], P[within, v])
return out
raise ValueError(f"gfdtd: a transformed {type(q).__name__} is not "
"supported")
def _inside_rotpoly(q, P, tol):
"""CSXCAD's CSPrimRotPoly::IsInside on the points P (N x 3): each point
taken to the polygon's plane at its distance from the axis (either side of
it), inside where the polygon holds it and its angle is in the range."""
import shapely
n, ra = q.norm_dir, q.rot_axis
raP, raPP = (ra + 1) % 3, (ra + 2) % 3
foot = P[:, ra]
dist = np.hypot(P[:, raP], P[:, raPP])
alpha = np.arctan2(P[:, raPP], P[:, raP])
if raP == n:
alpha = alpha - np.pi / 2
alpha = np.where(alpha < 0, alpha + 2 * np.pi, alpha)
a0, a1 = q.angle
poly = shapely.Polygon(np.asarray(q.points).T)
poly = (poly if poly.is_valid else poly.buffer(0)).buffer(tol)
def held(d):
o = np.empty((len(P), 3))
o[:] = d[:, None]
o[:, n] = 0.0
o[:, ra] = foot
return shapely.intersects_xy(poly, o[:, (n + 1) % 3], o[:, (n + 2) % 3])
al = np.where(alpha < a0, alpha + 2 * np.pi, alpha)
first = held(dist) & (al < a1 + 1e-12)
al2 = alpha + np.pi
al2 = np.where(al2 > 2 * np.pi, al2 - 2 * np.pi, al2)
al2 = np.where(al2 < a0, al2 + 2 * np.pi, al2)
second = (al2 <= a1 + 1e-12) & held(-dist)
return first | second
def _inside_transformed(q, pts, grid):
"""inside() of a primitive with a transform (CSXCAD's AddTransform): the
grid points in the box its own box maps to, mapped back to its
coordinates and tested there (CSXCAD's IsInside: InvertTransform)."""
shape = tuple(len(x) for x in pts)
out = np.zeros(shape, bool)
lo, hi = _local_bounds(q)
corners = np.array([[lo[0] if i & 1 == 0 else hi[0],
lo[1] if i & 2 == 0 else hi[1],
lo[2] if i & 4 == 0 else hi[2], 1.0]
for i in range(8)])
M = (q.transform.matrix if getattr(q, 'transform', None) is not None
and q.HasTransform() else np.eye(4))
world = (corners @ M.T)[:, :3]
wlo, whi = world.min(0), world.max(0)
idx = [np.nonzero(_range_mask(pts[a], wlo[a], whi[a], grid.tol[a]))[0]
for a in range(3)]
if not all(len(i) for i in idx):
return out
G = np.stack(np.meshgrid(*[pts[a][idx[a]] for a in range(3)],
indexing='ij'), -1).reshape(-1, 3)
Minv = np.linalg.inv(M)
L = G @ Minv[:3, :3].T + Minv[:3, 3]
# a flat primitive takes the points within half the finest cell of it (as
# a thickness, in its own coordinates): a tilted sheet meets few nodes
cell = min(float(np.diff(pts[a]).min()) if len(pts[a]) > 1 else 1.0
for a in range(3))
scale = float(np.abs(np.linalg.det(Minv[:3, :3]))) ** (1 / 3)
tol = max(grid.tol) * 10
sub = _inside_local(q, L, tol, max(tol, 0.5 * cell * scale)).reshape(
[len(i) for i in idx])
out[np.ix_(*idx)] = sub
return out
def _snap_primary(lines, c):
"""openEMS's SnapToMeshLine on the primary mesh: the nearest line (a tie
goes to the lower one)."""
dual = 0.5 * (lines[1:] + lines[:-1])
return int(min(np.searchsorted(dual, c, 'left'), len(lines) - 1))
def _foot(P, a, b):
"""openEMS's Point_Line_Distance: the foot of P on the line a -> b (0 at a,
1 at b) and its distance."""
d = b - a
L2 = float(d @ d)
t = float((P - a) @ d) / L2 if L2 > 0 else 0.0
return t, float(np.linalg.norm(P - (a + t * d)))
[docs]
def find_path(grid, p1, p2):
"""[(axis, (i, j, k))] of the mesh edges along the segment p1 -> p2 (drawing
units), as openEMS's FindPath: from the line crossing nearest p1, each step
to the neighbouring node closest to the segment and further along it."""
L = grid.lines
p1, p2 = np.asarray(p1, float), np.asarray(p2, float)
for a in range(3):
if ((p1[a] < L[a][0] and p2[a] < L[a][0])
or (p1[a] > L[a][-1] and p2[a] > L[a][-1])):
return []
s = [_snap_primary(L[a], p1[a]) for a in range(3)]
e = [_snap_primary(L[a], p2[a]) for a in range(3)]
node = lambda q: np.array([L[a][q[a]] for a in range(3)])
cur = list(s)
cfoot = mfoot = _foot(node(s), p1, p2)[0]
stop_foot = _foot(node(e), p1, p2)[0]
path = []
while mfoot < stop_foot:
best = None
for a in range(3):
for step in (-1, 1):
q = list(cur)
q[a] += step
if not 0 <= q[a] < len(L[a]):
continue
f, dist = _foot(node(q), p1, p2)
if f > cfoot and (best is None or dist < best[0]):
best = (dist, f, a, step)
if best is None:
break
_, mfoot, a, step = best
lo = list(cur)
if step < 0:
lo[a] -= 1
cur[a] += step
path.append((a, tuple(lo)))
cfoot = mfoot
for a in range(3): # close what is missing to the end node
if cur[a] > e[a]:
cur[a] -= 1
path.append((a, tuple(cur)))
elif cur[a] < e[a]:
path.append((a, tuple(cur)))
return path
[docs]
def curve_edges(q, grid):
"""find_path over each segment of a Curve primitive."""
return [
e for P0, P1 in zip(q.points[:-1], q.points[1:])
for e in find_path(grid, P0, P1)
]
[docs]
def edge_mask(q, a, grid):
"""inside() for the midpoints of the a-edges, on the (Nx, Ny, Nz) node array
(False past the last edge)."""
m = inside(q, [grid.mid[b] if b == a else grid.lines[b] for b in range(3)],
grid)
return np.pad(m, [(0, 1) if b == a else (0, 0) for b in range(3)])
# ---- the operator -----------------------------------------------------------
[docs]
def timestep(grid, factor=SAFETY):
"""The largest stable step for vacuum on this grid: 1 / (c sqrt(sum over
axes of the largest 1/(d_i-1 d_i))), the neighbouring primary cells around
each node (half cells at the ends count once, as 1/d^2)."""
s = 0.0
for d in grid.d:
q = 1.0 / (d * d)
if len(d) > 1:
q = np.maximum(q, np.concatenate([1.0 / (d[1:] * d[:-1]), [0]]))
s += float(q.max())
return factor / (C0 * np.sqrt(s))
def _curl_V(V):
"""The loop sum of V around each primary face (what the H update subtracts,
per unit iv)."""
Vx, Vy, Vz = V
out = np.zeros_like(V)
out[0][:, :-1, :-1] = (Vz[:, 1:, :-1] - Vz[:, :-1, :-1] - Vy[:, :-1, 1:]
+ Vy[:, :-1, :-1])
out[1][:-1, :, :-1] = (Vx[:-1, :, 1:] - Vx[:-1, :, :-1] - Vz[1:, :, :-1]
+ Vz[:-1, :, :-1])
out[2][:-1, :-1, :] = (Vy[1:, :-1, :] - Vy[:-1, :-1, :] - Vx[:-1, 1:, :]
+ Vx[:-1, :-1, :])
return out
[docs]
def curl_I_part(I, a):
"""Component a of the loop sum of I around each dual face (the E update's c;
the numpy backend's too)."""
b, c = (a + 1) % 3, (a + 2) % 3
along = lambda x, s: tuple(s if y == x else slice(None) for y in range(3))
out = I[c] - I[b]
out[along(b, slice(1, None))] -= I[c][along(b, slice(None, -1))]
out[along(c, slice(1, None))] += I[b][along(c, slice(None, -1))]
return out
def _curl_I(I):
return np.stack([curl_I_part(I, a) for a in range(3)])
# TimeStepMethod auto: the operator's own limit from this many cells (or when it
# is cached)
AUTO_CELLS = 1_000_000
def _dt_cache():
return os.path.join((os.environ.get('XDG_CACHE_HOME')
or os.path.join(os.path.expanduser('~'), '.cache')),
'gfdtd', 'timestep.json')
def _kept_limits():
"""{model key: its exact limit (s, before the safety factor)} from earlier
runs, {} where there is none."""
try:
with open(_dt_cache(), encoding='utf-8') as fh:
return json.load(fh)
except (OSError, ValueError):
return {}
[docs]
def keep_limit(key, dt):
"""Keep a model's exact limit for its later runs (a few hundred models at
most; the oldest dropped)."""
fn = _dt_cache()
d = _kept_limits()
d.pop(key, None)
d[key] = dt
d = dict(list(d.items())[-500:])
try:
os.makedirs(os.path.dirname(fn), exist_ok=True)
tmp = fn + f'.{os.getpid()}'
with open(tmp, 'w', encoding='utf-8') as fh:
json.dump(d, fh)
os.replace(tmp, fn)
except OSError:
pass
[docs]
def exact_timestep(einv, hk, factor=SAFETY, tol=1e-2):
"""The leapfrog's own limit for these coefficients (R-D6): the largest
eigenvalue of the curl-curl operator M = E^-1 C^T K C (E^-1 = 1 / C_edge, 0
on PEC edges; K = l' / (mu A) on the dual edges) by Lanczos on its symmetric
form E^-1/2 C^T K C E^-1/2, and dt = factor x 2 / sqrt(lambda). The
materials count (a small cell in a dielectric allows a longer step), which
the vacuum Courant rule of the smallest cells does not: on the examples
1.26-1.35 times its step. Loss, lumped capacitance and the poles only lower
the edges' vi: stabler."""
from scipy.sparse.linalg import LinearOperator, eigsh
d = np.sqrt(einv).astype(np.float32)
hk = hk.astype(np.float32)
shp = einv.shape
A = LinearOperator((einv.size, einv.size), dtype=float, matvec=lambda x:
(d * _curl_I(hk * _curl_V(d * x.reshape(shp).astype(
np.float32)))).ravel().astype(np.float64))
lam = float(
eigsh(A, k=1, which='LA', tol=tol, ncv=20, return_eigenvectors=False,
maxiter=5000,
v0=np.random.default_rng(0).standard_normal(einv.size))[0])
return factor * 2.0 / np.sqrt(lam * (1 + 2 * tol))
def _hedge_average(cell, a, grid):
"""A cell quantity (N-1 each axis) along each dual a-edge (an H_a node: line
i of axis a, the cell centre in the other two): the two cells it runs
through, weighted by their half lengths along a (one at the first and last
lines); on the (Nx, Ny, Nz) node array, zero past the last cell in the other
two axes."""
b, c = [x for x in range(3) if x != a]
P = np.moveaxis(cell, (a, b, c), (0, 1, 2))
d = grid.d[a]
lo = np.concatenate([[0.0], d / 2])[:, None, None] # the cell below line i
hi = np.concatenate([d / 2, [0.0]])[:, None, None] # the cell above it
Pp = np.pad(P, ((1, 1), (0, 0), (0, 0)), mode='edge')
s = (Pp[:-1] * lo + Pp[1:] * hi) / (lo + hi)
s = np.pad(s, ((0, 0), (0, 1), (0, 1)))
return np.moveaxis(s, (0, 1, 2), (a, b, c))
def _edge_average(cell, a, grid):
"""A cell quantity (N-1 each axis) averaged over the four quarter cells
around each a-edge (weights: the quarter areas); returned on the (Nx, Ny,
Nz) node array, zero past the last a-edge."""
b, c = [x for x in range(3) if x != a]
P = np.moveaxis(cell, (a, b, c), (0, 1, 2))
P = np.pad(P, ((0, 0), (1, 1), (1, 1)))
db, dc = grid.d[b], grid.d[c]
lo_b, hi_b = np.concatenate([[0], db / 2]), np.concatenate([db / 2, [0]])
lo_c, hi_c = np.concatenate([[0], dc / 2]), np.concatenate([dc / 2, [0]])
s = (P[:, :-1, :-1] * lo_b[:, None] * lo_c[None, :]
+ P[:, 1:, :-1] * hi_b[:, None] * lo_c[None, :]
+ P[:, :-1, 1:] * lo_b[:, None] * hi_c[None, :]
+ P[:, 1:, 1:] * hi_b[:, None] * hi_c[None, :])
s /= (grid.dual[b][:, None] * grid.dual[c][None, :])
s = np.pad(s, ((0, 1), (0, 0), (0, 0)))
return np.moveaxis(s, (0, 1, 2), (a, b, c))
class _Axes:
"""A geometry quantity per component, each a broadcast view of shape sh made
of 1D spacings: read as an (3, Nx, Ny, Nz) array by component ([a]), at no
memory per node (R-D7: the four had been 96 B a node of the build, and three
of them kept with the core)."""
def __init__(self, parts, sh):
self.parts, self.sh = parts, tuple(sh)
def __getitem__(self, a):
if isinstance(a, tuple): # [a, i, j, k] and the like
return self[a[0]][a[1:]]
return np.broadcast_to(self.parts[a], self.sh)
def __len__(self):
return 3
def _geometry(grid):
"""Per component: edge length l, dual area A' (E) and dual length l', face
area A (H), on (Nx, Ny, Nz) (_Axes: views of the grid's spacings)."""
sh = grid.shape
lE, aE, lH, aH = ([None] * 3 for _ in range(4))
d = [np.concatenate([x, [0]]) for x in grid.d]
r = lambda v, ax: np.asarray(v, float).reshape(
[-1 if x == ax else 1 for x in range(3)])
for a in range(3):
b, c = [x for x in range(3) if x != a]
lE[a] = r(d[a], a)
aE[a] = r(grid.dual[b], b) * r(grid.dual[c], c)
lH[a] = r(grid.dual[a], a)
aH[a] = r(d[b], b) * r(d[c], c)
return tuple(_Axes(q, sh) for q in (lE, aE, lH, aH))
def _box_ranges(q, grid, a):
"""Edge index range along a and line index ranges across, of the a-edges
inside box q (midpoint rule; a box that catches no line across takes the
nearest one)."""
out = []
for b in range(3):
lo, hi = sorted((q.start[b], q.stop[b]))
coord = grid.mid[b] if b == a else grid.lines[b]
if b != a and hi - lo < grid.tol[b]:
lo = hi = _snap(grid.lines[b], lo)
idx = np.nonzero(_range_mask(coord, lo, hi, grid.tol[b]))[0]
if len(idx) == 0:
if b == a:
return None
idx = np.array([int(np.argmin(np.abs(coord - 0.5 * (lo + hi))))])
out.append((int(idx[0]), int(idx[-1])))
return out
def _clipped_weights(grid, b, i0, i1, lo, hi):
"""Share of each line i0..i1 in the width of a box [lo, hi] across axis b
(its dual cell clipped to the box; equal shares for a flat box)."""
if i0 == i1:
return np.ones(1)
L = grid.lines[b]
w = []
for i in range(i0, i1 + 1):
a0 = L[i] - (L[i] - L[i - 1]) / 2 if i > 0 else L[i]
a1 = L[i] + (L[i + 1] - L[i]) / 2 if i < len(L) - 1 else L[i]
w.append(max(min(a1, hi) - max(a0, lo), 0.0))
w = np.asarray(w)
return w / w.sum() if w.sum() > 0 else np.full(len(w), 1.0 / len(w))
def _sheet_normal(q):
"""The normal axis of a flat primitive (a Polygon, or a Box flat along one
axis), else None: openEMS models a conducting sheet on 2D primitives only
(PEC on the others)."""
if getattr(q, 'transform', None) is not None and q.HasTransform():
return None # (tilted: not a sheet along an axis; PEC, as solids)
if isinstance(q, C.Polygon) and not isinstance(q, (C.LinPoly, C.RotPoly)):
return int(q.norm_dir)
flat = ([a for a in range(3) if q.start[a] == q.stop[a]]
if isinstance(q, C.Box) else [])
return flat[0] if len(flat) == 1 else None
def _bc_size(b):
"""openEMS's boundary size (cells) of a side: 1 for Mur, n for PML_n, else
0."""
b = str(b).upper()
if b.startswith('PML'):
return int(b.split('_')[1]) if '_' in b else 8
return 1 if b == 'MUR' else 0
def _sheet_edges(sheets, sheet_of, sheet_m, grid, lE, dt, f_max, notes):
"""The conducting-sheet model (gfdtd.sheet) on the edges in sheet_m: (flat
edge indices, C, G per edge, [(edges, R, tau), ...] one per R-L branch), or
None. A sheet's square has a conductance G_sq and R-L branches (R_sq, tau):
openEMS's two (per_square), or a rough sheet's wideband fit (fit_rough). An
edge takes G = G_sq / f / w and R = R_sq f w, L = tau R, w = (edge length) /
(node width across it), f = 2 on the sheet's border (half the width
covered). Its C is openEMS's, dt^2 / 4 (16 / min(L) + sum 1 / L), in place
of the dielectric's. tau is the sheet's, so that one sheet's poles share
their relaxations exactly."""
from . import sheet as S
if not sheet_m.any():
return None
sh = sheet_m.shape[1:]
par = [] # per sheet: (G_sq, [(R_sq, tau), ...])
for p, _ in sheets:
rms = getattr(p, 'roughness', 0.0) or 0.0
fin, share, face = (getattr(p, 'finish',
()), getattr(p, 'finish_share', 1.0),
getattr(p, 'face', False))
if rms > 0 or (fin and share > 0):
par.append(
S.fit_rough(p.conductivity, p.thickness, f_max, rms,
fin if share > 0 else (), share, face))
continue
g, r1, l1, r2, l2, ok = S.per_square(p.conductivity, p.thickness, f_max)
par.append((g, [(r1, l1 / r1), (r2, l2 / r2)]))
if not ok:
notes.append(
f"conducting sheet {p.name}: {p.thickness * 1e6:g} um at "
f"{p.conductivity:g} S/m is past the model's fit at "
f"{f_max / 1e9:g} GHz (openEMS's last row used, as openEMS "
"does)"
)
nrm = np.array([n for _, n in sheets])
idx, cap, cond, branches = [], [], [], []
for a in range(3):
ijk = np.nonzero(sheet_m[a])
if not len(ijk[0]):
continue
sid = sheet_of[a][ijk]
t = 3 - a - nrm[sid] # the sheet's other in-plane axis
if np.any(nrm[sid] == a):
raise ValueError(
"gfdtd: a conducting sheet owns an edge along its normal")
width = np.choose(t, [grid.dual[b][ijk[b]] for b in range(3)])
w = lE[a][ijk] / width
f = np.ones(len(sid))
for b in range(3): # the edges across it at its node and the one before
sel = t == b
if not sel.any():
continue
here = tuple(c[sel] for c in ijk)
prev = list(here)
prev[b] = here[b] - 1
has_prev = prev[b] >= 0
prev[b] = np.maximum(prev[b], 0)
border = ~sheet_m[b][here] | ~(sheet_m[b][tuple(prev)] & has_prev)
f[np.nonzero(sel)[0][border]] = 2.0
flat = np.ravel_multi_index((np.full(len(sid), a),) + ijk, (3,) + sh)
for n in np.unique(sid): # sheet by sheet: its own branches
mine = sid == n
g, br = par[n]
fw = (f * w)[mine]
L = [r * tau * fw for r, tau in br]
idx.append(flat[mine])
cond.append(g / fw)
cap.append(dt * dt / 4 *
(16 / np.min(L, axis=0) + sum(1 / x for x in L)))
branches += [(flat[mine], r * fw, tau) for r, tau in br]
for p in {id(p): p for p, _ in sheets}.values():
rms = getattr(p, 'roughness', 0.0) or 0.0
fin, share = getattr(p, 'finish', ()), getattr(p, 'finish_share', 1.0)
extra = (([
f"{rms * 1e6:g} um RMS rough (Hammerstad)"
] if rms else []) + ([
"finished "
f"({' / '.join(f'{t * 1e6:g} um at {s:g} S/m' for s, t in fin)}) "
f"on {share:.0%} of its loss"
] if fin and share > 0 else []))
notes.append(
f"conducting sheet {p.name}: {p.conductivity:g} S/m, "
f"{p.thickness * 1e6:g} um"
+
(f", {', '.join(extra)} (a wideband fit to {2 * f_max / 1e9:g} GHz)"
if extra else f" (openEMS's model, fitted to {f_max / 1e9:g} GHz)")
)
return (np.concatenate(idx).astype(np.int64), np.concatenate(cap),
np.concatenate(cond), branches)
# {key: (op, ctx)}: the last model's core, for its other excitations (R-D4)
_CORES = {}
_CORES_LOCK = threading.Lock()
_BUILDING = threading.Lock() # held while a core or its compressed form is made
def _kept(cache, key, make):
"""make()'s result for the model `key`, kept in cache (_CORES, _COMPRESSED):
excitations started together have one make it; one model's at a time (its
arrays are large)."""
with _BUILDING:
with _CORES_LOCK:
kept = cache.get(key)
if kept is None:
kept = make()
with _CORES_LOCK:
cache.clear()
cache[key] = kept
return kept
def _digest(h, o, seen):
"""Feed what an object of the CSX holds into hash h (its class, its fields,
recursively; arrays by value)."""
if isinstance(o, (str, int, float, bool, type(None))):
h.update(repr(o).encode())
elif isinstance(o, np.ndarray):
h.update(
str(o.dtype).encode() + str(o.shape).encode()
+ np.ascontiguousarray(o).tobytes())
elif isinstance(o, (list, tuple)):
h.update(b'[')
for x in o:
_digest(h, x, seen)
h.update(b']')
elif isinstance(o, dict):
h.update(b'{')
for k in sorted(o, key=repr):
_digest(h, k, seen)
_digest(h, o[k], seen)
h.update(b'}')
elif hasattr(o, '__dict__'):
if id(o) in seen: # (a primitive's prop: its property, met before)
h.update(b'<ref>')
return
seen.add(id(o))
h.update(type(o).__name__.encode())
_digest(h, {k: v
for k, v in vars(o).items()
if not k.startswith('_')}, seen)
else:
h.update(repr(o).encode())
def _core_key(csx, fdtd):
"""What the core depends on: the grid, every property but the excitations,
probes and dumps (with their primitives), the background and the settings.
None when the structure cannot be read for it."""
try:
h = hashlib.sha256()
g = csx.GetGrid()
_digest(h, [np.asarray(x, float)
for x in g.lines] + [getattr(g, 'delta_unit', 1.0)], set())
_digest(h, getattr(csx, 'background', None), set())
props = [
p for p in csx.GetAllProperties()
if not isinstance(p, (C.Excitation, C.ProbeBox, C.DumpBox))
]
_digest(h, props, set())
_digest(
h, {
k: v
for k, v in fdtd.items()
if k not in ('nr_ts', 'end_crit', 'excite_type',
'excite_function')
}, set())
return h.hexdigest()
# (no key: built anew)
except Exception: # noqa: BLE001
return None
[docs]
def build(csx, fdtd, log=None):
"""The Operator of a ContinuousStructure (gfdtd.csx, or anything with the
same attributes) and the FDTD settings dict(bc, f0, fc, nr_ts, end_crit,
oversampling). The core (everything but the excitations, probes, dumps and
the pulse) is kept for the model's next excitation, which differs only in
those: kicad2ems runs one per port (the coupler: 0.15 s a run, and
compress's 0.2 s on the GPU)."""
key = _core_key(csx, fdtd)
def make():
core, ctx = _core(csx, fdtd)
core._core_key = key
return core, ctx
core, ctx = make() if key is None else _kept(_CORES, key, make)
op = copy.copy(core) # its arrays shared (read only), the rest its own
op.notes = list(core.notes)
props = [p for p in csx.GetAllProperties() if getattr(p, 'enabled', True)]
return _finish(op, props, fdtd, log, **ctx)
def _finish(op, props, fdtd, log, grid, sh, vv, vi, iv, lE, lH, aE, kap, dt,
ncell):
"""build's part of one excitation: its excitations, probes, dumps and the
pulse."""
# excitations: E (types 0 soft, 1 hard) on the edges, H (2 soft, 3 hard) on
# the dual edges, weighted, delayed
op.exc, op.exc_more = _excitations(props, grid, sh, vv, vi, lE, lH, dt,
op.notes)
# probes
op.probes = []
for p in props:
if isinstance(p, C.ProbeBox) and p.primitives:
pr = (_field_probe(p, p.primitives[0], grid, sh) if p.p_type
in (2, 3) else _probe(p, p.primitives[0], grid, sh))
if pr is None: # (a field probe had been dropped, nothing said)
op.notes.append(
f"probe {p.name} (type {p.p_type}): not a kind gfdtd "
"measures (voltage, current, E or H field, "
"mode-matching): left out")
elif isinstance(pr, list): # a field probe: its three components
op.probes.extend(pr)
if getattr(p, 'frequency', None):
op.notes.append(
f"probe {p.name}: a field probe in the time domain "
"only (its FD_Samples: the DFT of its file)")
else:
op.probes.append(pr)
op.dumps = [
d for p in props if isinstance(p, C.DumpBox) and p.primitives
for d in _dump(p, grid, op.notes)
]
if op.dumps: # the geometry the dumps need, kept
op.lE, op.aE, op.lH = lE, aE, lH
if any(d['field'] == 'Jc' for d in op.dumps):
op.kappa_E = np.stack(
[_edge_average(kap, a, grid) for a in range(3)])
op.vv, op.vi, op.iv = vv, vi, iv
op.cells = int(np.prod(ncell))
# excitation signal: openEMS's Gaussian pulse, or its sinus, Dirac, step or
# custom one (R-B18)
f0, fc = float(fdtd['f0']), float(fdtd['fc'])
op.f0, op.fc = f0, fc
op.excite_type = kind = int(fdtd.get('excite_type', 0) or 0)
op.signal, op.signal_h = excitation_signal(kind, f0, fc, dt,
int(fdtd.get('nr_ts', 1e9)),
fdtd.get('excite_function'))
op.delay_max = max([g['delay'] for g in op.exc_more], default=0)
op.nyquist = nyq = max(
1, int(1.0 / (2 * ((f0 + fc) if kind == 0 else max(f0, fc)) * dt)))
op.sub = max(1, nyq // int(fdtd.get('oversampling', 4) or 4))
if log:
for line in describe(op):
log(line)
return op
# steps a signal that lasts the run (sinus, step, custom) may hold
SIGNAL_MAX = 20_000_000
[docs]
def excitation_signal(kind, f0, fc, dt, nr_ts, function=None):
"""(signal at the E steps, at the H steps half a step later) of openEMS's
excitation `kind`: 0 the Gaussian pulse (f0, fc), 1 sin(2 pi f0 t), 2 a
Dirac (one step, f_max = fc), 3 a step (f_max = fc), 10 a custom function of
t (f0, f_max = fc). A pulse's signal ends with it; the others last the whole
run (nr_ts steps), so that the end criterion never stops them (as openEMS's:
a sinus runs to its last step)."""
if kind == 0:
n = int(2 * 9.0 / (2 * np.pi * fc) / dt)
t = np.arange(n + 1) * dt
g = lambda t: (np.cos(2 * np.pi * f0 * (t - 9.0 / (2 * np.pi * fc)))
* np.exp(-(2 * np.pi * fc * t / 3 - 3)**2))
return g(t), g(t + dt / 2)
if kind == 2:
return np.array([0.0, 1.0]), np.array([0.0, 1.0])
if kind not in (1, 3, 10):
raise ValueError(
f"gfdtd: excitation type {kind}: 0 (Gaussian), 1 (sinus), 2 "
"(Dirac), 3 (step), 10 (custom)"
)
if nr_ts > SIGNAL_MAX:
raise ValueError(
"gfdtd: a "
f"{('sinusoidal', 'step', 'custom')[(1, 3, 10).index(kind)]} "
"excitation lasts the run: set its number of timesteps (NrTS), at "
f"most {SIGNAL_MAX:,} (it is {nr_ts:,})"
)
t = np.arange(nr_ts + 1) * dt
if kind == 1:
return np.sin(2 * np.pi * f0 * t), np.sin(2 * np.pi * f0 * (t + dt / 2))
if kind == 3:
return np.r_[0.0, np.ones(nr_ts)], np.r_[0.0, np.ones(nr_ts)]
from .csx import evaluate_signal
if not function:
raise ValueError("gfdtd: a custom excitation without its function")
return evaluate_signal(function, t), evaluate_signal(function, t + dt / 2)
def _core(csx, fdtd):
"""build's part that every excitation of a model shares: the grid, the
materials, the metal, the sheets, the lumped parts, the update coefficients
and the boundaries. (op, what the rest of build reads)."""
grid = Grid(csx.GetGrid())
sh = grid.shape
op = Operator()
op.grid, op.shape = grid, sh
# openEMS's TimeStepFactor
op.dt = timestep(grid) * float(fdtd.get('timestep_factor', 1.0) or 1.0)
if fdtd.get('timestep'): # and its TimeStep: no longer than the limit
limit = op.dt
op.dt = min(float(fdtd['timestep']), limit)
if float(fdtd['timestep']) > limit:
op.notes.append(
f"TimeStep {fdtd['timestep']:.4g} s is past this grid's limit: "
f"{limit:.4g} s taken"
)
for k in fdtd.get('ignored', ()):
op.notes.append(f"openEMS's {k}: not used by gfdtd (ignored)")
ncell = tuple(n - 1 for n in sh)
bg = (csx.background if hasattr(csx, 'background') else dict(
Epsilon=1.0, Kappa=0.0))
eps = np.full(ncell, float(bg.get('Epsilon', 1.0)))
kap = np.full(ncell, float(bg.get('Kappa', 0.0)))
# (R-B18: openEMS's Mue and Sigma, the magnetic loss, had been dropped)
mue = np.full(ncell, float(bg.get('Mue', 1.0)))
sig = np.full(ncell, float(bg.get('Sigma', 0.0)))
prio = np.full(ncell, -np.inf)
# the Debye material of each cell (index), the ferrite of each (index)
owner = np.full(ncell, -1, np.int32)
fown = np.full(ncell, -1, np.int32)
props = [p for p in csx.GetAllProperties() if getattr(p, 'enabled', True)]
debye = [
p for p in props if isinstance(p, C.DebyeMaterial) and p.pole_list()
]
fer = [p for p in props if isinstance(p, C.FerriteMaterial)]
mats = [(q.priority, p, q) for p in props if isinstance(p, C.Material)
for q in p.primitives]
for pr, p, q in sorted(mats, key=lambda t: t[0]):
if isinstance(q, C.Polygon) and not isinstance(q, (C.LinPoly,
C.RotPoly)):
continue # flat: no cell volume
m = inside(q, grid.mid, grid) & (pr >= prio)
eps[m], kap[m], prio[m] = p.epsilon, p.kappa, pr
mue[m], sig[m] = getattr(p, 'mue', 1.0), getattr(p, 'sigma', 0.0)
owner[m] = debye.index(p) if p in debye else -1
fown[m] = next((n for n, f in enumerate(fer) if f is p), -1)
lE, aE, lH, aH = _geometry(grid)
with np.errstate(divide='ignore', invalid='ignore'):
cap, cond, epsE = (np.zeros((3,) + sh) for _ in range(3))
for a in range(3):
epsE[a] = _edge_average(eps, a, grid)
cap[a] = np.where(lE[a] > 0, EPS0 * epsE[a] * aE[a] / lE[a], 0.0)
cond[a] = np.where(lE[a] > 0,
_edge_average(kap, a, grid) * aE[a] / lE[a], 0.0)
# metals: edges whose midpoint is in a primitive, by priority. sheet_of: the
# conducting sheet (an index into sheets: (property, normal axis)) that owns
# the edge, -1 for PEC
pec = np.full((3,) + sh, -np.inf, np.float32) # (priorities: whole numbers)
sheet_of = np.full((3,) + sh, -1, np.int32)
sheets = []
for p in props:
if isinstance(p, (C.Metal, C.ConductingSheet)):
for q in p.primitives:
sid = -1
if isinstance(p, C.ConductingSheet):
nrm, why = _sheet_normal(q), None
if nrm is None:
why = f"a {type(q).__name__} is not flat"
elif not (p.conductivity > 0 and p.thickness > 0):
why = "zero conductivity or thickness"
if why:
op.notes.append(
f"conducting sheet {p.name}: {why}, modelled as PEC"
)
else:
sid = len(sheets)
sheets.append((p, nrm))
if isinstance(q, C.Curve):
for a, ijk in curve_edges(q, grid):
if ijk[a] < sh[a] - 1:
pec[(a,) + ijk] = max(pec[(a,) + ijk], q.priority)
continue
for a in range(3):
m = edge_mask(q, a, grid)
sheet_of[a][m & (q.priority > pec[a])] = sid
np.maximum(pec[a], np.where(m, q.priority, -np.inf),
out=pec[a])
# lumped elements: parallel R / C into G / C of the edges, parallel L and
# series RLC as edge branches
op.par_L, op.series = [], []
lumped = [(q.priority, p, q) for p in props
if isinstance(p, C.LumpedElement) for q in p.primitives]
for pr, p, q in lumped:
a = p.ny
rg = _box_ranges(q, grid, a)
if rg is None:
op.notes.append(
f"lumped element {p.name}: its box holds no {C.AXES[a]} edge - "
"left out"
)
continue
(e0, e1), others = rg[a], [(b, rg[b]) for b in range(3) if b != a]
# drawing units, like the lines
Lbox = grid.d[a][e0:e1 + 1].sum() / grid.unit
(b, (j0, j1)), (c, (k0, k1)) = others
wb = _clipped_weights(grid, b, j0, j1, *sorted((q.start[b], q.stop[b])))
wc = _clipped_weights(grid, c, k0, k1, *sorted((q.start[c], q.stop[c])))
frac = np.multiply.outer(wb, wc) # each column's share of the current
series = (p.LEtype == 1
and sum(v is not None for v in (p.R, p.L, p.C)) > 1)
for e in range(e0, e1 + 1):
share = (grid.d[a][e] / grid.unit) / Lbox # of the length
for jj in range(j0, j1 + 1):
for kk in range(k0, k1 + 1):
idx = [0, 0, 0]
idx[a], idx[b], idx[c] = e, jj, kk
i, j, k = idx
# a metal of higher priority keeps the edge
if pec[a, i, j, k] > pr:
continue
pec[a, i, j, k] = -np.inf
f = frac[jj - j0, kk - k0]
Re = None if p.R is None else p.R * share / f
Le = None if p.L is None else p.L * share / f
Ce = None if p.C is None else p.C * f / share
if series:
op.series.append((_flat(sh, a, i, j, k), Re or 0.0, Le
or 0.0, Ce))
continue
if Re is not None:
if Re > 0:
cond[a, i, j, k] += 1.0 / Re
else:
pec[a, i, j, k] = pr
if Ce is not None:
cap[a, i, j, k] += Ce
if Le is not None and Le > 0:
op.par_L.append((_flat(sh, a, i, j, k), Le))
if p.caps: # metal faces at both ends
for line in (e0, e1 + 1):
for t, (t0, t1), (u, (u0, u1)) in ((b, (j0, j1), (c, (k0, k1))),
(c, (k0, k1), (b, (j0,
j1)))):
for ti in range(t0, t1):
for ui in range(u0, u1 + 1):
idx = [0, 0, 0]
idx[a], idx[t], idx[u] = line, ti, ui
if pr >= pec[t][tuple(idx)]:
sheet_of[t][tuple(idx)] = -1
pec[t][tuple(idx)] = max(pec[t][tuple(idx)], pr)
pec_m = pec > -np.inf
# (openEMS.settings: GFDTD_TIMESTEP too)
method = str(fdtd.get('timestep_method') or 'auto').lower()
key = (_core_key(csx, fdtd) if method in ('auto', 'exact', '3',
'rennings') else None)
kept = _kept_limits().get(key) if key else None
if method == 'auto': # the large models, or one already measured
method = ('exact' if
(kept or int(np.prod([n - 1 for n in sh])) >= AUTO_CELLS) else
'courant')
if method in ('exact', '3', 'rennings'): # R-D6: the operator's own limit
einv = np.where(
pec_m & ~(sheet_of >= 0), 0.0,
np.divide(1.0, cap, out=np.zeros_like(cap), where=cap > 0))
hk = np.zeros((3,) + sh)
for a in range(3):
mu = (MU0 *
(_hedge_average(mue, a, grid) if np.any(mue != 1.0) else 1.0))
np.divide(lH[a], mu * aH[a], out=hk[a], where=aH[a] > 0)
geo_dt = op.dt
limit = kept or exact_timestep(einv, hk, factor=1.0)
if key and not kept:
keep_limit(key, limit)
op.dt = SAFETY * limit * float(fdtd.get('timestep_factor', 1.0) or 1.0)
if fdtd.get('timestep'):
op.dt = min(op.dt, float(fdtd['timestep']))
del einv, hk
op.notes.append(
"time step from the operator's own "
f"limit{' (kept from an earlier run)' if kept else ''}: "
f"{op.dt * 1e15:.4g} fs, {op.dt / geo_dt:.3f} x the vacuum Courant "
"rule's"
)
dt = op.dt
# conducting sheets: openEMS's model on the edges a sheet owns; PEC near the
# boundaries, as openEMS's
sheet_m = pec_m & (sheet_of >= 0)
if sheet_m.any():
bcn = [_bc_size(b) for b in fdtd['bc']]
near = np.zeros(sh, bool)
for b in range(3):
sl = [None] * 3
sl[b] = slice(None)
k = np.arange(sh[b])
near |= (((k <= bcn[2 * b]) |
(k >= sh[b] - bcn[2 * b + 1] - 1))[tuple(sl)])
sheet_m &= ~near[None]
sheet_of[~sheet_m] = -1
pec_m &= ~sheet_m # from here on: PEC only
op.n_pec = [int(pec_m[a].sum()) for a in range(3)]
op.n_sheet = int(sheet_m.sum())
rl = _sheet_edges(sheets, sheet_of, sheet_m, grid, lE, dt,
float(fdtd['f0']) + float(fdtd['fc']), op.notes)
if rl is not None:
cap.reshape(-1)[rl[0]], cond.reshape(-1)[rl[0]] = rl[1], rl[2]
# poles: i' = ka i + kb (V' - sg V). Debye (sg 1): tau di/dt + i = C_p
# dV/dt; a sheet's R-L branch (sg -1): L di/dt + R i = V. Both by the
# trapezoidal rule; the E update sees (i + i') / 2, so kb / 2 joins the
# edge's C / dt in the denominator and sg kb / 2 in the numerator
# (made where there is a pole: 48 B a node)
kb_sum = kbs_sum = None
# (flat edge, ka, kb, sg) of every pole on every edge
op.debye = []
if debye or rl is not None:
kb_sum, kbs_sum = np.zeros((3,) + sh), np.zeros((3,) + sh)
for n, p in enumerate(debye):
mine = owner == n
for d_eps, tau in p.pole_list():
for a in range(3):
with np.errstate(divide='ignore', invalid='ignore'):
cp = np.where(
lE[a] > 0,
EPS0
* _edge_average(np.where(mine, d_eps, 0.0), a, grid)
* aE[a] / lE[a], 0.0)
cp[pec_m[a] | sheet_m[a]] = 0.0
nz = np.nonzero(cp > 0)
if not len(nz[0]):
continue
kb = 2 * cp[nz] / (2 * tau + dt)
kb_sum[a][nz] += kb
kbs_sum[a][nz] += kb
op.debye.append((_flat(sh, a, *nz),
np.full(len(kb), (2 * tau - dt) /
(2 * tau + dt)), kb, np.ones(len(kb))))
if rl is not None:
for e, R, tau in rl[3]: # L di/dt + R i = V: tau = L / R
kb = dt / (R * (2 * tau + dt))
kb_sum.reshape(-1)[e] += kb
kbs_sum.reshape(-1)[e] -= kb
op.debye.append((e, np.full(len(e), (2 * tau - dt) /
(2 * tau + dt)), kb, -np.ones(len(kb))))
if op.debye:
idx, ka, kb, sg = (np.concatenate(v) for v in zip(*op.debye))
op.debye = (idx.astype(np.int64), ka, kb, sg)
else:
op.debye = None
vv, vi, iv = (np.zeros((3,) + sh) for _ in range(3))
# magnetic materials (Mue, Sigma): I' = ii I - iv curl V, ii = (1 - g) / (1
# + g), iv / (1 + g) with mu, g = sigma dt / (2 mu); the compiled kernels' H
# update is geometry alone, so such a model runs on NumPy's
op.magnetic = bool(np.any(mue != 1.0) or np.any(sig != 0.0))
op.ii = np.ones((3,) + sh) if np.any(sig != 0.0) else None
if op.magnetic:
names = sorted({
p.name
for _, p, _ in mats
if getattr(p, 'mue', 1.0) != 1.0 or getattr(p, 'sigma', 0.0)
})
op.notes.append(
f"magnetic materials ({', '.join(names) or 'the background'}: Mue "
"/ Sigma): the NumPy backend runs them (the compiled kernels' H "
"update is geometry alone)")
# a component at a time (its temporaries)
with np.errstate(divide='ignore', invalid='ignore'):
for a in range(3):
den = cap[a] + cond[a] * (dt / 2)
num = cap[a] - cond[a] * (dt / 2)
if kb_sum is not None:
den += kb_sum[a] * (dt / 2)
num += kbs_sum[a] * (dt / 2)
ok = den > 0
np.divide(num, den, out=vv[a], where=ok)
np.divide(dt, den, out=vi[a], where=ok)
del den, num, ok
h = aH[a] > 0
if op.magnetic:
mu = MU0 * _hedge_average(mue, a, grid)
g = (_hedge_average(sig, a, grid) * dt /
(2 * np.where(mu > 0, mu, MU0)))
np.divide(dt * lH[a], mu * aH[a] * (1 + g), out=iv[a],
where=h & (mu > 0))
if op.ii is not None:
op.ii[a] = (1 - g) / (1 + g)
else:
np.divide(dt * lH[a], MU0 * aH[a], out=iv[a], where=h)
vv[pec_m], vi[pec_m] = 0.0, 0.0
# boundaries
op.bc = bc = [str(b).upper() for b in fdtd['bc']]
mur0, mur1, murk = [], [], []
op.pml = []
for side, b in enumerate(bc):
a, hi = side // 2, side % 2
n = sh[a]
face, inner = (n - 1, n - 2) if hi else (0, 1)
if b.startswith('PML'):
op.pml.append(_pml_slab(grid, a, hi, b, dt))
b = 'PEC' # behind the PML
for t in range(3):
if t == a:
continue
sl = [slice(None)] * 3
sl[a] = face
if b == 'PEC':
vv[t][tuple(sl)] = 0.0
vi[t][tuple(sl)] = 0.0
elif b == 'MUR':
pos = np.nonzero(vi[t][tuple(sl)] > 0)
ijk0, ijk1 = [None] * 3, [None] * 3
rest = [x for x in range(3) if x != a]
ijk0[a], ijk1[a] = (np.full(len(pos[0]),
face), np.full(len(pos[0]), inner))
for r_, pp in zip(rest, pos):
ijk0[r_] = ijk1[r_] = pp
delta = abs(grid.m[a][face] - grid.m[a][inner])
cl = C0 / np.sqrt(np.maximum(epsE[t][tuple(ijk0)], 1.0))
mur0.append(_flat(sh, t, *ijk0))
mur1.append(_flat(sh, t, *ijk1))
murk.append((cl * dt - delta) / (cl * dt + delta))
elif b != 'PMC':
raise ValueError(
f"gfdtd: boundary {b} not supported (PEC, PMC, MUR, PML_n)")
op.mur = ((np.concatenate(mur0).astype(np.int64),
np.concatenate(mur1).astype(np.int64),
np.concatenate(murk)) if mur0 else None)
op.ferrite = _ferrite(fer, fown, grid, sh, dt, op.notes) if fer else None
del fown
return (op,
dict(grid=grid, sh=sh, vv=vv, vi=vi, iv=iv, lE=lE, lH=lH, aE=aE,
kap=kap, dt=dt, ncell=ncell))
def _nearest(t, c):
"""Index of the nearest of the sorted values t to each of c."""
t = np.asarray(t, float)
if len(t) < 2:
return np.zeros(len(c), np.int64)
j = np.clip(np.searchsorted(t, c), 1, len(t) - 1)
return np.where(c - t[j - 1] <= t[j] - c, j - 1, j)
[docs]
class Ferrite:
"""A model's magnetised ferrite (_ferrite): its cells' update and the H
edges they meet, flat arrays. na: the components (2: every cell biased
along +-z, the fast path; 3: along its own direction u, or partly
magnetised). Per cell c (nc): e[c] its 2 na edges (x lower, x upper, y
lower, y upper[, z lower, z upper]: positions in the edge list), k[c]
(na 2: p0, s p1, q0, s q1; na 3: p0, p1, q0, q1, ux, uy, uz, qs), state
(m, the last b: 2 na floats, A/m, zero at the start; faces: and per
component its faces' difference mode m, its partner and the last
difference: 3 na more). Per edge (ne): idx (its flat index into I), lh
(its dual length, m: I = H lh), cells (its two cells' offsets into the
change array dm[rows (nc + 1)]: the component's row, faces: the face's,
the dummy cell nc where there is none), w (their weights)."""
def __init__(self, **kw):
self.__dict__.update(kw)
[docs]
def nbytes(self):
"""What its arrays take on the GPU (bytes): per cell the edges,
coefficients, state and change; per edge its index, lengths, cells,
weights and m."""
f = getattr(self, 'faces', False)
per_cell = 4 * (2 * self.na + self.k.shape[1] + (5 if f else 2)
* self.na + (2 if f else 1) * self.na)
return per_cell * self.nc + 36 * self.ne
def _cell_bias(p, grid, cells):
"""The internal field h (n, 3, A/m) and M / Ms m (n, 3; None: saturated
along h) of a FerriteMaterial at the cells (index arrays), its bias
table's nearest point to each centre."""
n = len(cells[0])
b = p.bias
if isinstance(b, dict):
near = tuple(_nearest(b[a], grid.mid[k][q])
for k, (a, q) in enumerate(zip('xyz', cells)))
h = np.stack([b[c][near] if b.get(c) is not None else np.zeros(n)
for c in ('hx', 'hy', 'hz')], axis=1)
m = (np.stack([b[c][near] for c in ('mx', 'my', 'mz')], axis=1)
if b.get('mz') is not None else None)
return h, m
v = np.asarray(b, float)
h = np.tile(v if v.shape == (3,) else [0.0, 0.0, float(v)], (n, 1))
return h, None
[docs]
def schlomann(fm, f):
"""Schlomann's demagnetised permeability: 1/3 + 2/3 sqrt(1 - (fm / f)^2)
(fm = gamma Ms, f the frequency; 1/3 where f <= fm, the low-field loss's
band, which it does not hold)."""
x = np.clip(np.asarray(fm, float) / np.maximum(f, 1e-300), 0.0, 1.0)
return 1.0 / 3.0 + 2.0 / 3.0 * np.sqrt(1.0 - x * x)
def _ferrite(fer, fown, grid, sh, dt, notes):
"""The ferrite cells' update (gfdtd.csx.FerriteMaterial). The linearised
Landau-Lifshitz-Gilbert equation of the small magnetisation m (normal to
the static magnetisation's direction u: internal field H0, saturation
Ms), written in b = B / mu0 = h + m, which the H update advances by
Faraday's law alone (the ferrite's H edges are vacuum's: mu0):
dm/dt = U (wr m - wm b) + alpha U dm/dt, U v = u x v
wr = gamma (H0 + Ms), wm = gamma Ms; in the frequency domain the Polder
tensor turned to u (B = mu0 [mu, j kappa; -j kappa, mu] h for +z). m
lives at the cell centres: b there is the mean of its two x (y, z)
edges', and the edges get h = b - the cells' m weighted by half their
lengths over the edge's dual one (the transpose of that mean in the
cells' and edges' volumes). The trapezoidal rule makes it m+ = p0 m- +
p1 U m- + q0 P (b+ + b-) + q1 U (b+ + b-) (P: across u; U^2 = -P): a
rotation by 2 atan(wr dt / 2) unbiased by b, at any step.
A partly magnetised cell (M / Ms = r < 1: the table's m) is Green and
Sandy's: a static mu_s = mu_d + (1 - mu_d) r^1.5 (mu_d Schlomann's at
the material's freq) and Rado's kappa = r wm / w, which is the same
update with wr = r wm / mu_s, wm -> wr / mu_s (no internal field) plus
an instant qs b+, qs = 1 - 1 / mu_s, its change (qs (b+ - b-)) in the
cell's.
Every cell along +-z and saturated: the two components x and y alone
(na 2, the fast path); else all three (na 3)."""
ncell = tuple(n - 1 for n in sh)
idx = np.nonzero(fown >= 0)
nf = len(idx[0])
# the faces' scheme unless every ferrite asks for the cells' centres alone
faces = any(getattr(p, 'scheme', 'faces') != 'centre' for p in fer)
h = np.full((nf, 3), np.nan)
m = np.full((nf, 3), np.nan)
has_m = np.zeros(nf, bool)
ms, al, ga, fq = (np.zeros(nf) for _ in range(4))
own = fown[idx]
for n, p in enumerate(fer):
mine = own == n
if not mine.any():
continue
hh, mm = _cell_bias(p, grid, tuple(q[mine] for q in idx))
h[mine] = hh
if mm is not None:
m[mine], has_m[mine] = mm, True
ms[mine], al[mine], ga[mine] = p.ms, p.alpha, p.gamma
fq[mine] = getattr(p, 'freq', 0.0) or 0.0
# M / Ms and its direction: the table's m where given, else saturated
# along h
with np.errstate(invalid='ignore'):
r = np.where(has_m, np.sqrt((m * m).sum(axis=1)), 1.0)
dirn = np.where(has_m[:, None], m, h)
nd = np.sqrt((dirn * dirn).sum(axis=1))
hn = np.sqrt((h * h).sum(axis=1))
sat = r >= 1 - 1e-6
live = (np.isfinite(h).all(axis=1) & np.isfinite(dirn).all(axis=1)
& (nd > 0) & (ms > 0) & (r > 0) & np.where(sat, hn > 0, True))
part = live & ~sat
n_off = nf - int(live.sum())
if n_off:
notes.append(
f"ferrite: {n_off} of {nf} cells not "
"saturated (no bias there): left unbiased, a dielectric of mu 1")
if not live.any():
return None
ci, cj, ck = (q[live] for q in idx)
nc = len(ci)
u = dirn[live] / nd[live, None]
h0 = np.where(sat[live], hn[live], 0.0)
ms_, al_, ga_ = ms[live], al[live], ga[live]
r_ = np.minimum(r[live], 1.0)
pt = part[live]
# Green and Sandy's mu_s (1 where saturated), Rado's kappa
mu_s = np.ones(nc)
if pt.any():
mu_d = schlomann(ga_[pt] * ms_[pt] / (2 * np.pi), fq[live][pt])
mu_s[pt] = mu_d + (1 - mu_d) * r_[pt] ** 1.5
wr = np.where(pt, r_ * ga_ * ms_ / mu_s, ga_ * (h0 + ms_))
wm = np.where(pt, wr / mu_s, ga_ * ms_)
beta, gm = wr * dt / 2, wm * dt / 2
a, c = al_ + beta, al_ - beta
den = 1 + a * a
p0, p1, q0, q1 = (1 + a * c) / den, 2 * beta / den, gm * a / den, -gm / den
qs = 1 - 1 / mu_s
na = 2 if (not pt.any() and not np.any(u[:, :2])) else 3
if na == 2:
sg = np.sign(u[:, 2])
k = np.stack([p0, sg * p1, q0, sg * q1], axis=1)
else:
k = np.stack([p0, p1, q0, q1, u[:, 0], u[:, 1], u[:, 2], qs], axis=1)
# the cells' edges: along a at lines i and i + 1 of a
cols = []
for ax_ in range(na):
o = [int(ax_ == q) for q in range(3)]
cols += [_flat(sh, ax_, ci, cj, ck),
_flat(sh, ax_, ci + o[0], cj + o[1], ck + o[2])]
edges, inv = np.unique(np.stack(cols, axis=1).ravel(), return_inverse=True)
e_of = inv.reshape(nc, 2 * na).astype(np.int32)
# each edge's cells: the ferrite cell index map (-1: none)
cmap = np.full(ncell, -1, np.int64)
cmap[ci, cj, ck] = np.arange(nc)
n_per = int(np.prod(sh))
ax = edges // n_per
rest = edges % n_per
e3 = (rest // (sh[1] * sh[2]), (rest // sh[2]) % sh[1], rest % sh[2])
ne = len(edges)
cells = np.full((ne, 2), nc, np.int64)
w = np.zeros((ne, 2))
lh = np.choose(ax, [grid.dual[q][e3[q]] for q in range(3)])
for side, off in ((0, -1), (1, 0)): # the cell below the line, above it
l3 = [np.where(ax == q, e3[q] + off, e3[q]) for q in range(3)]
ok = np.ones(ne, bool)
for q in range(3):
ok &= (l3[q] >= 0) & (l3[q] < ncell[q])
cc = np.full(ne, -1, np.int64)
cc[ok] = cmap[l3[0][ok], l3[1][ok], l3[2][ok]]
hs = cc >= 0
d = np.choose(ax, [grid.d[q][np.clip(l3[q], 0, ncell[q] - 1)]
for q in range(3)])
cells[hs, side] = cc[hs]
w[hs, side] = 0.5 * d[hs] / lh[hs]
# offsets into dm: the edge's component's row (centre: na rows of nc + 1);
# faces: 2 na rows, each component's lower faces' then its upper ones',
# the edge the upper face of the cell below the line and the lower of
# the one above it
if faces:
cells = cells + (2 * ax[:, None] + np.array([[1, 0]])) * (nc + 1)
else:
cells = cells + ax[:, None] * (nc + 1)
del cmap
if na == 2:
sg = np.sign(u[:, 2])
notes.append(
f"ferrite: {nc} cells magnetised ({ne} H edges), bias "
f"{h0.min():.4g} to {h0.max():.4g} A/m "
f"({'+' if (sg > 0).all() else '-' if (sg < 0).all() else '+/-'}"
"z)")
else:
tilt = np.degrees(np.arccos(np.clip(np.abs(u[:, 2]), 0, 1)))
hsat = h0[~pt]
notes.append(
f"ferrite: {nc} cells magnetised ({ne} H edges) along their own "
f"directions (up to {tilt.max():.3g} deg off z, mean "
f"{tilt.mean():.2g}), bias "
+ (f"{hsat.min():.4g} to {hsat.max():.4g} A/m" if len(hsat) else
"none saturated"))
if pt.any():
notes.append(
f"ferrite: {int(pt.sum())} of them partly magnetised (M / Ms "
f"{r_[pt].min():.2g} to {r_[pt].max():.2g}; Green and Sandy's "
f"mu {mu_s[pt].min():.3g} to {mu_s[pt].max():.3g}, Rado's "
"kappa)")
return Ferrite(nc=nc, ne=ne, na=na, faces=faces, e=e_of, k=k,
idx=edges.astype(np.int64), lh=lh,
cells=cells.astype(np.int32), w=w, ijk=(ci, cj, ck),
h0=h0, ms=ms_, u=u, mr=r_, mu_s=mu_s)
def _excitations(props, grid, sh, vv, vi, lE, lH, dt, notes):
"""(idx, amp) of the soft and hard E excitations without delay (one signal
for all: the fast path), and [dict(field 'V' | 'I', delay steps, hard, idx,
amp)] of the others. Edges are taken as openEMS takes them: the E edges
whose midpoint, the H edges whose dual midpoint (inside the last lines) is
in a primitive, curves along their path; the amplitude is exc_val times the
weight there times the edge's length. Hard E edges lose their update (vv =
vi = 0), so the signal sets them; hard H edges are set after the H
update."""
main_i, main_a, more = [], [], {}
for p in props:
if not isinstance(p, C.Excitation):
continue
if p.exc_type not in (0, 1, 2, 3):
raise ValueError(
f"gfdtd: excitation {p.name}: type {p.exc_type} not supported "
"(0-3)"
)
hfield = p.exc_type >= 2
hard = p.exc_type in (1, 3)
delay = int(p.delay / dt) if p.delay > 0 else 0
idx, amp = [], []
for q in p.primitives:
for a in range(3):
if p.exc_val[a] == 0:
continue
if isinstance(q, C.Curve):
if hfield:
continue
hits = [
ijk for b, ijk in curve_edges(q, grid)
if b == a and ijk[a] < sh[a] - 1
]
if not hits:
continue
nz = tuple(np.array(v) for v in zip(*hits))
else:
if hfield: # H_a at line a, cell centres across
pts = [
grid.lines[b] if b == a else grid.mid[b]
for b in range(3)
]
m = inside(q, pts, grid)
m = np.pad(m, [(0, 0) if b == a else (0, 1)
for b in range(3)])
m[tuple(
slice(sh[b] - 1, None) if b == a else slice(None)
for b in range(3))] = False
else:
m = edge_mask(q, a, grid) & (vi[a] > 0)
nz = np.nonzero(m)
if not len(nz[0]):
continue
if hfield:
coords = [
grid.lines[b][nz[b]]
if b == a else grid.mid[b][np.minimum(nz[b], sh[b] - 2)]
for b in range(3)
]
length = lH[a][nz]
else:
coords = [
grid.mid[b][nz[b]] if b == a else grid.lines[b][nz[b]]
for b in range(3)
]
length = lE[a][nz]
w = p.weights(a, coords) * p.exc_val[a] * length
keep = w != 0
idx.append(_flat(sh, a, *(v[keep] for v in nz)))
amp.append(w[keep])
if hard and not hfield:
vv[a][tuple(v[keep] for v in nz)] = 0.0
vi[a][tuple(v[keep] for v in nz)] = 0.0
if not idx:
continue
idx, amp = np.concatenate(idx).astype(np.int64), np.concatenate(amp)
if not hfield and delay == 0:
main_i.append(idx)
main_a.append(amp)
else:
g = more.setdefault(
('I' if hfield else 'V', delay, hard and hfield), ([], []))
g[0].append(idx)
g[1].append(amp)
main = (np.concatenate(main_i) if main_i else np.zeros(0, np.int64),
np.concatenate(main_a) if main_a else np.zeros(0))
groups = [
dict(field=f, delay=d, hard=h, idx=np.concatenate(i),
amp=np.concatenate(a_))
for (f, d, h), (i, a_) in sorted(more.items())
]
return main, groups
# compressed coefficients: low mantissa bits dropped (2^-20 relative) so that
# equal ones match
QUANT_BITS = 4
def _q32(x):
"""float32 values with the low QUANT_BITS mantissa bits rounded off, and
their bit patterns."""
bits = np.ascontiguousarray(x, np.float32).view(np.uint32)
half = np.uint32(1 << (QUANT_BITS - 1))
bits = (bits + half) & np.uint32(~((1 << QUANT_BITS) - 1) & 0xFFFFFFFF)
return bits.view(np.float32), bits
[docs]
class Compressed:
"""The operator without its coefficient arrays, for the compiled kernels
(GPU and CPU core). vi = geoE * s and iv = geoH come from 1-D line arrays:
geoE_a = dt / eps0 * d_a * (1 / dual_b) * (1 / dual_c), geoH_a = dt / mu0 *
dual_a * (1 / d_b) * (1 / d_c). Each node keeps one code into a table of its
three E edges' (vv, s, Debye poles); the nodes of one material (and one
quarter-cell mix at interfaces) share one.
code (Nx, Ny, Nz) uint8, uint16 past 255 codes, uint32 past 65535
vv, s (ncode, 3) float32; pole (ncode, 3) int32: row of kbt, or -1 (no
poles)
kbt (nrow, P) float32: each pole's kb~ = kb l / (eps0 A'); ka (P,):
its ka; h (2P,): (1 + ka) / 2, then its sg (1: Debye, -1: a
conducting sheet's R-L branch)
slot (Nx, Ny, Nz) int32: the node's row in the pole currents (nslot, 3,
P), -1 elsewhere
G float32 [d | 1/d | dual | 1/dual], each [x | y | z] (d and 1/d
zero past the last line)
ke, kh dt / eps0, dt / mu0
Pole currents are kept scaled: i~ = i l / (eps0 A'), so that V' = vv V + vi
c - dt s sum(h i~) and i~' = ka i~ + kb~ (V' - sg V) need no geometry."""
def _unique_rows(trip):
"""np.unique(trip, axis=0, return_inverse=True) for (n, 3) non-negative
integer codes, through one int64 key per row (21 bits a code): the sort of a
1-D array, where unique over rows sorts structured records - 0.4 s against
6.4 s at 5.6 M nodes. Rows of larger codes fall back to np.unique."""
trip = np.asarray(trip)
if trip.size == 0 or trip.min() < 0 or trip.max() >= 1 << 21:
nodes, code = np.unique(trip, axis=0, return_inverse=True)
return nodes, code.ravel()
t = trip.astype(np.int64)
key = (t[:, 0] << 42) | (t[:, 1] << 21) | t[:, 2]
u, code = np.unique(key, return_inverse=True)
m = (1 << 21) - 1
nodes = np.stack([u >> 42, (u >> 21) & m, u & m], 1).astype(trip.dtype)
return nodes, code.ravel()
# {core key: Compressed}: the GPU's form of the core, for its other excitations
_COMPRESSED = {}
[docs]
def compress(op):
"""op.vv / op.vi / op.iv / op.debye as a Compressed operator (exact to 2^-20
in vv and s), the same object for every excitation of one model (it reads
only the core): read only."""
key = getattr(op, '_core_key', None)
return (_compress(op)
if key is None else _kept(_COMPRESSED, key, lambda: _compress(op)))
def _compress(op):
g, sh, dt = op.grid, op.shape, op.dt
cp = Compressed()
pad0 = lambda d: np.concatenate([d, [0.0]])
d = [pad0(x) for x in g.d]
idd = [pad0(1.0 / x) for x in g.d]
cp.G = np.concatenate([
np.concatenate(v) for v in (d, idd, g.dual, [1.0 / x for x in g.dual])
]).astype(np.float32)
cp.ke, cp.kh = dt / EPS0, dt / MU0
r = lambda v, ax: v.reshape([-1 if x == ax else 1 for x in range(3)])
geo = [None] * 3 # (separable: a 1-D product per component)
s_ = np.zeros((3,) + sh, np.float32)
for a in range(3):
b, c = [x for x in range(3) if x != a]
geo[a] = (cp.ke * r(d[a], a) * r(1.0 / g.dual[b], b)
* r(1.0 / g.dual[c], c))
with np.errstate(divide='ignore', invalid='ignore'):
np.divide(op.vi[a], geo[a], out=s_[a],
where=np.broadcast_to(geo[a] > 0, sh), casting='unsafe')
# every per-edge array below is let go once used (R-D7: they had all lived
# to the end, 290 B a node)
vv_q, vv_b = _q32(op.vv.ravel())
s_q, s_b = _q32(s_.ravel())
del s_
# Debye: the poles by relaxation (ka), each edge's kb~ per pole, and the
# distinct pole rows
N = vv_b.size
pid = np.zeros(N, np.int32) # 0: no poles, else row + 1
cp.P, cp.ka, cp.h, cp.kbt = (0, np.zeros(0, np.float32),
np.zeros(0, np.float32),
np.zeros((0, 0), np.float32))
if op.debye is not None:
idx, ka, kb, sg = op.debye
# the poles: (ka, sg)
pairs, col = np.unique(np.stack([ka, sg], 1), axis=0,
return_inverse=True)
col = col.ravel()
kas, sgs = pairs[:, 0], pairs[:, 1]
cp.P = len(kas)
kbt = np.zeros((N, cp.P))
a_of, rest = np.divmod(idx, int(np.prod(sh)))
at = np.empty(len(idx))
for a in range(3): # geo at each pole's edge
m = a_of == a
at[m] = np.broadcast_to(geo[a], sh).reshape(-1)[rest[m]]
with np.errstate(divide='ignore', invalid='ignore'):
# kb~ = kb l / (eps0 A') = kb geo / dt
np.add.at(kbt, (idx, col), kb * at / dt)
rows_e = np.unique(idx)
kq, kbits = _q32(kbt[rows_e])
rows, inv = np.unique(kbits, axis=0, return_inverse=True)
pid[rows_e] = inv.ravel() + 1
cp.kbt = rows.view(np.float32).reshape(len(rows), cp.P).copy()
cp.ka = kas.astype(np.float32)
# [h | sg]
cp.h = np.concatenate([0.5 * (1 + kas), sgs]).astype(np.float32)
# the edge codes: the distinct (vv, s, pole row) of the edges, in that sort
# order, found a component at a time (np.unique of all 3N edges at once had
# held its sort and inverse of 3N: 96 B a node) and joined
n1, P1 = N // 3, int(pid.max()) + 1
local, tabs = [], []
for a in range(3):
sl = slice(a * n1, (a + 1) * n1)
k = ((vv_b[sl].astype(np.uint64) << np.uint64(32))
| s_b[sl].astype(np.uint64))
u, inv = np.unique(k, return_inverse=True)
del k
w = inv.ravel().astype(np.int64) * P1 + pid[sl]
del inv
u2, code_a = np.unique(w, return_inverse=True)
del w
# (key, pole row + 1) of each local code
tabs.append((u[u2 // P1], u2 % P1))
local.append(code_a.ravel().astype(np.int32))
del vv_b, s_b, vv_q, s_q
keys = np.concatenate([t[0] for t in tabs])
prow = np.concatenate([t[1] for t in tabs])
# by key, then pole row: the old codes' order
order = np.lexsort((prow, keys))
keys, prow = keys[order], prow[order]
new_ = np.r_[True, (keys[1:] != keys[:-1]) | (prow[1:] != prow[:-1])]
gid = np.empty(len(order), np.int64)
gid[order] = np.cumsum(new_) - 1
ukeys, uprow = keys[new_], prow[new_]
evv = (ukeys >> np.uint64(32)).astype(np.uint32).view(np.float32)
es = (ukeys & np.uint64(0xFFFFFFFF)).astype(np.uint32).view(np.float32)
epole = (uprow - 1).astype(np.int32)
has = (pid.reshape((3,) + sh) > 0).any(0)
del pid
offs = np.cumsum([0] + [len(t[0]) for t in tabs])
for a in range(3): # each component's codes, the joined table's
local[a] = gid[offs[a]:offs[a + 1]][local[a]].astype(np.int32)
if len(ukeys) < 1 << 21: # per node: its three edge codes (_unique_rows)
key = ((local[0].astype(np.int64) << 42) |
(local[1].astype(np.int64) << 21) | local[2])
del local
u, code = np.unique(key, return_inverse=True)
del key
m = (1 << 21) - 1
nodes = np.stack([u >> 42, (u >> 21) & m, u & m], 1)
code = code.ravel()
else:
nodes, code = _unique_rows(np.stack(local, 1))
del local
cp.vv, cp.s, cp.pole = evv[nodes], es[nodes], epole[nodes] # (ncode, 3)
cp.ncode = len(nodes)
dtype = (np.uint8 if cp.ncode <= 255 else
(np.uint16 if cp.ncode <= 65535 else np.uint32))
cp.code = code.ravel().astype(dtype).reshape(sh)
del code
cp.slot = np.full(sh, -1, np.int32)
cp.nslot = int(has.sum())
cp.slot[has] = np.arange(cp.nslot, dtype=np.int32)
return cp
def _pml_slab(grid, a, hi, b, dt):
"""dict(axis, hi, e0, h0, n, bE, cE, bH, cH) of a PML_n side: its n
outermost cells along axis a. psi = b psi + c (difference across a) at the E
edges' lines e0.. (bE, cE) and the H edges' cell centres h0.. (bH, cH)."""
try:
n = int(b.split('_')[1])
except (IndexError, ValueError):
n = 8
L = grid.m[a]
N = len(L)
n = max(1, min(n, N - 2))
if hi:
# E lines N-n .. N-1, H cells N-1-n .. N-2
x0, e0, h0 = L[N - 1 - n], N - n, N - 1 - n
else:
x0, e0, h0 = L[n], 0, 0 # E lines 0 .. n-1, H cells 0 .. n-1
depth = abs(L[-1] - L[N - 1 - n]) if hi else abs(L[n] - L[0])
# sigma_max / eps0
smax = -(PML_GRADING + 1) * np.log(PML_R0) * C0 / (2 * depth)
xe = L[e0:e0 + n]
xh = 0.5 * (L[h0:h0 + n] + L[h0 + 1:h0 + n + 1])
grade = lambda x: smax * np.clip(np.abs(x - x0) / depth, 0, 1)**PML_GRADING
bE, bH = np.exp(-grade(xe) * dt), np.exp(-grade(xh) * dt)
return dict(axis=a, hi=hi, n=n, e0=int(e0), h0=int(h0), bE=bE, cE=bE - 1,
bH=bH, cH=bH - 1, name=b)
DUMP_FIELDS = {0: 'E', 1: 'H', 2: 'Jc', 3: 'J'} # dump_type % 10
def _dump(p, grid, notes):
"""[dict(name, field, fd (freqs Hz or None), mode ('cell' | 'node'), lo, hi
(index ranges, inclusive), coords (m), file_type, sub)] of a dump, one per
box (named <name>_<n> when it has several, as openEMS's NF2FF boxes). Dump
mode 2 picks cells as openEMS does: the box snapped to the nearest lines s0
.. s1, then the cells s0-1 .. s1 (a flat box: the cell below its line; the
cell past the last line counts, its field is zero). Modes 0 and 1: the nodes
on the lines s0 .. s1."""
t = p.dump_type
if t % 10 not in DUMP_FIELDS or t // 10 not in (0, 1):
notes.append(
f"field dump {p.name}: dump type {t} not supported - skipped")
return []
fd = t >= 10
if fd and not p.frequency:
notes.append(
f"field dump {p.name}: frequency domain with no frequencies - "
"skipped"
)
return []
mode = 'cell' if p.dump_mode == 2 else 'node'
sub = int(np.max(p.sub_sampling)) if p.sub_sampling is not None else 1
out = []
for n, q in enumerate(p.primitives):
if not isinstance(q, C.Box) or q.HasTransform():
notes.append(
f"field dump {p.name}: a {type(q).__name__}"
+ (" with a transform" if isinstance(q, C.Box) else "")
+ " - only boxes along the axes are dumped, skipped")
continue
lo3, hi3 = np.minimum(q.start, q.stop), np.maximum(q.start, q.stop)
lo, hi, coords = [], [], []
for a in range(3):
L = grid.lines[a]
# the box snapped to lines s0 .. s1
s0 = int(np.argmin(np.abs(L - lo3[a])))
s1 = int(np.argmin(np.abs(L - hi3[a])))
if mode == 'node':
i0, i1, pts = s0, s1, L
else:
i0 = max(s0 - 1, 0)
# the cells s0-1 .. s1; flat: the one below
i1 = s1 if s1 > s0 else i0
pts = np.concatenate(
[grid.mid[a], [L[-1] + 0.5 * (L[-1] - L[-2])]])
lo.append(i0)
hi.append(i1)
coords.append(pts[i0:i1 + 1] * grid.unit)
out.append(
dict(name=(p.name if len(p.primitives) == 1 else f"{p.name}_{n}"),
field=DUMP_FIELDS[t % 10], type=t,
fd=(list(p.frequency) if fd else None), mode=mode, lo=lo,
hi=hi, coords=coords, file_type=p.file_type, sub=max(1, sub),
unit=grid.unit))
return out
def _current_nodes(grid, b, lo, hi):
"""The node range (inclusive) a current probe's loop encloses across axis b,
as openEMS snaps the box to the dual mesh: the nodes whose dual cell
overlaps (lo, hi); a flat box: the nearest node (none at a midpoint tie)."""
L = grid.lines[b]
# node k's dual cell: dual[k] .. dual[k+1]
dual = np.concatenate([[-np.inf], 0.5 * (L[1:] + L[:-1]), [np.inf]])
tol = grid.tol[b]
if hi - lo < tol:
k = int(np.argmin(np.abs(L - lo)))
return ((k, k) if abs(
abs(L[k] - lo)
- min(abs(np.delete(L, k) - lo), default=np.inf)) > tol else
(k, k - 1))
ks = np.nonzero((dual[1:] > lo + tol) & (dual[:-1] < hi - tol))[0]
return (int(ks[0]), int(ks[-1])) if len(ks) else (0, -1)
def _probe(p, q, grid, sh):
"""dict(name, type, field 'V' | 'I', idx, w, start, stop) of a probe box:
the terms whose sum is its value."""
s = [int(np.argmin(np.abs(grid.lines[a] - q.start[a]))) for a in range(3)]
e = [int(np.argmin(np.abs(grid.lines[a] - q.stop[a]))) for a in range(3)]
terms = defaultdict(float)
if p.p_type == 0: # E integral, x then y then z
pos = list(s)
for a in range(3):
step = 1 if e[a] >= s[a] else -1
while pos[a] != e[a]:
i = pos[a] if step > 0 else pos[a] - 1
idx = list(pos)
idx[a] = i
terms[_flat(sh, a, *idx)] += step * p.weight
pos[a] += step
field = 'V'
elif p.p_type == 1: # H loop around the box, normal n
n = p.norm_dir
if n < 0:
n = next(a for a in range(3) if s[a] == e[a])
b, c = (n + 1) % 3, (n + 2) % 3 # cyclic: the loop's sense is curl's
cn = 0.5 * (q.start[n] + q.stop[n])
layer = int(
np.clip(
np.searchsorted(grid.lines[n], cn - grid.tol[n], 'left') - 1, 0,
sh[n] - 2))
rb = _current_nodes(grid, b, *sorted((q.start[b], q.stop[b])))
rc = _current_nodes(grid, c, *sorted((q.start[c], q.stop[c])))
for jb in range(rb[0], rb[1] + 1):
for kc in range(rc[0], rc[1] + 1):
idx = [0, 0, 0]
idx[n], idx[b], idx[c] = layer, jb, kc
# loop sum of I around the n-edge: +I_c[.] - I_c[.-b] - I_b[.] +
# I_b[.-c]
for comp, off, sgn in ((c, b, +1), (b, c, -1)):
for shift, s2 in ((0, 1), (1, -1)):
jdx = list(idx)
jdx[off] -= shift
if jdx[off] < 0:
continue
terms[_flat(sh, comp, *jdx)] += sgn * s2 * p.weight
field = 'I'
elif p.p_type in (10, 11):
terms = _mode_match(p, grid, sh, s, e)
if terms is None:
return None
field = 'V' if p.p_type == 10 else 'I'
else:
return None
terms = {k: v for k, v in terms.items() if v != 0}
return dict(name=p.name, type=p.p_type, field=field,
idx=np.array(list(terms),
np.int64), w=np.array(list(terms.values()), float),
start=([grid.lines[a][s[a]] for a in range(3)], s),
stop=([grid.lines[a][e[a]]
for a in range(3)], e), unit=grid.unit)
def _field_probe(p, q, grid, sh):
"""openEMS's field probes (R-B18: they had been left out): type 2 E, type 3
H at the node nearest the box's centre, as three probes of one group (x, y,
z; the engine writes them as one file, t Ex Ey Ez): E_a the mean of the
node's two a-edges' V / l, H_a the mean of the four dual a-edges round it, I
/ l'."""
c = 0.5 * (np.asarray(q.start, float) + np.asarray(q.stop, float))
n = [int(np.argmin(np.abs(grid.lines[a] - c[a]))) for a in range(3)]
out = []
for a in range(3):
b, cc = [x for x in range(3) if x != a]
terms = defaultdict(float)
if p.p_type == 2: # E: the edges from n - e_a and from n
cand = [i for i in (n[a] - 1, n[a]) if 0 <= i < sh[a] - 1]
for i in cand:
idx = list(n)
idx[a] = i
terms[_flat(sh, a, *idx)] += (p.weight /
(len(cand) * grid.d[a][i]))
field = 'V'
else: # H: the four dual edges round the node
cand = [(j, k) for j in (n[b] - 1, n[b]) for k in (n[cc] - 1, n[cc])
if 0 <= j < sh[b] - 1 and 0 <= k < sh[cc] - 1]
for j, k in cand:
idx = [0, 0, 0]
idx[a], idx[b], idx[cc] = n[a], j, k
terms[_flat(sh, a, *idx)] += (p.weight /
(len(cand) * grid.dual[a][n[a]]))
field = 'I'
if not terms:
return None
xyz = [grid.lines[x][n[x]] for x in range(3)]
out.append(
dict(name=p.name, type=p.p_type, field=field,
idx=np.array(list(terms),
np.int64), w=np.array(list(terms.values()),
float), start=(xyz, n),
stop=(xyz, n), unit=grid.unit, group=p.name, comp=a))
return out
def _mode_match(p, grid, sh, s, e):
"""The terms of a mode-matching probe, as openEMS's ProcessModeMatch: on the
box's plane (normal n) the transverse E at the nodes (type 10, interpolated
between the edges either side) or H (type 11, the average of the four dual
edges round the node), times the mode function normalised to unit energy (at
the nodes for E, at the cell centres for H, as openEMS evaluates them),
times the node area. The boundary lines are left out."""
dual = p.p_type == 11
lo, hi = ([min(a, b)
for a, b in zip(s, e)], [max(a, b) for a, b in zip(s, e)])
for a in range(3):
if lo[a] == 0:
lo[a] += 1
if hi[a] == sh[a] - 1:
hi[a] -= 1
elif dual and hi[a] > lo[a] + 1:
hi[a] -= 1
flat = [a for a in range(3) if lo[a] == hi[a]]
if len(flat) != 1:
return None
n = flat[0]
u, v = (n + 1) % 3, (n + 2) % 3
def disc(a, i):
x = grid.lines[a]
if not dual:
return x[i]
if i < sh[a] - 1:
return grid.mid[a][i]
return x[i] + 0.5 * (x[i] - x[i - 1])
def width(a, i):
if not dual:
return grid.dual[a][i]
return grid.d[a][i] if i < sh[a] - 1 else 0.0
iu, iv = np.arange(lo[u], hi[u] + 1), np.arange(lo[v], hi[v] + 1)
cu = np.array([disc(u, i) for i in iu])
cv = np.array([disc(v, i) for i in iv])
area = np.outer([width(u, i) for i in iu], [width(v, i) for i in iv])
coords = [None] * 3
U, Vv = np.meshgrid(cu, cv, indexing='ij')
coords[u], coords[v], coords[n] = U, Vv, np.full(U.shape, disc(n, lo[n]))
fu, fv = p.mode(n, coords)
norm = np.sqrt(((fu ** 2 + fv ** 2) * area).sum())
if norm == 0:
return None
fu, fv = fu / norm, fv / norm
terms = defaultdict(float)
def add(comp, ijk, w):
terms[_flat(sh, comp, *ijk)] += w * p.weight
for x, i in enumerate(iu):
for y, j in enumerate(iv):
pos = [0, 0, 0]
pos[n], pos[u], pos[v] = lo[n], i, j
for comp, f in ((u, fu[x, y]), (v, fv[x, y])):
wt = f * area[x, y]
if wt == 0:
continue
if not dual: # E at the node: edges pos and pos-1 along comp
d = grid.d[comp]
k = pos[comp]
if k == sh[comp] - 1:
q_ = list(pos)
q_[comp] -= 1
add(comp, q_, wt / d[k - 1])
continue
if k == 0:
add(comp, pos, wt / d[0])
continue
rel = d[k] / (d[k] + d[k - 1])
add(comp, pos, wt * (1 - rel) / d[k])
q_ = list(pos)
q_[comp] -= 1
add(comp, q_, wt * rel / d[k - 1])
else: # H at the node: four dual edges round it
cP, cPP = (comp + 1) % 3, (comp + 2) % 3
if (any(pos[b] == sh[b] - 1 for b in range(3))
or pos[cP] == 0 or pos[cPP] == 0):
continue
for dP, dPP in ((0, 0), (1, 0), (1, 1), (0, 1)):
q_ = list(pos)
q_[cP] -= dP
q_[cPP] -= dPP
add(comp, q_, wt / 4 / grid.dual[comp][q_[comp]])
return terms
def describe(op):
g = op.grid
nx, ny, nz = g.shape
lines = [
f"Dimensions\t\t: {nx}x{ny}x{nz} = {op.cells} Cells "
f"({op.cells / 1e6:g} MCells)",
f"Number of PEC edges\t: {sum(op.n_pec)}",
f"Timestep (s)\t\t: {op.dt:g}",
f"Nyquist criteria (TS)\t: {op.nyquist}",
f"Voltage excitations\t: {len(op.exc[0])}",
f"Excitation Length (TS)\t: {len(op.signal)}",
f"Lumped branches\t\t: {len(op.par_L)} parallel L, {len(op.series)} "
"series RLC",
f"Mur ABC edges\t\t: {0 if op.mur is None else len(op.mur[0])}",
"PML sides\t\t: " + (', '.join(
f"{C.AXES[s_['axis']]}{'max' if s_['hi'] else 'min'} ({s_['n']} "
"cells)"
for s_ in op.pml) or 'none'),
"Debye pole edges\t: "
f"{0 if op.debye is None else int((op.debye[3] > 0).sum())}",
f"Conducting sheet edges\t: {getattr(op, 'n_sheet', 0)}",
"Ferrite cells\t\t: " + (f"{op.ferrite.nc} ({op.ferrite.ne} H edges)"
if getattr(op, 'ferrite', None) else '0'),
f"Probes\t\t\t: {len(op.probes)}", f"Field dumps\t\t: {len(op.dumps)}",
f"FDTD timestep is: {op.dt:g} s; Nyquist rate: {op.nyquist} timesteps "
f"@{1 / (2 * op.nyquist * op.dt):g} Hz"
]
return lines + [f"note: {n}" for n in op.notes]