gfem.refinement#

Mesh refinement: error estimates of a solved result, and the refinement loop.

refine_mesh solves, estimates the error, marks the tetrahedra holding most of it (Dörfler marking), bisects them and solves again, until the error estimate meets a tolerance or a cap stops it. error_estimate gives one estimate of a result without refining (a measurement). Estimators are value objects named by what they estimate: the FieldEstimator estimates the field’s error in the energy norm by flux recovery; the QuantityEstimator names one quantity of interest.

refine_mesh logs one INFO record per refinement cycle on the logger gfem.mesh_refinement (silent by default), once the cycle’s outcome is settled: before the refined mesh is solved, or where the loop stops on that cycle. The record’s attributes are the cycle’s RefinementCycle numbers (tetrahedra, dofs, estimate, value, marked; not modes), with cycle (0 is the input mesh), tolerance and stop (the MeshRefinement.stop reason on the cycle the loop stops on, else None). A mesh whose solve failed was never solved, so it has no record; the not-converged warning names that stop.

Classes#

ErrorEstimate

An error estimator's estimate for one solved result.

FieldEstimator

Estimates the error of a result's fields in the energy norm.

MeshRefinement

What refine_mesh returns: the last solved model, its result and history.

QuantityEstimator

Estimates the error of one quantity of a solved result.

RefinementCycle

The numbers of one solved mesh of a MeshRefinement.

Functions#

error_estimate(result, estimator, *, model)

Estimate the error of a solved result, without refining.

refine_mesh(model, problem, *[, estimator, tolerance, ...])

Refine the mesh where the error is, until the error estimate meets a tolerance.

Module Contents#

class ErrorEstimate#

An error estimator’s estimate for one solved result.

Variables:
  • estimator – The estimator that made it.

  • kind – What was estimated: "field" for a FieldEstimator; "capacitance", "s", "omega" or "q" for a QuantityEstimator, after its keyword, "cluster mean" for a tuple omega; for an objective, what it reads ("objective of s"), or "objective of s, lossless rewrite" on a lossless model with lumped ports only, whose estimate also uses the power each port’s column must carry (tighter). Each kind has its own measured effectivity range (verification page).

  • values – Estimated size of the error per frequency (a driven result), per mode (an eigenmode result under a FieldEstimator), or one entry, in the units of tolerance. For a FieldEstimator this is relative to the field’s energy norm. For a QuantityEstimator this is the quantity’s error: relative to the capacitance entry, to omega, to a cluster’s mean omega or to Q, absolute for an S entry. It is never negative and carries no sign or phase. It is an estimate, not a bound.

  • indicators – Each tetrahedron’s share of the estimated error, shape (n_tetrahedra,), in the order of the model’s mesh.tetrahedra, combined over frequencies, terminals, ports and modes; zero outside the solve domain. For a single solve sqrt(sum(indicators**2)) is value for a FieldEstimator. For a QuantityEstimator, indicators**2 is each tetrahedron’s term of the quantity’s error, in its units; sum(indicators**2) is value for a capacitance, and may lie above or below it for an S entry or omega, whose value keeps the curl and mass terms from cancelling.

estimator: Estimator#
indicators: ndarray#
kind: str#
property value: float#

what refine_mesh compares to tolerance.

NaN when any of values is NaN.

Type:

The largest of values

Return type:

float

values: tuple[float, ...]#
class FieldEstimator#

Estimates the error of a result’s fields in the energy norm.

The estimate is relative to the field’s energy norm: 1e-2 means the field is about 1 % off its value on the same geometry with an infinitely fine mesh. Each tetrahedron’s indicator is the distance between the solved electric flux and a smoother flux recovered from it (flux recovery), so no extra solve is needed. It is an estimate, not a bound; it does not include the faceting of curved surfaces or the error left by the linear solve.

With loss, the flux is the total current \(\varepsilon_\mathrm{eff} E\), \(\varepsilon_\mathrm{eff} = \varepsilon_r (1 - i \tan\delta) - i \sigma / (\omega \varepsilon_0)\), and the norm is \(\|\nabla \times E\|^2_{\mu^{-1}} + |k|^2 \int |\varepsilon_\mathrm{eff}| |E|^2\): the conduction current counts, as it does in the field. Weighting the flux error by \(\mathrm{Re}(\varepsilon_\mathrm{eff})^{-1}\) instead overestimates; recovering \(\varepsilon_r E\), as without loss, underestimates without bound under conduction loss.

A dispersive material (a gfem.PermittivityLaw) enters at its permittivity at each solved frequency, lossless or not, \(\mathrm{Re}\,\varepsilon < 0\) included. Where it is exactly zero (a lossless Drude term at its plasma frequency, without conductivity) the flux has no weight, and refine_mesh and error_estimate raise ValueError.

refine_mesh and error_estimate raise gfem.MeshRefinementUnsupportedError at order 1.

class MeshRefinement#

What refine_mesh returns: the last solved model, its result and history.

Not a JAX pytree and not differentiable: differentiate gfem.solve on model instead.

Variables:
  • model – The last solved model (its mesh refined, its design carried).

  • result – That model’s solve result.

  • estimate – That result’s ErrorEstimate; with a tuple of estimators, a tuple of them in the estimators’ order.

  • cycles – One RefinementCycle per solved mesh; cycles[0] is the input mesh.

  • stop – Why the loop stopped: "tolerance", "max_cycles", "max_tetrahedra", "solve failed" or "non-finite estimate" (an estimate is NaN or infinite: it counts as above its tolerance, and the loop warns).

  • converged – Whether estimate.value is at or below the tolerance; with a tuple of estimators, whether every one is at or below its own.

  • tetrahedron_parents – For each tetrahedron of model.mesh, the row of the input mesh’s tetrahedra it lies in.

  • triangle_parents – For each triangle of model.mesh, the row of the input mesh’s triangles it lies in.

transfer(values, region)#

Carry per-element values of a region from the input mesh to model.

Each element of the refined mesh takes the value of the input element it lies in. Plain indexing: a JAX array stays one, and jax.grad passes through it.

Parameters:
  • values (Any) – Shape (n,) or (n, k), one value per element of region on the input mesh, in mesh.elements(region) order.

  • region (str) – A volume (tetrahedra) or surface (triangles) region name.

Returns:

One value per element of region on model.mesh, in model.mesh.elements(region) order.

Raises:
Return type:

Any

converged: bool#
cycles: tuple[RefinementCycle, ...]#
estimate: ErrorEstimate | tuple[ErrorEstimate, ...]#
model: Model#
result: Any#
stop: str#
tetrahedron_parents: ndarray#
triangle_parents: ndarray#
class QuantityEstimator#

Estimates the error of one quantity of a solved result.

Estimates how far one quantity of a solved result (a capacitance entry, an S entry whose source port is excited, one mode’s omega or its Q, the mean omega of a degenerate cluster, or an objective of the result) is from its value on the same geometry with an infinitely fine mesh. ErrorEstimate.kind names which, and each kind has its own measured effectivity range (verification page). The estimate uses the fields already solved, with no extra solve, except for the adjoint duals below. It does not include the faceting of curved surfaces or the error left by the linear solve.

The estimate is a magnitude in the units of tolerance: relative to the capacitance entry, to omega or to Q, absolute for an S entry. It has no sign or phase, and gfem never adds it to the quantity. It is an estimate, not a bound. A diagonal capacitance entry never lies below its value on the meshed geometry: \(C_h \ge C\); an off-diagonal entry may lie on either side.

Give exactly one keyword, named after the result attribute that holds the quantity and indexed the same way.

Example

Refine for S21, then read its estimated error:

est = gfem.QuantityEstimator(s=("p2", "p1"))
ref = gfem.refine_mesh(model, gfem.Driven([5e9]), estimator=est)
ref.result.s["p2", "p1"], ref.estimate.values
Variables:
  • capacitance – Two terminal names (i, j), the entry ElectrostaticResult.capacitance[i, j]; the same name twice for a diagonal entry.

  • s – (to, from) port names, the entry result.s[to, from]; the source port from must be excited (Driven.excite), to may be any port.

  • omega – An index into EigenmodeResult.omega on the first mesh; on each refined mesh the estimate follows the mode whose omega is nearest the previous mesh’s, and refine_mesh raises gfem.DegenerateModeError when that mode is not clearly the same one. Or a tuple of indices naming whole degenerate clusters (result.cluster), stored sorted, whose mean omega is the quantity, estimated relative to its modulus: on each refined mesh the estimate follows as many modes, those nearest the previous mean, and raises gfem.DegenerateModeError when the mean moved further than the previous estimate allows, or another mode is less than twice as far from it as the farthest of them. Ask for at least one mode more than the tuple names.

  • q – An index into EigenmodeResult.q, followed as omega; the estimate is relative to Q. Q’s relative error is \(\cot(\arg\omega)\) times the imaginary part of omega’s relative error, estimated on the same terms, with no extra solve. A lossless mode (infinite Q) raises ValueError.

  • objective – objective(result, model), a real 0-d JAX value: the same function you differentiate. gfem traces it to find what it reads (ErrorEstimate.kind) and raises gfem.MeshRefinementUnsupportedError for anything it does not estimate (feature names it): a field read other than through gfem.power_flow or gfem.region_mean, a point value, a port mode output, a mixture of kinds, a branch on a value it reads (max, min, sort, where) or a custom derivative of its own. In this version an objective of S is estimated (S and its networks: db, y(), z(), renormalize, with_offsets), and of an electrostatic result: of its capacitance (mutual and inverse too), of its region energies, or of potential means (gfem.region_mean of result.potential), and of a driven result’s fields: the power absorbed in a side without ports and with only volume losses of isotropic materials without a permittivity law (-gfem.power_flow), or the means of gfem.region_mean over named regions; and an objective of an eigenmode result’s omega (frequency, q) and bulk_participation, each mode it reads followed as a mode of its own; q_port, participation, sheet_participation, principal_participation and the mode fields raise. A participation needs its mode-field dual: an isolated mode, the direct solver on the CPU and eigen_tolerance at most 1e-10 (in refine_mesh it rides on the eigen solves from the second mesh on; error_estimate factorizes once more per mode). The estimate is absolute, in the objective’s units, and refine_mesh needs its tolerance given. A read row whose port is not excited uses that port’s adjoint dual, as for s, and a read energy, potential mean, absorbed power or field mean its own dual; in refine_mesh each is solved once more on the first mesh and rides on the solves after it.

Raises:
  • TypeError – Not exactly one keyword is given, or a value has the wrong type (a tuple for q: the Q of a cluster is not estimated; an objective that is not callable).

  • ValueError – omega or q is negative, or a tuple omega names fewer than two modes or a mode twice.

refine_mesh and error_estimate raise gfem.MeshRefinementUnsupportedError for entries with no verified estimate. An S entry and every objective of a driven result raise it before any solve on a model with an gfem.Impedance or gfem.Absorbing surface (feature "impedance or absorbing surface"), with a lumped port whose face borders materials of different mu_r ("lumped port spanning a permeability contrast"), or with a permittivity law at \(-20 < \mathrm{Re}\,\varepsilon < 0\) at a solve frequency ("plasmonic permittivity"); refine those with FieldEstimator. The omega of a mode bound to a permittivity law region where \(\mathrm{Re}\,\varepsilon < 0\) at the mode raises it when it is estimated. Both estimators also raise it at order 1. For a lossy mode the omega estimate covers the complex omega; q estimates Q, and raises on a mode of a model with a permittivity law (feature "dispersive eigenmode"), a second-order absorbing boundary, a complex mu_r or loss inside an anisotropic material ("lossy eigenmode"). Every quantity of a mode of a model with a gfem.WavePort (omega, q and objectives) raises it before any solve ("wave port eigenmode"): refine such a mode with FieldEstimator. An S entry (to, from) whose port to is not excited needs that port’s adjoint dual: refine_mesh adds it to each of its solves, one more right-hand side with its options; error_estimate on a finished result factorizes once more per frequency, with the direct solver at the result’s order, so estimate a large model through refine_mesh (max_cycles=0).

capacitance: tuple[str, str] | None = None#
objective: Callable[[Any, Model], Any] | None = None#
omega: int | tuple[int, ...] | None = None#
q: int | None = None#
s: tuple[str, str] | None = None#
class RefinementCycle#

The numbers of one solved mesh of a MeshRefinement.

With a tuple of estimators, estimate and value are tuples, one entry per estimator in the given order.

Variables:
  • tetrahedra – The mesh’s tetrahedron count.

  • dofs – The field’s coefficient count (one solve’s unknowns).

  • estimate – The error estimate’s value on this mesh.

  • value – The quantity of a QuantityEstimator on this mesh: the capacitance entry in farads, a tuple of the S entry per frequency, the followed mode’s complex omega in rad/s, its Q, the followed cluster’s mean complex omega, or an objective’s value; None for a FieldEstimator.

  • marked – How many tetrahedra Dörfler marking picked on this mesh; 0 when the loop stopped on it before marking.

  • modes – For an eigenmode quantity, each mode index the estimators name on the first mesh, mapped to the index of the mode followed to this mesh (read-only); empty otherwise. A cluster’s members, in order, map to the modes followed as the cluster, in order.

dofs: int#
estimate: float | tuple[float, ...]#
marked: int#
modes: Mapping[int, int]#
tetrahedra: int#
value: Any#
error_estimate(result, estimator, *, model)#

Estimate the error of a solved result, without refining.

No solve is needed, except for an S entry, or an objective reading a row of S, whose port to is not excited: its adjoint dual factorizes the system once more per frequency, with the direct solver at the result’s order (the result does not record its solve options). An objective reading an electrostatic energy or a potential mean factorizes once more the same way, for all its duals at once, and one reading a driven field through gfem.power_flow or gfem.region_mean once more per frequency it reads. On a large model, estimate through refine_mesh with max_cycles=0, whose adjoint rides on its own solve with your options (from its second mesh on, for an objective).

Example

The field error of a capacitance solve:

result = gfem.solve(model, gfem.Electrostatic(terminals=["t1"]))
est = gfem.error_estimate(result, gfem.FieldEstimator(), model=model)
est.value, est.indicators  # relative energy error, per tetrahedron
Parameters:
  • result (Any) – A result of gfem.solve on model: electrostatic, eigenmode (every mode is estimated), or a uniform driven sweep solved with keep_fields=True (every kept field).

  • estimator (Estimator) – FieldEstimator(), or a QuantityEstimator naming an entry of result (its omega index is a mode of result).

  • model (Model) – The model the result was solved on (its materials weight the fields).

Returns:

The estimate, with NumPy values.

Raises:
  • TypeError – An argument has the wrong type (a tuple of estimators too: call it once per quantity), or a QuantityEstimator names a quantity of another result type.

  • KeyError – A QuantityEstimator names no terminal or port of the result.

  • ValueError – The result was not solved on model’s mesh, or is a driven result without the fields of every frequency (solve with keep_fields=True); a QuantityEstimator names a source port that was not excited, a mode the result does not hold, the Q of a lossless mode, or a cluster with no other mode in the result; a permittivity law is zero at a driven frequency.

  • MeshRefinementUnsupportedError – The estimator or the result has no estimate in this version of gfem (feature names what): an adaptive sweep, a periodic model, a driven result with sources (feature "incident field" or "point dipole"), a driven or eigenmode result on a model with a gfem.PML, another result type, a result solved at order 1, a quantity entry with no verified estimate (an S entry read at a lumped port with no resistance, whose row is undefined; an S entry or a driven objective beside an impedance or absorbing surface, a lumped port across a permeability contrast or a permittivity law at \(-20 < \mathrm{Re}\,\varepsilon < 0\); a plasmon-bound mode; see QuantityEstimator), or an objective reading what it may not.

  • DegenerateModeError – A QuantityEstimator names a mode of a degenerate cluster, or one within the default SolverOptions.cluster_rtol of another mode (the message names the cluster); a cluster omega=(i, ...) holds part of a degenerate cluster, or another mode lies less than twice as far from its mean as its farthest member.

  • NotImplementedError – model holds a metal-dielectric blend (MaterialField.interpolate with a permittivity law), which is supported on the driven uniform sweep only.

  • DistributedUnsupportedError – The result was solved across ranks.

  • NonDifferentiableError – A model or result leaf is a JAX tracer, or the call is inside jax.jit.

