Low-frequency copper currents, capacitance and fields

kicad2ems.pcbqs.mqs.MQS meshes explicitly selected copper, vias and terminals. The default magnetic model solves divergence-free loop currents with sheet DC resistance and partial inductance. No infinite ground plane or image is added: include the return copper in nets. Geometry inputs and mesh sizes use mm; frequencies use Hz; field observation coordinates use m.

from pcbqs.mqs import MQS

q = MQS(board, nets={'VIN', 'GND', 'SW'}, terminals=terminals,
        region=(xmin, ymin, xmax, ymax), dmax=0.5)
q.source('hot', 'VIN_pad', 'PGND_pad', part_h=0.5)
q.element('Cin', 'Cin_1', 'Cin_2', C=10e-6, ESR=3e-3, ESL=0.4e-9)
r = q.solve([1e5, 1e6, 1e7])
Z = r.z['hot']                    # includes lumped part impedances
Zc = r.zc['hot']                  # copper contribution in the magnetic model
H = q.h_field(r, 0, points_m)     # exact filaments, refined triangle quadrature

r.i holds branch currents in A, in the order RWG edges, via segments, parts. amps={'hot': 2.0} sets the source current; every source defaults to 1 A. Sources act simultaneously; their reported impedances include coupling from the other driven sources. A source set to zero has an undefined impedance (nan) but still participates as an open current-source branch. The AC solvers require finite, strictly positive frequencies; use pdn for DC.

Integration and speed

The static kernel classifies tiled triangle pairs within near times the sum of their bounding radii (default 3). These pairs use analytic source integration and a six-point observation rule; very close pairs subdivide the observation triangle into four (outer_levels=1). The remaining pairs use a three-point product rule. Each unordered pair is evaluated once, retaining both observation and source moments to enforce reciprocity. Coordinates are shifted locally before combining RWG moments to reduce cancellation.

Use near=float('inf') for the all-analytic reference path. Use outer_levels=2 to check close-pair quadrature convergence, and reduce dmax to check mesh convergence. Analytic refers to the inner integral; the outer integral remains numerical. Resistance assembly and loop projection use sparse matrices. Resistance stays sparse through branch assembly. Inductance remains in its copper blocks, without dense padding or duplicate branch copies. Copper matrices are reused when sources or lumped parts are added. Dense inductance and triangle-moment storage are still quadratic in mesh size.

Filling defaults to the compiled OpenMP backend when available, with a multithreaded NumPy fallback. fill_backend='numpy' selects the serial reference; fill_workers controls CPU threads. Third-party backends share the same double-precision pair interface. See backend configuration and extension protocol for thread defaults, bounded scratch memory and scaling benchmarks.

The reproducible CPU benchmark is:

OPENBLAS_NUM_THREADS=2 python tools/pcbqs/benchmark_mqs.py --dmax 0.8

On the development environment, a 974-triangle example took 1.20 s for the hybrid fill versus 2.08 s for the refined all-analytic reference, with a 0.005% relative Frobenius error in inductance. A separate 2,474-triangle sheet comparison against revision 6be2bc3 took 6.12 s versus 19.26 s (3.1 times faster, including the more accurate close terms). These are small synthetic examples, not whole-board benchmarks.

Fast field planes and volumes

H = q.h_grid(r, [0, 1, 2], x_m, y_m, z_m)
# shape: (nx, ny, nz, 3, 3 frequencies)
H0 = q.h_grid(r, 0, x_m, y_m, z_m)  # (nx, ny, nz, 3)
H, info = q.h_grid(r, [0, 1, 2], x_m, y_m, z_m,
                   rtol=0.02, max_refine=8, return_info=True)

x_m and y_m must be increasing uniform grids; z_m contains absolute heights, including heights below or between the copper layers. Currents are conservatively deposited, and FFT linear convolution applies the free-space Biot–Savart kernel without periodic images. The internal source grid expands to include all copper even when the requested window is small. Filaments remain analytic. Current spectra and field kernels serve all requested frequencies/heights. No implicit ground image is used.

Grid spacing should be well below the distance to the nearest sheet; refine until the field converges. refine=2 halves the internal deposition spacing while preserving output coordinates. With rtol, successive refinements must agree within that fraction of the peak component at each height and frequency, or the call raises at max_refine. This checks grid convergence, not mesh or model accuracy. info records the refinement and relative changes. Spectra are batched to bound working memory. The near-field demo uses these checks for its planes and volume by default. Evaluation exactly on a sheet is rejected. For isolated points and checks use h_field. In the benchmark above, 3,813 points at three frequencies took 0.078 s by FFT versus 2.75 s directly (35 times faster), with 0.38% maximum error relative to the peak reference field.

Distributed capacitance (PEEC)

q = MQS(board, nets=nets, terminals=terminals, dmax=0.5,
        capacitance=True, er=4.0)
q.source('hot', 'VIN_pad', 'PGND_pad')
r = q.solve([1e3, 1e6])
r.charge                         # (nf, n_nodes), C
r.potential                      # (nf, n_nodes), V relative to infinity
E = q.e_field(r, 0, points_m)     # Coulomb E, V/m
C, node_labels, terminal_labels = q.capacitance_matrix()

The default electrostatic model uses a homogeneous dielectric, with explicitly specified real er (default 1). The reciprocal 1/R kernel supplies the Galerkin coefficient-of-potential matrix P. Charge density is constant per triangle; the triangles grouped into one terminal or via fan share one charge density. Keep terminal regions local to their physical pads so that the remaining copper can resolve edge charge and current distribution.

With branch incidence A positive at the starting node and exp(+jwt):

Z i = A.T P q,    A i + jw q = 0.

The sparse loop/tree formulation separates each passive component’s electrostatic equilibrium and scales the tree-current correction by jw. This avoids recovering tiny conduction charges by subtraction of nearly equal currents at low frequency. A source between disconnected pieces of copper can drive displacement current. Series RLC parts remain available. r.zc is None for PEEC; use the full source impedance r.z.

PEEC caches its topology, electrostatic preparation and projected R/L matrices until parts change. Frequency LU factors are reused across excitation changes within an LRU budget (factor_cache_bytes, default 64 MiB; 0 disables storage). This budget covers factors, not the model’s dense matrices. Construct a new model when changing geometry or material settings. capacitance_matrix() has a scalar-only integration path and does not build magnetic matrices.

tools/benchmark_peec.py measured 0.23 s for capacitance-only extraction on 432 triangles, 0.57 s for the first three-frequency solve after extraction, and 0.015 s on a changed excitation, with no additional factorizations and 17.2 MiB cached.

capacitance_matrix() returns the Maxwell capacitance matrix in F, with one row/column per connected component of copper and vias (lumped parts do not join components). The two label outputs map mesh nodes and terminal names to those conductors. Potentials are relative to infinity: row sums need not vanish. A floating two-conductor capacitance is 1 / (e @ solve(C, e)), with e=[1,-1], rather than C[0,0].

e_field uses exact edge integrals and solid angles for the constant triangle charges. It returns only the Coulomb field, excluding inductive -jw A. Observe away from charged surfaces, which have a discontinuous normal field.

Layered dielectric electrostatics and loss

q = MQS(board, nets=nets, terminals=terminals, capacitance=True,
        dielectric='stack', dielectric_tol=1e-8)

dielectric='stack' uses the board’s contiguous dielectric slabs (z0, z1 in mm, er, tand) as laterally infinite materials. Copper must lie on slab interfaces. Exterior half spaces are air, overridable with stack.top_er and stack.bottom_er. Specify er only for the homogeneous model. There is no implicit PEC ground. Image charges account for reflections and transmission at every dielectric interface, with complex er*(1-j*tand) for constant dielectric loss. Maxwell C is therefore complex in a lossy stack.

Close images retain analytic source integration; smooth image sums are tabulated and integrated by the product rule with analytic close-pair corrections. dielectric_tol cuts off individual ray amplitudes, not a bound on the final field error: tighten it and refine the mesh for convergence. Excessive image growth raises explicitly. High-contrast or many-layer stacks can be expensive. Layered e_field evaluates the transmitted/reflected images and requires observation points away from dielectric interfaces, where the normal E is discontinuous. Material frequency dispersion is not yet included.

