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#
An error estimator's estimate for one solved result. |
|
Estimates the error of a result's fields in the energy norm. |
|
What |
|
Estimates the error of one quantity of a solved result. |
|
The numbers of one solved mesh of a |
Functions#
|
Estimate the error of a solved result, without refining. |
|
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 aFieldEstimator;"capacitance","s","omega"or"q"for aQuantityEstimator, after its keyword,"cluster mean"for a tupleomega; 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 oftolerance. For aFieldEstimatorthis is relative to the field’s energy norm. For aQuantityEstimatorthis is the quantity’s error: relative to the capacitance entry, toomega, to a cluster’s meanomegaor 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’smesh.tetrahedra, combined over frequencies, terminals, ports and modes; zero outside the solve domain. For a single solvesqrt(sum(indicators**2))isvaluefor aFieldEstimator. For aQuantityEstimator,indicators**2is each tetrahedron’s term of the quantity’s error, in its units;sum(indicators**2)isvaluefor a capacitance, and may lie above or below it for an S entry oromega, whosevaluekeeps the curl and mass terms from cancelling.
- estimator: Estimator#
- property value: float#
what
refine_meshcompares totolerance.NaN when any of
valuesis NaN.
- 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, andrefine_meshanderror_estimateraiseValueError.refine_meshanderror_estimateraisegfem.MeshRefinementUnsupportedErrorat order 1.
- class MeshRefinement#
What
refine_meshreturns: the last solved model, its result and history.Not a JAX pytree and not differentiable: differentiate
gfem.solveonmodelinstead.- 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
RefinementCycleper 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.valueis 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’stetrahedrait lies in.triangle_parents – For each triangle of
model.mesh, the row of the input mesh’strianglesit 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.gradpasses through it.- Parameters:
values (Any) – Shape
(n,)or(n, k), one value per element ofregionon the input mesh, inmesh.elements(region)order.region (str) – A volume (tetrahedra) or surface (triangles) region name.
- Returns:
One value per element of
regiononmodel.mesh, inmodel.mesh.elements(region)order.- Raises:
RegionNotFoundError –
regionis not a region of the mesh.ValueError –
valuesdoes not hold one value per element.
- Return type:
Any
- cycles: tuple[RefinementCycle, ...]#
- estimate: ErrorEstimate | tuple[ErrorEstimate, ...]#
- result: Any#
- 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
omegaor its Q, the meanomegaof a degenerate cluster, or an objective of the result) is from its value on the same geometry with an infinitely fine mesh.ErrorEstimate.kindnames 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, toomegaor 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 entryElectrostaticResult.capacitance[i, j]; the same name twice for a diagonal entry.s –
(to, from)port names, the entryresult.s[to, from]; the source portfrommust be excited (Driven.excite),tomay be any port.omega – An index into
EigenmodeResult.omegaon the first mesh; on each refined mesh the estimate follows the mode whose omega is nearest the previous mesh’s, andrefine_meshraisesgfem.DegenerateModeErrorwhen 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 raisesgfem.DegenerateModeErrorwhen 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 asomega; 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) raisesValueError.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 raisesgfem.MeshRefinementUnsupportedErrorfor anything it does not estimate (featurenames it): a field read other than throughgfem.power_floworgfem.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 (mutualandinversetoo), of its region energies, or of potential means (gfem.region_meanofresult.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 ofgfem.region_meanover named regions; and an objective of an eigenmode result’somega(frequency,q) andbulk_participation, each mode it reads followed as a mode of its own;q_port,participation,sheet_participation,principal_participationand the mode fields raise. A participation needs its mode-field dual: an isolated mode, the direct solver on the CPU andeigen_toleranceat most 1e-10 (inrefine_meshit rides on the eigen solves from the second mesh on;error_estimatefactorizes once more per mode). The estimate is absolute, in the objective’s units, andrefine_meshneeds itstolerancegiven. A read row whose port is not excited uses that port’s adjoint dual, as fors, and a read energy, potential mean, absorbed power or field mean its own dual; inrefine_mesheach 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; anobjectivethat is not callable).ValueError –
omegaorqis negative, or a tupleomeganames fewer than two modes or a mode twice.
refine_meshanderror_estimateraisegfem.MeshRefinementUnsupportedErrorfor entries with no verified estimate. An S entry and every objective of a driven result raise it before any solve on a model with angfem.Impedanceorgfem.Absorbingsurface (feature"impedance or absorbing surface"), with a lumped port whose face borders materials of differentmu_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 withFieldEstimator. Theomegaof 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 theomegaestimate covers the complexomega;qestimates Q, and raises on a mode of a model with a permittivity law (feature"dispersive eigenmode"), a second-order absorbing boundary, a complexmu_ror loss inside an anisotropic material ("lossy eigenmode"). Every quantity of a mode of a model with agfem.WavePort(omega,qand objectives) raises it before any solve ("wave port eigenmode"): refine such a mode withFieldEstimator. An S entry(to, from)whose porttois not excited needs that port’s adjoint dual:refine_meshadds it to each of its solves, one more right-hand side with its options;error_estimateon a finished result factorizes once more per frequency, with the direct solver at the result’s order, so estimate a large model throughrefine_mesh(max_cycles=0).
- class RefinementCycle#
The numbers of one solved mesh of a
MeshRefinement.With a tuple of estimators,
estimateandvalueare 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
valueon this mesh.value – The quantity of a
QuantityEstimatoron this mesh: the capacitance entry in farads, a tuple of the S entry per frequency, the followed mode’s complexomegain rad/s, its Q, the followed cluster’s mean complexomega, or an objective’s value;Nonefor aFieldEstimator.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.
- 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
tois 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 throughgfem.power_floworgfem.region_meanonce more per frequency it reads. On a large model, estimate throughrefine_meshwithmax_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.solveonmodel: electrostatic, eigenmode (every mode is estimated), or a uniform driven sweep solved withkeep_fields=True(every kept field).estimator (Estimator) –
FieldEstimator(), or aQuantityEstimatornaming an entry ofresult(itsomegaindex is a mode ofresult).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
QuantityEstimatornames a quantity of another result type.KeyError – A
QuantityEstimatornames 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 withkeep_fields=True); aQuantityEstimatornames 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 (
featurenames 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 agfem.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; seeQuantityEstimator), or an objective reading what it may not.DegenerateModeError – A
QuantityEstimatornames a mode of a degenerate cluster, or one within the defaultSolverOptions.cluster_rtolof another mode (the message names the cluster); a clusteromega=(i, ...)holds part of a degenerate cluster, or another mode lies less than twice as far from its mean as its farthest member.NotImplementedError –
modelholds a metal-dielectric blend (MaterialField.interpolatewith 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:
- 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 holdingerror_fractionof 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 (MaterialFieldvalues, 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**2divided 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=Truewhatever it asks: the estimate reads every frequency’s field of every excited port, andresultkeeps 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
Electrostaticproblem, aDrivenproblem on a uniform sweep (lumped or wave ports), or anEigenmodeproblem. The estimate of a driven run is the worst frequency’s, of an eigenmode run the worst mode’s.estimator (Estimator | tuple[QuantityEstimator, ...]) –
FieldEstimator(), aQuantityEstimatornaming a quantity ofproblem, or a tuple of distinctQuantityEstimatorobjects; 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;
Noneis 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 aFieldEstimator; for aQuantityEstimatorrelative to the capacitance entry, toomega, to a cluster’s meanomegaor to Q, absolute for an S entry. At least 10 timesoptions.tolerance(options.eigen_tolerancefor anEigenmode; 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.
Nonesets 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;
NoneisSolverOptions().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
RefinementCycleper 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
QuantityEstimatornames a quantity of another problem type, or a tuple of estimators holds aFieldEstimator.KeyError – A
QuantityEstimatornames 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
QuantityEstimatornames a source port that is not excited, a mode index at or aboven_modes, a cluster of at leastn_modesmodes (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 (
featurenames 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 agfem.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; seeQuantityEstimator), an objective reading what it may not (on the first estimate), orfrequency_workersabove 1 for an estimate that solves an adjoint dual (an unexcitedtoor an objective’s dual), which rides on the forward solve.DegenerateModeError – The mode a
QuantityEstimatorfollows is not alone: another mode lies withinoptions.cluster_rtolof it, or shares itsresult.clusterlabel (the message names the cluster, to estimate its mean withomega=(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 clusteromega=(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 –
modelholds a metal-dielectric blend (MaterialField.interpolatewith 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. Underjax.gradorjax.vmapwith concrete inputs it runs; refine outside the transformed function, then differentiategfem.solveon 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: