Repository navigation
Drift terms - #1231
Drift terms#1231
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1231 +/- ##
==========================================
- Coverage 95.89% 95.70% -0.20%
==========================================
Files 55 57 +2
Lines 4780 4956 +176
==========================================
+ Hits 4584 4743 +159
- Misses 196 213 +17 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Fixes three failures in festim-dev#1231's test_codim1_exports.py: test_quantities_on_an_exterior_manifold KeyError test_flux_on_an_interior_manifold_is_not_silently_zero KeyError test_export_on_a_manifold_boundary_locator_matching_... DID NOT RAISE One root cause for the first two. The revamp maps both `TotalSurface(field=bulk, surface=gamma)` and `TotalVolume(field=gamma_species, volume=gamma)` onto the same `domain=gamma`, which throws away a distinction festim-dev#1231 depends on. A codim-1 volume subdomain is two things at once: a subdomain a species lives on, and a set of facets a *bulk* species has a trace on. The two mean different integrals over the same geometry, and the old class name was carrying that information. The discriminator is whether the field lives on the domain -- `domain in field.subdomains` -- which is the rule festim-dev#1231's export_surface_context already applies. Added as FieldQuantity.reads_domain_itself and the problem-side _reads_domain_itself, and used in three places: volume_of bulk field -> coupling_side(manifold, field), so the solution is read from the side the species lives on rather than looked up on the manifold's submesh, which raised the KeyError measure_for bulk field -> unindexed_coupling_measure (dS). The parent ds integrates to exactly zero over interior facets, so this would have been a silent zero restriction_for bulk field -> restriction_of(manifold, volume). This is the case the previous commit left returning None and flagged as an open design question; the tests answer it. test_flux_on_an_interior_manifold_is_not_ silently_zero has different exchange rates per side precisely so a swapped +/- gives a wrong number domain_name follows the same rule, so a bulk quantity over a manifold titles itself "surface" as it did pre-revamp, keeping csv headers stable. Third failure is timing, not dispatch. festim-dev#1231 validates surface exports in initialise_exports via export_surface_context, but the field quantities are no longer SurfaceQuantity, so they resolved lazily at post-processing and initialise() raised nothing. check_export_compatibility now resolves every field quantity's domain eagerly and discards the result; resolution is memoised, so post-processing is unaffected. STILL NOT EXECUTED HERE: no FEniCSx in this environment. The dispatch was traced symbolically against the four exports of test_quantities_on_an_exterior_manifold and produces the titles the test asserts, but the numbers are unverified.
ee-nn
left a comment
There was a problem hiding this comment.
A few high-level comments
| v_cg = basix.ufl.element( | ||
| "Lagrange", | ||
| function_space.mesh.topology.cell_name(), | ||
| 1, |
There was a problem hiding this comment.
We should also allow for DG 0 velocity fields for imports from openFOAM
There was a problem hiding this comment.
Probably.
- Since this PR now enforces that we use the conservative form for the advection, the DG0 to CG1 interpolation making the velocity field non divergence-free is no longer a problem
- But we still want to not modify the data too much! I feel like this is a separate problem and can be tacked by a smaller, more focused PR
What do you think?
There was a problem hiding this comment.
Agreed on both counts, and a separate focused PR for the DG0 handling works for me.
One concrete piece from #1081 to carry over whenever that happens, since I am closing that PR: VelocityField.convert_input_value there short-circuits when the given function already lives on the target mesh
if vel.function_space.mesh == function_space.mesh:
self.fenics_object = vel
else:
... # build the CG1 vector space and nmm_interpolateAs it stands here every velocity is copied into a freshly built CG1 vector space even when the input is already CG1 on that same mesh, which is both an avoidable interpolation and the point at which a DG0 field from foam2dolfinx loses its data. In the discontinuous problem the interpolation onto each subdomain's submesh is genuinely needed, so the short-circuit only buys anything in the continuous case, but that is the common one for an OpenFOAM velocity.
|
I am closing #1081 in favour of this PR, having checked that everything in it is covered here. One difference is worth a decision rather than a silent drop, so raising it here. #1081 added a separate How we could fix this: |
959a751 to
fb3ee00
Compare
8ab1c4a to
6a80cbb
Compare
62d42ae to
6834ac3
Compare
| if is_zero_velocity(velocity): | ||
| return None |
There was a problem hiding this comment.
This is done at initialise. In the scenario where the velocity is zero at the beginning but increases later on then it will never be added to the form, leading to wrong results!
We should simply add it everytime.
The warning above could stay but it should be more specific ("the drift velocity is zero at t=0")
| @@ -860,11 +953,17 @@ def create_sources_from_reactions(self): | |||
| self._unpacked_sources += reaction.create_sources() | |||
|
|
|||
| def convert_advection_term_to_fenics_objects(self): | |||
There was a problem hiding this comment.
Should we rename this method to make it not focussed on advection?
| if _drift.warn_if_no_effect(drift_term, species, velocity): | ||
| continue |
There was a problem hiding this comment.
Same comment as above
| concentration=species.solution, | ||
| test_function=species.test_function, | ||
| velocity=velocity, | ||
| dx=self.dx(vol.id), |
There was a problem hiding this comment.
Does that work with the codim1 stuff?
There was a problem hiding this comment.
it's correctly covered in the Discontinuous class no problem
| @@ -1721,13 +1840,21 @@ def convert_source_input_values_to_fenics_objects(self): | |||
| ) | |||
|
|
|||
| def convert_advection_term_to_fenics_objects(self): | |||
There was a problem hiding this comment.
Rename method
Description
To be merged after #1229 (stack).
Replaces #1081
Summary
Adds drift terms: transport driven by a gradient other than the species' own. All of
them add a velocity to the flux, and differ only in what sets it:
F.AdvectionTerm(existing)F.SoretTerm-D Q*/(k_B T²) grad(T)F.ElectromigrationTerm-z D/(k_B T) grad(phi)They share one assembly, in divergence form
div(c v), and one new list on theproblem,
drift_terms.AdvectionTermis folded onto the same base class.Also here, because the divergence form makes them necessary:
F.OutflowBC— marks a surface the flow leaves through, so drift carries thespecies out of the domain. This is the
+ (v·n) u w dsterm of new OutflowBC #1081, arrived at fromthe other direction; see Relationship to new OutflowBC #1081 below.
F.SurfaceFluxnow reports the total flux-D grad(c)·n + c v·n. The"advection terms are not accounted for" warning is gone.
Related Issues
Stacked on #1229. Replaces #1081.
Fixes #973, #1080
Motivation and Context
Soret is a v1 → v2 regression.
docs/source/theory.rstdocuments the effect with itsflux equation, and
docs/source/userguide/settings.rstlistedsoretas a settingsoption — but nothing in
src/festim/implemented it (grep -i soret src/returnednothing, and
Settingshas no such parameter). FESTIM 1 had it, including forcylindrical and spherical coordinates. Thermal gradients in plasma-facing components are
large enough to redistribute tritium, and TMAP7/TMAP8 both have Soret, so any
thermal-gradient benchmark was out of reach.
Electromigration was unreachable, which rules out proton-conducting-ceramic
electrochemistry (e.g. TMAP8's val-2l case), electrochemical hydrogen pumping, and
Devanathan–Stachurski permeation cells — the standard experimental method for measuring
H diffusivity in metals.
The existing
AdvectionTermwas non-conservative and volume-only. It assembledv·grad(c), which equalsdiv(c v)only wherediv(v) = 0, and it contributed nothingat the boundary — so a flux BC constrained only the diffusive part.
Doing all three as one term is what makes this a small change rather than three: the same
weak form covers stress-driven diffusion later, which is the remaining member of the
family.
Relationship to #1081
#1081 identified exactly the same missing term: "an additional term may be required from
integration by parts: + (v·n) u w ds", and added
boundary_conditions/outflow_bc.pyunder the same name. This PR arrives at it from the conservative-form direction — the
term is required precisely because
div(c v)is integrated by parts — and adds the testsand docs that PR was missing, plus support for the boundary of a codim-1 manifold.
One deliberate difference: #1081 added a separate
exports/advection_flux.py. Here theadvective contribution is folded into
SurfaceFluxinstead, so that one export reportsthe flux the model actually conserves. Happy to revisit if a separate export is wanted.
Type of Change
Implementation
src/festim/drift.py(new) —DriftTermBase,SoretTerm,ElectromigrationTerm,and the shared
drift_form. Coefficients (Q_star,potential) go throughhelpers.Valuewithup_to_ufl_expr=True, so they get the usualx/t/Tdependence for free.
advection.py—AdvectionTermsubclassesDriftTermBaseand keepsVelocityField. The new terms cannot reuse it: their velocities are ufl expressionsbuilt from
T,Dand a gradient, andVelocityFieldaccepts only afem.Functionor a callable of
t.m(rcylindrical,
r²spherical) and tests withw/m; those cancel inv·grad(c)but notin the divergence form, which needs
-m c v·grad(w/m).HydrogenTransportProblemDiscontinuousChangeVar, which ignoredadvection_termsentirely and silently before this.
built from an all-zero integrand has no integration domain for FFCx — and warns,
naming the input at fault.
temperature=lambda t: ...is the case this exists for: itvaries in time, not in space.
Testing
pytest) — 1021 passed, 5 skipped44 new tests: 30 unit (
test/test_drift.py), 11 system (test/system_tests/test_drift.py),3 in a worked example (
test/system_tests/test_counterflow.py). The physical ones assertclosed forms, not regression baselines.
c = A exp(Q*/k_B T)on a no-flux slabc = A exp(-z phi/k_B T)OutflowBCsemanticsc = e^(2x)= 7.389, outflow givesc = 1e²= 7.389056SurfaceFluxincludes driftThe discriminating test is
test_advection_mms_with_a_non_solenoidal_velocity: an MMSwhose source is built from
div(c v)withdiv(v) = 1. It converges at rate 2 under thedivergence form and stalls under
v·grad(c). Worth knowing that every pre-existingadvection test uses a divergence-free velocity with Dirichlet data on the whole
boundary, so all of them pass under either form and none would have caught a regression
here.
test_drift_form_is_the_divergence_formpins the assembled form directly as acheap unit-level guard.
Worked example (
test_counterflow.py): a counter-current membrane contactor — a 2Dsolid separator with a 1D fluid channel running up each face as a codim-1 manifold, one
flowing up and one down, exchanging through
J = k(c_fluid − c_wall). The fourchannel-end fluxes balance to 1.8e-15, and counter-current recovers 3.4% more into the
sweep than co-current (mesh-converged: 3.371 / 3.370 / 3.369 % at n = 60/120/240).
Code Quality Checklist
ruff format .)ruff check .) — clean on every file touchedDocumentation
New
docs/source/userguide/drift.rst; the Soret section oftheory.rstgeneralised todrift with electromigration added;
festim.driftadded to the API index.soretremovedfrom the settings list in
settings.rst, where it had been advertised as an option thatdoes not exist in v2. As in #1229 I could not run
sphinx-buildin a full environment(the docs env here lacks
io4dolfinx), so the HTML builds clean and the RST is otherwiseunverified beyond review.
Breaking Changes
1.
AdvectionTermis now assembled in divergence form. Results are unchanged if thevelocity field is divergence-free (as an incompressible flow is) and every boundary
the flow crosses carries a boundary condition. If the flow leaves through an untagged
boundary, that boundary is now a closed end and the species backs up against it — add an
F.OutflowBCthere. Documented with a warning in both the user guide and the theoryguide.
This bit two tests in this repo, both of which had a manifold outlet with no condition on
it; both now declare one.
test_multi_material_with_advectionalso changes answers — ithas untagged boundary either side with a horizontal velocity — but it asserts nothing, so
it passes either way. Worth deciding whether to give it an
OutflowBCand someassertions.
2.
advection_termsis deprecated in favour ofdrift_terms, with aDeprecationWarning. It is deliberately not a plain alias: it appends todrift_termsrather than replacing it, so thatdoes not silently drop a Soret term and leave the model solving different physics.
Re-assigning replaces the advection entries rather than accumulating them, and the getter
returns just that subset. The five test files that used the old name have been migrated,
so the shim is exercised deliberately rather than incidentally.
Additional Notes
Known limitations:
form oscillates. Documented; a runtime warning on cell Péclet would be a reasonable
follow-up.
v = D V_H/(RT) grad(sigma_h), but needs a hydrostatic-stress field API FESTIM has nostory for.
DriftTermBaseis shaped so it drops in later.impose a linear potential across the membrane, but there is no Poisson/current
conservation solve.
CustomQuantity, which Codim: support for derived quantities #1229 already documents as broken in thediscontinuous problem for unrelated reasons.
ChangeVarwiring is included because that class silently ignored drift terms, butit is low-value given the plan to remove the class — easy to drop in review.