Conductor loss

q = MQS(board, nets=nets, terminals=terminals,
        conductor_loss='slab', conductor_faces=1)

The default remains conductor_loss='dc'. With conductor_loss='slab' the copper is two face sheets (below) unless conductor_faces=1, which is one sheet with the complex finite-thickness impedance u*coth(u)/(sigma*t), u=sqrt(j*w*mu0*sigma)*t: the current on one face, its internal inductance and skin resistance, tending to 1/(sigma*t) at DC. (conductor_faces is that one sheet’s: with face sheets it had been ignored, so 1 and 2 gave one model.) Via barrel resistance remains DC. Both MQS and PEEC use this option. share_kernels(other) gives a model another’s kernels of the same mesh, all of them (copying them one by one had left the faces’ loss terms out).

Two face sheets (the slab’s default)

q = MQS(board, nets=nets, terminals=terminals, conductor_loss='slab', matrix_backend='hierarchical')

Each layer’s copper becomes two sheets, at its faces (z ∓ t/2). The copies of a triangle share one node and each RWG edge carries two parallel currents. The faces are coupled through the copper by the slab’s exact 1D two-port, Zs*[[coth kt, csch kt], [csch kt, coth kt]] with k = sqrt(j*w*mu0*sigma) and Zs = k/sigma (conductor.face_impedance(..., vacuum=False)), uncorrected: the partial inductance’s own share of the field between the faces is left as filled. (A per-pair subtraction of it, removed on 2026-11-10, was right only far from a plane: +200% R at 100 MHz with a plane 0.1 mm away, while the uncorrected faces are within about 10% everywhere tested.) The external field decides how the current divides between the faces, which is the proximity effect a single sheet’s slab cannot give. DC resistance and low-frequency inductance are unchanged.

AC resistance against FastHenry (validation/pcbqs/mqs_fasthenry.py, review C14), 10 / 100 MHz:

Case

One sheet

Two face sheets

Strip loop, dmax 0.0625

−9.5 / −9.1%

−1.1 / +3.5%

Trace over plane, dmax 0.18

−18.8 / −29.7%

−12.5 / −12.5%

Inductance is 2–3% low with two sheets, against under 1% with one. The rest of the plane case is current on the copper’s edges and side walls, which the faces don’t carry. It doubles the unknowns, so use the compressed backend. With dielectric='stack' the faces sit on their layer’s interfaces (from_board_thick). With capacitance a node’s charge sits on the face that faces the other conductor (peec.node_potential), validated against FasterCap (validation/pcbqs/README.md).

Compressed backend without capacitance

matrix_backend='hierarchical' now also solves the inductance-only model (mqs_iterative.py). It runs GMRES on the loop currents, applying the compressed inductance as products, with no dense loop matrices. The preconditioner inverts the loop system exactly for a block-diagonal branch impedance through one sparse graph-Laplacian solve per frequency. The blocks are each branch’s own impedance, or a face pair’s 2×2 block. It matches the dense solve to 1e-5 or better.

Case

Dense

Compressed

Strip loop, 11,854 triangles

20.5 s

2 s, 0.4 GB

Strip loop, 47,548 triangles

out of memory (32 GB)

13 s, 1.7 GB

Two face sheets, 96k triangles

—

2 min, 7.5 GB

Port extraction for circuits (mqs_iterative.port_matrix) picks its route from the problem size (port_method):

  • Direct. The dense loop matrices are built from the compressed inductance by products (loop_matrices) and factorised per frequency. It is chosen when the loops number at most DIRECT_LOOPS (8,000) and also at most PRODUCTS_PER_SOLVE (60) × ports × frequencies, the point where building the matrix costs fewer products than iterating.

  • Iterative. All ports advance in lockstep through GMRES, one compressed product per step for every port, warm-started across frequencies.

With two face sheets the iteration uses a two-level preconditioner (mqs_precond.FaceLoops). The loops split into common-mode loops (both faces of a branch carrying the same current) and difference loops (current down one face and back along the other). The common-mode block, which holds the long-range inductance, is formed densely and solved exactly. The difference loops are local, so a sparse solve with each branch’s own impedance and its nearest mutuals covers them. If the split is not available (no face pairs, or too many common-mode loops) it falls back to the graph preconditioner. Quasistatic.port_solver ('auto', 'direct', 'iterative') and port_preconditioner ('auto', 'graph', 'faces') override the choice.

Validation and limits

Tests cover Wheeler’s inductance formula, image-theory magnetic fields and return currents, hybrid/reference agreement, reciprocity, positive magnetic energy, coordinate translation, close-integral convergence, FFT/direct agreement above and below copper, parallel-plate capacitance and E, permittivity scaling, Maxwell capacitance, lumped/distributed capacitance in parallel, charge continuity, and the PEEC limit approaching MQS down to 1 mHz. Layered images are checked against the independent spectral network; tests also cover series dielectrics, normal displacement continuity, positive dielectric loss and the slab’s DC/internal-inductance/skin limits.

Both models are quasi-static: no retardation or radiation. Via charges and part-body charges are omitted. Via inductance uses parallel filaments; part/copper mutual inductance is omitted, and raised part fields use a single horizontal filament. PEEC currently uses a dense branch solve, so its cost is higher than the loop-only magnetic model. Resolved conductor proximity effects, compressed whole-board solves, and validation of the complete model near wavelength/10 remain future work. See the CM5 U702 benchmark for a real cropped converter case.

All three synthetic converter layouts also complete with converged FFT dumps: the good/far/slot cases took approximately 1.3/4.7/3.4 s for planes and volume, with 4,140/5,326/5,588 triangles respectively. These runs use the demo’s unchanged meshes, RLC assumptions and source waveform.

The maintained tools/pcbqs/nearfield_demo.py now reruns those same geometries and waveform with layered PEEC and conductor-loss comparisons:

OPENBLAS_NUM_THREADS=4 OMP_NUM_THREADS=8 python tools/pcbqs/nearfield_demo.py out/

It compares MQS/DC-sheet, PEEC/DC-sheet and PEEC with one- and two-face slabs. The one-face slab is the primary field result; the face comparison is a model sensitivity, not a rigorous error bound. Lateral current redistribution and its loss are solved, while through-thickness proximity currents are not resolved. The board’s dielectric stack and loss tangent supply distributed capacitance; the explicit 10 µF capacitor retains its original ESR and ESL. Reported copper resistance is computed from copper dissipation per squared source-current amplitude, separate from capacitor ESR and dielectric loss. It does not subtract a lumped capacitor impedance from the PEEC port impedance.

The script writes per-model power-balance/charge-continuity checks, floating VIN–GND capacitance, current/charge and mesh pictures, and harmonic H dumps. Summed losses cover only the selected AC harmonics, excluding DC and omitted harmonics. --plot-only regenerates pictures from saved results with the same mesh controls. No KiCad or mom25d installation is needed for this synthetic example. Shared immutable geometry kernels are reused between model variants; their timing records identify that reuse.

Converter command and GUI

python -m kicad2ems.pcbqs.mqs --describe --json
python -m kicad2ems.pcbqs.mqs board.kicad_pcb --list-converters
python -m kicad2ems.pcbqs.mqs board.kicad_pcb --converter U702 --vin +5V \
  --capacitors C704,C705,C706 --fsw 500000 --current 3 --duty .33 \
  --heights 1,3,10 --fill-backend openmp --fill-workers 8 --out nearfield_U702

The command reads KiCad through kicad2ems, or a previously exported board JSON. It identifies candidate converters two ways: a regulator IC from power-inductor/IC switch-net connectivity and input-to-ground capacitors; and a discrete switching cell, a transistor or diode up from a switch node to a net with capacitors to ground and one down to ground (at least one of the two a transistor). The cell’s upper part names it, and its input loop runs from those capacitors through the upper part, the switch node’s copper and the lower part (a 10 mΩ conductor) back to ground: a buck’s switch and diode or two switches, a boost’s diode and switch (its loop is the output’s), each leg of a half or full bridge. A flyback (its loop through a transformer) and an inverting buck-boost (through both capacitors) are not found. A cell’s capacitors are those within --cap-radius, else every capacitor of its loop’s net. A unique candidate and supply can be selected automatically; ambiguous candidates require --converter and/or --vin. --inductor, --ground, --capacitors and --cap-radius refine selection. Only populated parts with usable copper pads participate. Discovery is a buck input-loop heuristic, not recognition of arbitrary converter topologies.