Return type:

ErrorEstimate

refine_mesh(model, problem, *, estimator=FieldEstimator(), tolerance=None, error_fraction=0.5, max_cycles=10, max_tetrahedra=None, options=None, comm=None)#

Refine the mesh where the error is, until the error estimate meets a tolerance.

Each refinement cycle solves the problem, estimates the error, stops if the estimate is at or below tolerance, marks the fewest tetrahedra holding error_fraction of the squared error (Dörfler marking), bisects them and their neighbours until the mesh conforms (new nodes at edge midpoints, physical groups and imported facets kept), and carries the model’s per-element design (MaterialField values, sheet fills) to the children. Cycle 0 solves the input mesh.

With a tuple of estimators, several quantities refine one mesh: every one is estimated on every mesh, the marking sums each quantity’s indicators**2 divided by its tolerance over the quantities still above it, and the loop stops when every one meets its tolerance. Modes named by several estimators are followed once each.

A driven problem is solved with keep_fields=True whatever it asks: the estimate reads every frequency’s field of every excited port, and result keeps them. Its low-frequency floor is checked once, on the returned mesh, not on every cycle.

Example

Refine a capacitance solve to a 1 % field error:

ref = gfem.refine_mesh(model, gfem.Electrostatic(terminals=["t1"]))
ref.model, ref.result, ref.estimate.value, ref.stop

Refine for S21 and S11 at once, each to its own tolerance:

estimators = (
    gfem.QuantityEstimator(s=("p2", "p1")),
    gfem.QuantityEstimator(s=("p1", "p1")),
)
ref = gfem.refine_mesh(
    model, gfem.Driven([5e9]), estimator=estimators, tolerance=(1e-4, 1e-3)
)
s21_estimate, s11_estimate = ref.estimate
Parameters:
  • model (Model) – The device, with concrete values.

  • problem (Electrostatic | Driven | Eigenmode) – An Electrostatic problem, a Driven problem on a uniform sweep (lumped or wave ports), or an Eigenmode problem. The estimate of a driven run is the worst frequency’s, of an eigenmode run the worst mode’s.

  • estimator (Estimator | tuple[QuantityEstimator, ...]) – FieldEstimator(), a QuantityEstimator naming a quantity of problem, or a tuple of distinct QuantityEstimator objects; the record then holds tuples, one entry per estimator in this order.

  • tolerance (float | tuple[float, ...] | None) – The error estimate to reach, one float for every estimator or a tuple with one per estimator; None is 1e-2, except for an objective, whose tolerance is in its own units and must be given (at least 10 x the solve tolerance times the objective’s first-order sensitivity, checked on the first estimate). Relative to the field’s energy norm for a FieldEstimator; for a QuantityEstimator relative to the capacitance entry, to omega, to a cluster’s mean omega or to Q, absolute for an S entry. At least 10 times options.tolerance (options.eigen_tolerance for an Eigenmode; for Q times \(\cot(\arg\omega)\), about 2Q, checked on the first solve), since the estimate does not include the linear solve’s error. Each tolerance is checked on its own.

  • error_fraction (float) – Dörfler’s fraction, in (0, 1]: the share of the summed squared error indicators the marked tetrahedra hold.

  • max_cycles (int) – How many times the mesh may be refined; 0 solves and estimates only.

  • max_tetrahedra (int | None) – A cap on the refined mesh’s tetrahedra: a bisected mesh above it is discarded and the loop stops on the last solved one. None sets no cap; each cycle grows the mesh, by about 1.6 times on the first cycle and 1.25 times on later ones.

  • options (SolverOptions | None) – The numerics of every solve; None is SolverOptions().

  • comm (Any) – As for gfem.solve; mesh refinement runs on one process.

Returns:

The last solved model, its result and estimate (a tuple with a tuple of estimators), and one RefinementCycle per solved mesh.

Warns:
  • MeshRefinementNotConvergedWarning – The loop stopped on a cap or a failed solve with an estimate above its tolerance; it names each such quantity.

  • LowFrequencyWarning – A frequency of a driven problem is below the returned mesh’s low-frequency floor.

  • MeshQualityWarning – The input mesh’s nodes have moved and an element fell far below its imported quality.

Raises:
  • TypeError – An argument has the wrong type, a QuantityEstimator names a quantity of another problem type, or a tuple of estimators holds a FieldEstimator.

  • KeyError – A QuantityEstimator names no terminal or port of the problem.

  • ValueError – A parameter is out of range; a tuple of estimators is empty or names a quantity twice, or the tolerances do not match the estimators one to one, or a cluster shares a mode with another estimator; a tolerance is below 10 times the solve tolerance (for Q, times \(\cot(\arg\omega)\)); a QuantityEstimator names a source port that is not excited, a mode index at or above n_modes, a cluster of at least n_modes modes (one more is needed to tell it apart), or the Q of a lossless mode; a permittivity law is zero at a driven frequency.

  • MeshRefinementUnsupportedError – The problem or the estimator has no mesh refinement (feature names what): an adaptive sweep, a port mode problem, a periodic model or a Bloch wave vector, a driven problem with sources (feature "incident field" or "point dipole"), a driven or eigenmode problem on a model with a gfem.PML (before any solve), options.order=1 (the "fast" preset), a quantity entry with no verified estimate (an S entry read at a lumped port with no resistance, whose row is undefined; an S entry or a driven objective beside an impedance or absorbing surface, a lumped port across a permeability contrast or a permittivity law at \(-20 < \mathrm{Re}\,\varepsilon < 0\), all before any solve; a plasmon-bound mode on the first estimate, after the first solve; see QuantityEstimator), an objective reading what it may not (on the first estimate), or frequency_workers above 1 for an estimate that solves an adjoint dual (an unexcited to or an objective’s dual), which rides on the forward solve.

  • DegenerateModeError – The mode a QuantityEstimator follows is not alone: another mode lies within options.cluster_rtol of it, or shares its result.cluster label (the message names the cluster, to estimate its mean with omega=(i, j, ...)). Or, on a refined mesh, the nearest mode is not clearly the followed one: a second mode is less than twice as far from the previous frequency, or the nearest moved further than the previous estimate allows (the mode probably left the solved modes: ask for more modes or start from a finer mesh). A cluster omega=(i, ...) raises it when it holds part of a labelled cluster, when another mode lies less than twice as far from its mean (on the first mesh) or from its previous mean as its farthest member, or when its mean moved further than the previous estimate allows. Or two modes named on the first mesh reached one mode.

  • NotImplementedError – model holds a metal-dielectric blend (MaterialField.interpolate with a permittivity law), which is supported on the driven uniform sweep only.

  • DistributedUnsupportedError – Launched on more than one rank.

  • MeshQualityError – The input mesh’s nodes have moved and an element is inverted.

  • NonDifferentiableError – A model or problem leaf is a JAX tracer, or the call is inside jax.jit. Under jax.grad or jax.vmap with concrete inputs it runs; refine outside the transformed function, then differentiate gfem.solve on the refined model.

  • LinearSolverConvergenceError, EigenmodeConvergenceError – The solve on the input mesh failed. On a later cycle the loop stops instead (stop="solve failed").

Return type:

MeshRefinement