The selected regulator’s input and ground pads define the source. Input capacitors close the loop through their copper. Their values come from the board; --esr, --esl and --part-height are explicit modeling assumptions. The copper and scan region are the selected pad extent plus --margin. --dmax and --fine control coarse and local mesh spacing. This model uses DC sheet loss, explicit return copper and the magnetic MQS solve.

--current is the assumed input-pulse amplitude (approximately buck load current), --duty its duty fraction, and --edge-time its smoothing time. Alternatively --vin-volts and --vout set ideal buck duty Vout/Vin. Harmonic amplitudes are peak A: 2 I D |sinc(n D) sinc(n fsw tr)|. The model omits switch-node E and output-inductor core/winding leakage. --spectrum FILE takes the harmonics from a file in place of that pulse: lines of f_Hz, A (peak), as a circuit run writes for each part on its supply (supply-<part>.csv). Its lowest frequency is the switching frequency, --harmonics still says which are solved, and the report lists the assumed pulse beside them. --circuit prints the selected converter as a circuit model for kicad2ems.pcbqs.circuit and stops; a run writes the same as circuit-model.json (From one tool to the next).

Outputs are mqs.json (selection, settings, copper R/L, complex dipole moment, peak H per harmonic/height, fill metadata, FFT convergence and assumptions), mesh.npz, H-map figures, spectrum.png, and standard frequency-domain H dumps under mqs/exc_converter. Multiple heights also produce a rectilinear volume through those heights. Dump coordinates are mm and fields are complex A/m; summary dipole moments are A m². The GUI’s Near field page obtains its settings from --describe --json, runs the command in a separate process and opens its field results in the Viewer, including Cut and 3D views.

Use successive mesh and crop refinements to check physical convergence; --field-tol only controls FFT deposition-grid convergence. Whole-board dense storage, crop/hardware validation and resolved package models remain open.

Layout, component shapes and mesh preview

python -m kicad2ems.pcbqs.mqs board.kicad_pcb --converter U702 --vin +5V --preview --out preview meshes the selected crop and exports mqs-preview.json, mqs_board.json and mqs_mesh_mqs.npz without matrix filling, GPU initialization or solving. The GUI Preview mesh button writes to a separate preview/ subfolder and opens Layout / mesh, with layer and mesh selectors. Its Summary reports triangle counts, longest edges and minimum angles per layer. Preview does not require capacitor values or a valid switching operating point.

Solved runs also export the same layout and standard 3D layer mesh. The field viewer and the Near field page’s Field overlay tab project a selected copper layer under horizontal scans, regardless of scan height. Opacity, layer and component controls do not change the sampled field. Cyan identifies simulated copper, grey the surrounding layout, and gold the selected converter/capacitors. This identifies model participation, not a thresholded current-density map. PNG/animation exports retain overlay settings. API users can pass layout= style options to kicad2ems’s field renderer/animation writer.

Component silhouettes use nominal dimensions inferred from package names where available, otherwise pad envelopes and an assumed height. These display-only bodies are shown in 2D/3D, include bottom-side placement, and do not add electrical parts or electromagnetic package solids. Their size source is retained in the layout metadata.

Use board and rail in Power Integrity shares the original board, input rail and return reference. Check supply voltage, source and DC loads before running the separate analysis. See the validation guide for convergence and low-frequency reference checks that do not require a whole-board openEMS simulation at the same frequency.

Nonlinear operational circuits

python -m kicad2ems.pcbqs.circuit simulates any circuit of parts, nodes and drives (switches, MOSFET or vendor subcircuits in ngspice, component parasitics, coupled windings), with the board’s copper between its parts’ pads as a passive broadband multi-port model (--copper) whose periodic terminal currents drive the MQS copper field response (--fields). See circuits; the wpthb bridge and its coupled receiver are data/wpthb_bridge.json.