diff --git a/docs/api/models.md b/docs/api/models.md index 95a6fb6..b7eeeac 100644 --- a/docs/api/models.md +++ b/docs/api/models.md @@ -46,6 +46,9 @@ .. autoclass:: DirichletMultiplier :members: + +.. autoclass:: BoundaryMisfit + :members: ``` ## Facets of discontinuous fields @@ -63,17 +66,38 @@ .. autoclass:: InflowBoundary :members: +.. autoclass:: InteriorFlux + :members: + .. autoclass:: UpwindFlux :members: +.. autoclass:: NormalVelocityJump + :members: + +.. autoclass:: DivergenceCorrection + :members: + .. autoclass:: TwoPointFlux :members: +.. autoclass:: TwoPointDirichlet + :members: + .. autoclass:: NonOrthogonalCorrection :members: +.. autoclass:: NonOrthogonalDirichletCorrection + :members: + .. autoclass:: LeastSquaresMisfit :members: + +.. autoclass:: LeastSquaresDirichletMisfit + :members: + +.. autoclass:: LeastSquaresNeumannMisfit + :members: ``` ## Interfaces diff --git a/docs/tutorials/13_weighted_averages.py b/docs/tutorials/13_weighted_averages.py index f8184cd..45f1e1a 100644 --- a/docs/tutorials/13_weighted_averages.py +++ b/docs/tutorials/13_weighted_averages.py @@ -291,13 +291,15 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f): # \end{aligned} # $$ (weighted-inflow) # -# {py:class}`InflowBoundary ` holds it: +# {py:class}`InflowBoundary ` holds it, as the +# inflow $q$ of a {py:class}`BoundaryFlux `, whose +# residual is $-\int_{\Gamma} q\, w \,\mathrm{d}s$: # # ```{literalinclude} ../../src/sumfem/models/dg.py # :language: python # :pyobject: InflowBoundary # :start-at: def __init__ -# :prepend: class InflowBoundary(Residual): +# :prepend: class InflowBoundary(BoundaryFlux): # ``` # With the upwinding and the inflow term, and $\mu_0 > 0$ in @@ -328,13 +330,24 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f): # \end{aligned} # $$ (weighted-two-point) # -# {py:class}`TwoPointFlux ` holds them: +# {py:class}`TwoPointFlux ` holds $a_I^0$, as the +# flux $\hat{F}$ of an {py:class}`InteriorFlux `, +# whose residual is $\sum_F \int_F \hat{F}\, [\![w]\!] \,\mathrm{d}s$, and +# {py:class}`TwoPointDirichlet ` holds $a_B^0$, +# as an inflow: # # ```{literalinclude} ../../src/sumfem/models/dg.py # :language: python # :pyobject: TwoPointFlux # :start-at: def __init__ -# :prepend: class TwoPointFlux(Residual): +# :prepend: class TwoPointFlux(InteriorFlux): +# ``` +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: TwoPointDirichlet +# :start-at: def __init__ +# :prepend: class TwoPointDirichlet(BoundaryFlux): # ``` # The two-point flux is consistent only where the segment between the @@ -366,13 +379,22 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f): # The centroids are a known coefficient, the coordinates interpolated into # piecewise constants. # {py:class}`NonOrthogonalCorrection ` -# holds the correction: +# holds the correction on the interior facets, and +# {py:class}`~sumfem.models.NonOrthogonalDirichletCorrection` on the +# boundary: # # ```{literalinclude} ../../src/sumfem/models/dg.py # :language: python # :pyobject: NonOrthogonalCorrection # :start-at: def __init__ -# :prepend: class NonOrthogonalCorrection(Residual): +# :prepend: class NonOrthogonalCorrection(InteriorFlux): +# ``` +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: NonOrthogonalDirichletCorrection +# :start-at: def __init__ +# :prepend: class NonOrthogonalDirichletCorrection(BoundaryFlux): # ``` # The gradient is a second unknown, fitted in each cell by least squares to @@ -392,8 +414,8 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f): # unknown, as in {doc}`../getting_started/04_energy_functionals`. Its # variation in the gradient alone, with the unknown held, gives the equations # of the gradient, the normal equations of the fit. -# {py:class}`LeastSquaresMisfit ` is that -# functional: +# {py:class}`LeastSquaresMisfit ` holds the +# terms of the neighbouring cells: # # ```{literalinclude} ../../src/sumfem/models/dg.py # :language: python @@ -401,6 +423,19 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f): # :start-at: def __init__ # :prepend: class LeastSquaresMisfit(Functional): # ``` +# +# On a boundary facet, the boundary value takes the place of the neighbour, in +# a {py:class}`BoundaryMisfit `, the weighted +# square $\frac{1}{2} \int_\Gamma w\, e^2 \,\mathrm{d}s$ of a misfit $e$; +# {py:class}`~sumfem.models.LeastSquaresDirichletMisfit` gives its misfit and +# weight, and the sum of the two is that functional: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: LeastSquaresDirichletMisfit +# :start-at: def __init__ +# :prepend: class LeastSquaresDirichletMisfit(BoundaryMisfit): +# ``` # ### The weighted-average method # @@ -456,16 +491,22 @@ def create_weighted_average_residual( model = ( models.Reaction("reaction", {u: 1}, {}, forward_rate=mu) + models.Source("source", u, f) - + models.TwoPointFlux("two_point", u, kappa, g) + + models.TwoPointFlux("two_point", u, kappa) + + models.TwoPointDirichlet("two_point_boundary", u, kappa, g) + flow ) if correct: shape = (u.domain.geometric_dimension,) G = symbolic.Field("G", u.domain, ("DG", 0, shape)) - misfit = models.LeastSquaresMisfit("gradient", G, u, centroids, g) + misfit = models.LeastSquaresMisfit( + "gradient", G, u, centroids + ) + models.LeastSquaresDirichletMisfit("gradient_boundary", G, u, centroids, g) model = ( model + models.NonOrthogonalCorrection("correction", u, G, kappa, centroids) + + models.NonOrthogonalDirichletCorrection( + "correction_boundary", u, G, kappa, centroids + ) + misfit.to_residual([G]) ) return model diff --git a/src/sumfem/models/__init__.py b/src/sumfem/models/__init__.py index 4acc5c7..8e4d20a 100644 --- a/src/sumfem/models/__init__.py +++ b/src/sumfem/models/__init__.py @@ -4,16 +4,22 @@ :class:`Diffusion`, :class:`ConvectiveAdvection` and :class:`ConservativeAdvection`, :class:`Source` and :class:`Poisson`, and Ohmic :class:`Conduction`. -- Boundaries: :class:`BoundaryFlux`, :class:`Outflow`, and constraints - with Lagrange multipliers, :class:`BoundaryConstraint` and - :class:`DirichletMultiplier`. +- Boundaries: :class:`BoundaryFlux`, :class:`Outflow`, constraints with + Lagrange multipliers, :class:`BoundaryConstraint` and + :class:`DirichletMultiplier`, and conditions by least squares, + :class:`BoundaryMisfit`. - Facets of discontinuous fields: the weighted interior penalty of diffusion, :class:`WeightedInteriorPenalty`, with :class:`NitscheDirichlet` on the boundary; upwinding of advection in convective form, :class:`InteriorUpwinding` with :class:`InflowBoundary`, or conservative - form, :class:`UpwindFlux`; and for piecewise constants, - :class:`TwoPointFlux` with :class:`NonOrthogonalCorrection` and the - gradient of :class:`LeastSquaresMisfit`. + form, :class:`UpwindFlux`, with :class:`DivergenceCorrection` for a + discrete flow that is not free of divergence; and for piecewise constants, + :class:`TwoPointFlux` and :class:`TwoPointDirichlet`, corrected by + :class:`NonOrthogonalCorrection` and + :class:`NonOrthogonalDirichletCorrection` with the gradient of + :class:`LeastSquaresMisfit`, :class:`LeastSquaresDirichletMisfit` and + :class:`LeastSquaresNeumannMisfit`; the fluxes through the interior facets + are each an :class:`InteriorFlux`. - Interfaces between subdomains: :class:`InterfaceLagrangeMultiplier`, a condition across an interface with a Lagrange multiplier for the flux, or penalized, by an exchange flux, :class:`InterfacePenalty`, or by an energy, @@ -34,14 +40,27 @@ """ from .advection import Advection, ConservativeAdvection, ConvectiveAdvection -from .boundary import BoundaryConstraint, BoundaryFlux, DirichletMultiplier, Outflow +from .boundary import ( + BoundaryConstraint, + BoundaryFlux, + BoundaryMisfit, + DirichletMultiplier, + Outflow, +) from .charge import Conduction from .dg import ( + DivergenceCorrection, InflowBoundary, + InteriorFlux, InteriorUpwinding, + LeastSquaresDirichletMisfit, LeastSquaresMisfit, + LeastSquaresNeumannMisfit, NitscheDirichlet, NonOrthogonalCorrection, + NonOrthogonalDirichletCorrection, + NormalVelocityJump, + TwoPointDirichlet, TwoPointFlux, UpwindFlux, WeightedInteriorPenalty, @@ -84,6 +103,7 @@ "ConvectiveAdvection", "BoundaryConstraint", "BoundaryFlux", + "BoundaryMisfit", "Conduction", "Diffusion", "InterfaceLagrangeMultiplier", @@ -100,11 +120,18 @@ "GradDiv", "DirichletMultiplier", "Outflow", + "DivergenceCorrection", "InflowBoundary", + "InteriorFlux", "InteriorUpwinding", + "LeastSquaresDirichletMisfit", "LeastSquaresMisfit", + "LeastSquaresNeumannMisfit", "NitscheDirichlet", "NonOrthogonalCorrection", + "NonOrthogonalDirichletCorrection", + "NormalVelocityJump", + "TwoPointDirichlet", "TwoPointFlux", "UpwindFlux", "WeightedInteriorPenalty", diff --git a/src/sumfem/models/boundary.py b/src/sumfem/models/boundary.py index ae7cb09..7215252 100644 --- a/src/sumfem/models/boundary.py +++ b/src/sumfem/models/boundary.py @@ -1,13 +1,22 @@ -"""Boundary terms: fluxes, outflow, and conditions with Lagrange multipliers.""" +"""Boundary terms: fluxes, outflow, conditions with Lagrange multipliers, and +conditions by least squares.""" from __future__ import annotations import numpy.typing as npt import ufl +from ufl.domain import extract_unique_domain -from sumfem.symbolic import Field, Residual, as_expr +from sumfem.error_handling import ComponentError +from sumfem.symbolic import Domain, Field, Functional, Residual, as_expr -__all__ = ["BoundaryConstraint", "BoundaryFlux", "DirichletMultiplier", "Outflow"] +__all__ = [ + "BoundaryConstraint", + "BoundaryFlux", + "BoundaryMisfit", + "DirichletMultiplier", + "Outflow", +] class BoundaryFlux(Residual): @@ -238,3 +247,70 @@ def __init__( def constraint(self) -> ufl.core.expr.Expr: """The constraint ``u - g``.""" return self._field - self._value + + +class BoundaryMisfit(Functional): + r"""The weighted square of the misfit of a condition on marked facets. + + A condition :math:`e = 0` on the boundary, which holds in the sense of + least squares where the functional, :eq:`boundary-misfit`, is minimized, + e.g. in the variation of some fields alone, see + :meth:`~sumfem.symbolic.Functional.to_residual`. + + Args: + name: Name of the functional. + misfit: The misfit ``e`` of the condition, an expression on one + domain. + weight: The weight ``w`` of its square. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + boundary. + + Raises: + ComponentError: If the misfit is not an expression on one domain. + """ + + _misfit: ufl.core.expr.Expr + """The misfit of the condition.""" + _weight: ufl.core.expr.Expr + """The weight of its square.""" + _domain: Domain + """The domain of the misfit.""" + _markers: tuple[str, ...] + """Facet markers of the boundary.""" + + def __init__( + self, + name: str, + misfit: ufl.core.expr.Expr, + weight: ufl.core.expr.Expr | float = 1.0, + markers: tuple[str, ...] = (), + ): + super().__init__(name) + self._misfit = as_expr(misfit) + self._weight = as_expr(weight) + domain = extract_unique_domain(self._misfit) + if not isinstance(domain, Domain): + raise ComponentError( + f"The misfit of {name!r} must be an expression on one domain." + ) + self._domain = domain + self._markers = tuple(markers) + + def functional(self) -> ufl.Form: + r"""The weighted square of the misfit on the boundary. + + With the misfit :math:`e` and the weight :math:`w`, + + .. math:: + :label: boundary-misfit + + \begin{aligned} + J &= \frac{1}{2} \int_\Gamma w\, e \cdot e \,\mathrm{d}s. + \end{aligned} + + Returns: + The form over the boundary. + """ + e = self._misfit + squared = 0.5 * self._weight * ufl.inner(e, e) + return squared * self._domain.ds(*self._markers) diff --git a/src/sumfem/models/dg.py b/src/sumfem/models/dg.py index 4ba937c..69f2229 100644 --- a/src/sumfem/models/dg.py +++ b/src/sumfem/models/dg.py @@ -5,7 +5,8 @@ :class:`~sumfem.models.Diffusion` and the advection models need: weighted interior penalties and Nitsche's terms for the diffusion, upwinding for the advection, and for piecewise constants, two-point fluxes with a correction -for non-orthogonal meshes. The tutorial on discretizing advection-dominated +for non-orthogonal meshes, and the correction of advection by a discrete flow +that is not divergence free. The tutorial on discretizing advection-dominated problems with discontinuous coefficients derives them and compares them. """ @@ -13,15 +14,26 @@ import numpy.typing as npt import ufl +from ufl.algorithms import expand_derivatives -from sumfem.symbolic import Field, Functional, Residual, as_expr +from sumfem.symbolic import Field, Functional, Residual, ResidualSum, as_expr + +from .boundary import BoundaryFlux, BoundaryMisfit +from .diffusion import Source __all__ = [ + "DivergenceCorrection", "InflowBoundary", + "InteriorFlux", "InteriorUpwinding", + "LeastSquaresDirichletMisfit", "LeastSquaresMisfit", + "LeastSquaresNeumannMisfit", "NitscheDirichlet", "NonOrthogonalCorrection", + "NonOrthogonalDirichletCorrection", + "NormalVelocityJump", + "TwoPointDirichlet", "TwoPointFlux", "UpwindFlux", "WeightedInteriorPenalty", @@ -31,37 +43,17 @@ class WeightedInteriorPenalty(Residual): r"""The weighted interior penalty of diffusion on the interior facets. - For a field :math:`u` of a discontinuous element and a diffusivity - :math:`\kappa` that may jump between cells, with the values :math:`q^\pm` - of the two cells :math:`K^\pm` of an interior facet :math:`F`, the - normal :math:`\mathbf{n}` out of :math:`K^+`, the jump - :math:`[\![q]\!] = q^+ - q^-` and the penalty constant :math:`\alpha`, - - .. math:: - :label: dg-weighted-interior-penalty - - \begin{aligned} - \omega^\pm &= \frac{\kappa^\mp}{\kappa^+ + \kappa^-}, \\ - \{\mathbf{q}\}_\omega &= \omega^+ \mathbf{q}^+ + \omega^- \mathbf{q}^-, \\ - \gamma &= \frac{\kappa^+ \kappa^-}{\kappa^+ + \kappa^-}, \\ - h_F &= \frac{|K^+| + |K^-|}{2 |F|}, \\ - a_I(u, w) &= \sum_F \int_F - \frac{\alpha \gamma}{h_F}\, [\![u]\!]\, [\![w]\!] - - \{\kappa \nabla u\}_\omega \cdot \mathbf{n}\, [\![w]\!] - - \{\kappa \nabla w\}_\omega \cdot \mathbf{n}\, [\![u]\!] - \,\mathrm{d}s. - \end{aligned} - - Each side is weighted with the diffusivity of the other, as in `Burman - and Zunino (2006) `_ and `Ern, - Stephansen and Zunino (2009) `_. - Where :math:`\kappa^+ = \kappa^-`, it is the symmetric interior penalty - method. The size :math:`h_F` holds in one, two and three dimensions, on - simplices: FFCx evaluates the cell volume of affine cells only. The terms - need the diffusivity of each side and no orientation of the facets. + For a field of a discontinuous element and a diffusivity that may jump + between cells, the terms :eq:`dg-weighted-interior-penalty` weight each + side of a facet with the diffusivity of the other, as in `Burman and Zunino + (2006) `_ and `Ern, Stephansen and + Zunino (2009) `_. Where the + diffusivity is continuous, it is the symmetric interior penalty method. The + terms need the diffusivity of each side and no orientation of the facets. Sum it with :class:`~sumfem.models.Diffusion` for the cells and :class:`NitscheDirichlet` on the boundary; for piecewise constants, use - :class:`TwoPointFlux` instead. + :class:`TwoPointFlux` instead. The cells are simplices, as FFCx evaluates + the cell volume of affine cells only. Args: name: Name of the model. @@ -91,43 +83,57 @@ def __init__( self._penalty = as_expr(penalty) def residual(self) -> ufl.Form: + r"""The penalty and the consistency terms of the jumps. + + With the values :math:`q^\pm` of the two cells :math:`K^\pm` of an + interior facet :math:`F`, the normal :math:`\mathbf{n}` out of + :math:`K^+`, the jump :math:`[\![q]\!] = q^+ - q^-` and the penalty + constant :math:`\alpha`, + + .. math:: + :label: dg-weighted-interior-penalty + + \begin{aligned} + \omega^\pm &= \frac{\kappa^\mp}{\kappa^+ + \kappa^-}, \\ + \{\mathbf{q}\}_\omega &= \omega^+ \mathbf{q}^+ + \omega^- \mathbf{q}^-, \\ + \gamma &= \frac{\kappa^+ \kappa^-}{\kappa^+ + \kappa^-}, \\ + h_F &= \frac{|K^+| + |K^-|}{2 |F|}, \\ + a_I(u, w) &= \sum_F \int_F + \frac{\alpha \gamma}{h_F}\, [\![u]\!]\, [\![w]\!] + - \{\kappa \nabla u\}_\omega \cdot \mathbf{n}\, [\![w]\!] + - \{\kappa \nabla w\}_\omega \cdot \mathbf{n}\, [\![u]\!] + \,\mathrm{d}s. + \end{aligned} + + Returns: + The form over the interior facets. + """ u, w, domain = self._field, self._field.v, self._field.domain kappa_p, kappa_m = self._diffusivity("+"), self._diffusivity("-") - omega_p = kappa_m / (kappa_p + kappa_m) - omega_m = kappa_p / (kappa_p + kappa_m) - gamma = kappa_p * kappa_m / (kappa_p + kappa_m) + kappa_sum = kappa_p + kappa_m + omega_p, omega_m = kappa_m / kappa_sum, kappa_p / kappa_sum + gamma = kappa_p * kappa_m / kappa_sum n = ufl.FacetNormal(domain)("+") h = ufl.avg(ufl.CellVolume(domain) / ufl.FacetArea(domain)) grad_u, grad_w = ufl.grad(u), ufl.grad(w) flux_u = omega_p * kappa_p * grad_u("+") + omega_m * kappa_m * grad_u("-") flux_w = omega_p * kappa_p * grad_w("+") + omega_m * kappa_m * grad_w("-") jump_u, jump_w = ufl.jump(u), ufl.jump(w) - consistency = ufl.dot(flux_u, n) * jump_w + ufl.dot(flux_w, n) * jump_u - penalty = self._penalty * gamma / h * jump_u * jump_w + consistency = ufl.inner(ufl.dot(flux_u, n), jump_w) + ufl.inner( + jump_u, ufl.dot(flux_w, n) + ) + penalty = ufl.inner(self._penalty * gamma / h * jump_u, jump_w) return (penalty - consistency) * domain.dS() class NitscheDirichlet(Residual): r"""A boundary value of diffusion by Nitsche's method. - With the outward normal :math:`\mathbf{n}`, the boundary value :math:`g`, - the penalty constant :math:`\alpha` and the size :math:`h_F = |K| / |F|` - of the cell :math:`K` of a boundary facet :math:`F`, the terms of - `Nitsche (1971) `_ are - - .. math:: - :label: dg-nitsche-dirichlet - - \begin{aligned} - a_B(u, w) &= \sum_{F \subset \Gamma} \int_F - \frac{\alpha \kappa}{h_F}\, (u - g)\, w - - \kappa \nabla u \cdot \mathbf{n}\, w - - (u - g)\, \kappa \nabla w \cdot \mathbf{n} \,\mathrm{d}s. - \end{aligned} - - Sum it with :class:`~sumfem.models.Diffusion` and, for a discontinuous - field, :class:`WeightedInteriorPenalty`. Other boundaries have no - diffusive flux. As there, the cells are simplices. + The terms :eq:`dg-nitsche-dirichlet` of `Nitsche (1971) + `_. Sum it with + :class:`~sumfem.models.Diffusion` and, for a discontinuous field, + :class:`WeightedInteriorPenalty`. Other boundaries have no diffusive + flux. As there, the cells are simplices. Args: name: Name of the model. @@ -167,6 +173,26 @@ def __init__( self._markers = tuple(markers) def residual(self) -> ufl.Form: + r"""The penalty, consistency and symmetry terms of the boundary value. + + With the outward normal :math:`\mathbf{n}`, the boundary value + :math:`g`, the penalty constant :math:`\alpha` and the size + :math:`h_F = |K| / |F|` of the cell :math:`K` of a boundary facet + :math:`F`, + + .. math:: + :label: dg-nitsche-dirichlet + + \begin{aligned} + a_B(u, w) &= \sum_{F \subset \Gamma} \int_F + \frac{\alpha \kappa}{h_F}\, (u - g)\, w + - \kappa \nabla u \cdot \mathbf{n}\, w + - (u - g)\, \kappa \nabla w \cdot \mathbf{n} \,\mathrm{d}s. + \end{aligned} + + Returns: + The form over the boundary. + """ u, w, domain = self._field, self._field.v, self._field.domain kappa = self._diffusivity n = ufl.FacetNormal(domain) @@ -174,30 +200,17 @@ def residual(self) -> ufl.Form: flux_u = ufl.dot(kappa * ufl.grad(u), n) flux_w = ufl.dot(kappa * ufl.grad(w), n) h = ufl.CellVolume(domain) / ufl.FacetArea(domain) - penalty = self._penalty * kappa / h * difference * w - form = penalty - flux_u * w - difference * flux_w + penalty = ufl.inner(self._penalty * kappa / h * difference, w) + form = penalty - ufl.inner(flux_u, w) - ufl.inner(difference, flux_w) return form * domain.ds(*self._markers) class InteriorUpwinding(Residual): r"""Upwinding of advection in convective form on the interior facets. - With the average :math:`\{q\} = \frac{1}{2} (q^+ + q^-)` and the other - notation of :class:`WeightedInteriorPenalty`, - - .. math:: - :label: dg-interior-upwinding - - \begin{aligned} - b_I(u, w) &= \sum_F \int_F - \frac{|\{\boldsymbol{\beta}\} \cdot \mathbf{n}|}{2}\, - [\![u]\!]\, [\![w]\!] - - \{\boldsymbol{\beta}\} \cdot \mathbf{n}\, [\![u]\!]\, \{w\} - \,\mathrm{d}s, - \end{aligned} - - a centered term and a least-squares penalty of the jumps, which in terms - of fluxes is upwinding (Section 2.3 of `Di Pietro and Ern (2012) + A centered term and a least-squares penalty of the jumps, + :eq:`dg-interior-upwinding`, which in terms of fluxes is upwinding (Section + 2.3 of `Di Pietro and Ern (2012) `_). For piecewise constants it is the upwind finite volume scheme. Sum it with :class:`~sumfem.models.ConvectiveAdvection` and :class:`InflowBoundary`; @@ -226,31 +239,50 @@ def __init__( self._velocity = as_expr(velocity) def residual(self) -> ufl.Form: + r"""The centered term and the penalty of the jumps. + + With the average :math:`\{q\} = \frac{1}{2} (q^+ + q^-)` and the other + notation of :eq:`dg-weighted-interior-penalty`, + + .. math:: + :label: dg-interior-upwinding + + \begin{aligned} + b_I(u, w) &= \sum_F \int_F + \frac{|\{\boldsymbol{\beta}\} \cdot \mathbf{n}|}{2}\, + [\![u]\!]\, [\![w]\!] + - \{\boldsymbol{\beta}\} \cdot \mathbf{n}\, [\![u]\!]\, \{w\} + \,\mathrm{d}s. + \end{aligned} + + Returns: + The form over the interior facets. + """ u, w, domain = self._field, self._field.v, self._field.domain flux = ufl.dot(ufl.avg(self._velocity), ufl.FacetNormal(domain)("+")) - upwinding = 0.5 * abs(flux) * ufl.jump(w) - return (-flux * ufl.avg(w) + upwinding) * ufl.jump(u) * domain.dS() + jump_u = ufl.jump(u) + upwinding = ufl.inner(0.5 * abs(flux) * jump_u, ufl.jump(w)) + return (upwinding - ufl.inner(flux * jump_u, ufl.avg(w))) * domain.dS() -class InflowBoundary(Residual): +class InflowBoundary(BoundaryFlux): r"""The boundary value where the flow enters, for the convective form. - With the outward normal :math:`\mathbf{n}` and the boundary value - :math:`g`, the weight is the negative part of - :math:`\boldsymbol{\beta} \cdot \mathbf{n}`, + The upwinding of :class:`InteriorUpwinding` with the boundary value + :math:`g` as the value outside the domain: the inflow of + :class:`~sumfem.models.BoundaryFlux` is weighted by the negative part of + :math:`\boldsymbol{\beta} \cdot \mathbf{n}`, with the outward normal + :math:`\mathbf{n}`, .. math:: :label: dg-inflow-boundary \begin{aligned} - b_B(u, w) &= \sum_{F \subset \Gamma} \int_F - \frac{|\boldsymbol{\beta} \cdot \mathbf{n}| - - \boldsymbol{\beta} \cdot \mathbf{n}}{2}\, (u - g)\, w - \,\mathrm{d}s, + q &= -\frac{|\boldsymbol{\beta} \cdot \mathbf{n}| + - \boldsymbol{\beta} \cdot \mathbf{n}}{2}\, (u - g). \end{aligned} - the upwinding of :class:`InteriorUpwinding` with the boundary value as - the value outside the domain. Where the flow leaves, it vanishes. + Where the flow leaves, it vanishes. Args: name: Name of the model. @@ -261,15 +293,6 @@ class InflowBoundary(Residual): boundary. """ - _field: Field - """The field.""" - _velocity: ufl.core.expr.Expr - """The velocity.""" - _value: ufl.core.expr.Expr - """The boundary value.""" - _markers: tuple[str, ...] - """Facet markers of the boundary.""" - def __init__( self, name: str, @@ -277,44 +300,94 @@ def __init__( velocity: ufl.core.expr.Expr | npt.ArrayLike, value: ufl.core.expr.Expr | float, markers: tuple[str, ...] = (), + ): + normal = ufl.dot(as_expr(velocity), ufl.FacetNormal(field.domain)) + inflow = -0.5 * (abs(normal) - normal) * (field - as_expr(value)) + super().__init__(name, field, inflow, markers) + + +class InteriorFlux(Residual): + r"""A numerical flux of a discontinuous field through the interior facets. + + The flux exchanges the field between the two cells of each interior + facet, :eq:`dg-interior-flux`. With the test function one, the terms of + each facet cancel, so the field is conserved. + + Args: + name: Name of the model. + field: The field ``u``, of a discontinuous element. + flux: The flux through each interior facet, along the normal out of + its ``"+"`` side, of the field's shape. + + Raises: + ValueError: If the flux has another shape than the field. + """ + + _field: Field + """The field.""" + _flux: ufl.core.expr.Expr + """The flux through the interior facets.""" + + def __init__( + self, + name: str, + field: Field, + flux: ufl.core.expr.Expr | npt.ArrayLike, ): super().__init__(name) self._field = field - self._velocity = as_expr(velocity) - self._value = as_expr(value) - self._markers = tuple(markers) + self._flux = as_expr(flux) + if self._flux.ufl_shape != field.ufl_shape: + raise ValueError( + f"The flux of {name!r} has the shape {self._flux.ufl_shape}, " + f"but {field.name!r} has {field.ufl_shape}." + ) def residual(self) -> ufl.Form: - u, w, domain = self._field, self._field.v, self._field.domain - flux = ufl.dot(self._velocity, ufl.FacetNormal(domain)) - inflow = 0.5 * (abs(flux) - flux) - return inflow * (u - self._value) * w * domain.ds(*self._markers) + r"""The flux times the jump of the test function. + + With the flux :math:`\hat{F}` and the jump + :math:`[\![w]\!] = w^+ - w^-` across each interior facet :math:`F`, + + .. math:: + :label: dg-interior-flux + + \begin{aligned} + b(u, w) &= \sum_F \int_F \hat{F}\, [\![w]\!] \,\mathrm{d}s. + \end{aligned} + Returns: + The form over the interior facets. + """ + w, domain = self._field.v, self._field.domain + return ufl.inner(self._flux, ufl.jump(w)) * domain.dS() -class UpwindFlux(Residual): + +class UpwindFlux(InteriorFlux): r"""The upwind flux of advection in conservative form on the interior facets. - With the notation of :class:`InteriorUpwinding`, the advective flux - through a facet takes the value of the cell upstream of it, + The advective flux through a facet takes the value of the cell upstream + of it. With the average :math:`\{q\} = \frac{1}{2} (q^+ + q^-)`, the + normal :math:`\mathbf{n}` out of the ``"+"`` side and the jump of + :eq:`dg-interior-flux`, the flux is .. math:: :label: dg-upwind-flux \begin{aligned} - b_I^c(u, w) &= \sum_F \int_F - \left( \{\boldsymbol{\beta}\} \cdot \mathbf{n}\, \{u\} - + \frac{|\{\boldsymbol{\beta}\} \cdot \mathbf{n}|}{2}\, [\![u]\!] - \right) [\![w]\!] \,\mathrm{d}s. + \hat{F} &= \{\boldsymbol{\beta}\} \cdot \mathbf{n}\, \{u\} + + \frac{|\{\boldsymbol{\beta}\} \cdot \mathbf{n}|}{2}\, [\![u]\!]. \end{aligned} Sum it with :class:`~sumfem.models.ConservativeAdvection`; on the boundary, :class:`~sumfem.models.Outflow` where the flow leaves and a :class:`~sumfem.models.BoundaryFlux` of the inflow - :math:`-\boldsymbol{\beta} \cdot \mathbf{n}\, g` where it enters. With - the test function one, the facet terms cancel, so the advected quantity - is conserved for any velocity, e.g. a drift that is not divergence free. - For a divergence-free velocity, the sum equals that of the convective - form with :class:`InteriorUpwinding` and :class:`InflowBoundary`. + :math:`-\boldsymbol{\beta} \cdot \mathbf{n}\, g` where it enters. The + advected quantity is conserved for any velocity, e.g. a drift that is not + divergence free. For a divergence-free velocity, the sum equals that of + the convective form with :class:`InteriorUpwinding` and + :class:`InflowBoundary`, and so it does for a discrete flow with + :class:`DivergenceCorrection`. Args: name: Name of the model. @@ -322,37 +395,27 @@ class UpwindFlux(Residual): velocity: The velocity ``beta``. """ - _field: Field - """The field.""" - _velocity: ufl.core.expr.Expr - """The velocity.""" - def __init__( self, name: str, field: Field, velocity: ufl.core.expr.Expr | npt.ArrayLike, ): - super().__init__(name) - self._field = field - self._velocity = as_expr(velocity) - - def residual(self) -> ufl.Form: - u, w, domain = self._field, self._field.v, self._field.domain - flux = ufl.dot(ufl.avg(self._velocity), ufl.FacetNormal(domain)("+")) - upwind = flux * ufl.avg(u) + 0.5 * abs(flux) * ufl.jump(u) - return upwind * ufl.jump(w) * domain.dS() + n = ufl.FacetNormal(field.domain)("+") + normal = ufl.dot(ufl.avg(as_expr(velocity)), n) + flux = normal * ufl.avg(field) + 0.5 * abs(normal) * ufl.jump(field) + super().__init__(name, field, flux) -class TwoPointFlux(Residual): +class TwoPointFlux(InteriorFlux): r"""The two-point fluxes of the diffusion of piecewise constants. - For piecewise constants, the gradients vanish, so the diffusion acts - only on the facets. On a simplex, the centroid of a cell :math:`K` lies - at the distance :math:`\delta_K` from its facet :math:`F`, and the - two-point fluxes of finite volumes, with harmonic weights where the - diffusivity jumps (`Eymard, Gallouët and Herbin (2000) - `_), are + For piecewise constants, the gradients vanish, so the diffusion acts only + on the facets: the two-point fluxes of finite volumes, with harmonic + weights where the diffusivity jumps (`Eymard, Gallouët and Herbin (2000) + `_). On a simplex, the + centroid of a cell :math:`K` lies at the distance :math:`\delta_K` from + its facet :math:`F`, and the flux of :eq:`dg-interior-flux` is .. math:: :label: dg-two-point-flux @@ -360,33 +423,54 @@ class TwoPointFlux(Residual): \begin{aligned} \delta_K &= \frac{d}{d + 1}\, \frac{|K|}{|F|}, \\ T &= \frac{1}{\delta_{K^+} / \kappa^+ + \delta_{K^-} / \kappa^-}, \\ - a^0(u, w) &= \sum_F \int_F T\, [\![u]\!]\, [\![w]\!] \,\mathrm{d}s - + \sum_{F \subset \Gamma} \int_F - \frac{\kappa}{\delta_K}\, (u - g)\, w \,\mathrm{d}s. + \hat{F} &= T\, [\![u]\!]. \end{aligned} They are consistent where the segment between the centroids of the two cells of a facet is orthogonal to it; elsewhere, add - :class:`NonOrthogonalCorrection`. Other boundaries have no diffusive - flux. + :class:`NonOrthogonalCorrection`. The boundary has no diffusive flux + without :class:`TwoPointDirichlet`. The cells are simplices. Args: name: Name of the model. field: The field ``u``, piecewise constant on simplices. diffusivity: The scalar diffusivity ``kappa``. - value: The boundary value ``g``. - markers: Facet markers of the boundary ``Gamma`` with the value. - Empty for the whole boundary. """ - _field: Field - """The field.""" - _diffusivity: ufl.core.expr.Expr - """The diffusivity.""" - _value: ufl.core.expr.Expr - """The boundary value.""" - _markers: tuple[str, ...] - """Facet markers of the boundary with the value.""" + def __init__( + self, name: str, field: Field, diffusivity: ufl.core.expr.Expr | float + ): + domain, kappa = field.domain, as_expr(diffusivity) + d = domain.topological_dimension + delta = d / (d + 1) * ufl.CellVolume(domain) / ufl.FacetArea(domain) + T = 1 / (delta("+") / kappa("+") + delta("-") / kappa("-")) + super().__init__(name, field, T * ufl.jump(field)) + + +class TwoPointDirichlet(BoundaryFlux): + r"""The two-point flux of piecewise constants to a boundary value. + + The flux from the centroid of a cell to the value :math:`g` on its + facets of the boundary, as :class:`TwoPointFlux` has between the + centroids of two cells: with the distance :math:`\delta_K` of + :eq:`dg-two-point-flux`, the inflow of + :class:`~sumfem.models.BoundaryFlux` is + + .. math:: + :label: dg-two-point-dirichlet + + \begin{aligned} + q &= -\frac{\kappa}{\delta_K}\, (u - g). + \end{aligned} + + Args: + name: Name of the model. + field: The field ``u``, piecewise constant on simplices. + diffusivity: The scalar diffusivity ``kappa``. + value: The boundary value ``g``. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + boundary. + """ def __init__( self, @@ -396,37 +480,26 @@ def __init__( value: ufl.core.expr.Expr | float, markers: tuple[str, ...] = (), ): - super().__init__(name) - self._field = field - self._diffusivity = as_expr(diffusivity) - self._value = as_expr(value) - self._markers = tuple(markers) - - def residual(self) -> ufl.Form: - u, w, domain = self._field, self._field.v, self._field.domain - kappa = self._diffusivity + domain = field.domain d = domain.topological_dimension delta = d / (d + 1) * ufl.CellVolume(domain) / ufl.FacetArea(domain) - T = 1 / (delta("+") / kappa("+") + delta("-") / kappa("-")) - interior = T * ufl.jump(u) * ufl.jump(w) - boundary = kappa / delta * (u - self._value) * w - return interior * domain.dS() + boundary * domain.ds(*self._markers) + inflow = -as_expr(diffusivity) / delta * (field - as_expr(value)) + super().__init__(name, field, inflow, markers) -class NonOrthogonalCorrection(Residual): +class NonOrthogonalCorrection(InteriorFlux): r"""The flux along the facets that two-point fluxes miss on non-orthogonal meshes. The over-relaxed correction of Jasak (PhD thesis, Imperial College - London, 1996) splits the normal into the direction :math:`\mathbf{d}` - between the centroids :math:`\mathbf{c}^\pm` of the two cells of a - facet, which :class:`TwoPointFlux` takes, and a remainder - :math:`\mathbf{k}` along the facet, whose flux it takes with a cell - gradient :math:`\mathbf{G}` of the field, e.g. of + London, 1996) splits the normal into the direction between the centroids + :math:`\mathbf{c}^\pm` of the two cells of a facet, which + :class:`TwoPointFlux` takes, and a remainder along the facet, whose flux + it takes with a cell gradient :math:`\mathbf{G}` of the field, e.g. of :class:`LeastSquaresMisfit` (Eqs. (3)-(4) of `Darwish, Mangani and - Moukalled (2017) `_). On a - boundary facet, its point :math:`\mathbf{x}` takes the place of the other - centroid (their Eqs. (24)-(25)). Both parts take the diffusivity of the - two-point flux, :math:`\kappa_T`: + Moukalled (2017) `_). Both + parts take the diffusivity of the two-point flux, :math:`\kappa_T`, with + :math:`T` and :math:`\delta` of :eq:`dg-two-point-flux`, so the flux of + :eq:`dg-interior-flux` is .. math:: :label: dg-non-orthogonal-correction @@ -435,14 +508,8 @@ class NonOrthogonalCorrection(Residual): \mathbf{d} &= \mathbf{c}^- - \mathbf{c}^+, \\ \mathbf{k} &= \mathbf{n} - \frac{\mathbf{d}}{\mathbf{d} \cdot \mathbf{n}}, \\ - \mathbf{k}_B &= \mathbf{n} - \frac{\mathbf{x} - \mathbf{c}} - {(\mathbf{x} - \mathbf{c}) \cdot \mathbf{n}}, \\ \kappa_T &= T\, (\delta_{K^+} + \delta_{K^-}), \\ - c(\mathbf{G}, w) &= -\sum_F \int_F - \kappa_T\, \mathbf{k} \cdot \{\mathbf{G}\}\, [\![w]\!] - \,\mathrm{d}s - - \sum_{F \subset \Gamma} \int_F - \kappa\, \mathbf{k}_B \cdot \mathbf{G}\, w \,\mathrm{d}s. + \hat{F} &= -\kappa_T\, \mathbf{k} \cdot \{\mathbf{G}\}. \end{aligned} On meshes whose facets are orthogonal to the segments between the @@ -455,21 +522,8 @@ class NonOrthogonalCorrection(Residual): diffusivity: The scalar diffusivity ``kappa``. centroids: The centroids of the cells, e.g. a known coefficient of piecewise constant vectors set to the spatial coordinate. - markers: Facet markers of the boundary ``Gamma`` of - :class:`TwoPointFlux`. Empty for the whole boundary. """ - _field: Field - """The field.""" - _gradient: Field - """The gradient of the field.""" - _diffusivity: ufl.core.expr.Expr - """The diffusivity.""" - _centroids: ufl.core.expr.Expr - """The centroids of the cells.""" - _markers: tuple[str, ...] - """Facet markers of the boundary of the two-point fluxes.""" - def __init__( self, name: str, @@ -477,54 +531,77 @@ def __init__( gradient: Field, diffusivity: ufl.core.expr.Expr | float, centroids: ufl.core.expr.Expr, - markers: tuple[str, ...] = (), ): - super().__init__(name) - self._field = field - self._gradient = gradient - self._diffusivity = as_expr(diffusivity) - self._centroids = centroids - self._markers = tuple(markers) - - def residual(self) -> ufl.Form: - w, G, domain = self._field.v, self._gradient, self._field.domain - c, kappa = self._centroids, self._diffusivity - x, n = ufl.SpatialCoordinate(domain), ufl.FacetNormal(domain) + domain, kappa, c = field.domain, as_expr(diffusivity), centroids + n = ufl.FacetNormal(domain)("+") between = c("-") - c("+") - k = n("+") - between / ufl.dot(between, n("+")) + k = n - between / ufl.dot(between, n) d = domain.topological_dimension delta = d / (d + 1) * ufl.CellVolume(domain) / ufl.FacetArea(domain) kappa_T = (delta("+") + delta("-")) / ( delta("+") / kappa("+") + delta("-") / kappa("-") ) - k_boundary = n - (x - c) / ufl.dot(x - c, n) - interior = -kappa_T * ufl.dot(k, ufl.avg(G)) * ufl.jump(w) - boundary = -kappa * ufl.dot(k_boundary, G) * w - return interior * domain.dS() + boundary * domain.ds(*self._markers) + flux = -kappa_T * ufl.dot(ufl.avg(gradient), k) + super().__init__(name, field, flux) -class LeastSquaresMisfit(Functional): - r"""The misfit of a gradient of piecewise constants to the neighbouring values. +class NonOrthogonalDirichletCorrection(BoundaryFlux): + r"""The correction of :class:`TwoPointDirichlet` on non-orthogonal boundary facets. - The gradient :math:`\mathbf{G}_K` of each cell fits the differences of - the field to the cells :math:`L` across its facets, and to the boundary - value :math:`g` at the points :math:`\mathbf{x}` of its facets on the - boundary :math:`\Gamma`, by least squares, so it is exact for linear - functions on any mesh. The functional sums the misfits over all cells, + The correction of :class:`NonOrthogonalCorrection` on a facet of the + boundary, where the facet's point :math:`\mathbf{x}` takes the place of + the other centroid (Eqs. (24)-(25) of `Darwish, Mangani and Moukalled + (2017) `_): with the + centroid :math:`\mathbf{c}` of the facet's cell, the inflow of + :class:`~sumfem.models.BoundaryFlux` is .. math:: - :label: dg-least-squares-misfit + :label: dg-non-orthogonal-dirichlet-correction \begin{aligned} - J(\mathbf{G}, u) &= \sum_K \sum_{L} - \frac{\left( \mathbf{G}_K \cdot (\mathbf{c}_L - \mathbf{c}_K) - - (u_L - u_K) \right)^2}{2\, |\mathbf{c}_L - \mathbf{c}_K|^2}, + \mathbf{k}_\Gamma &= \mathbf{n} - \frac{\mathbf{x} - \mathbf{c}} + {(\mathbf{x} - \mathbf{c}) \cdot \mathbf{n}}, \\ + q &= \kappa\, \mathbf{k}_\Gamma \cdot \mathbf{G}. \end{aligned} - with the facet terms averaged over each facet. Its variation in the - gradient alone, ``to_residual([gradient])``, gives the equations of the - gradient, the normal equations of the fit, with the field held. Each cell - needs neighbours in as many independent directions as the dimension. + Args: + name: Name of the model. + field: The field ``u``, piecewise constant on simplices. + gradient: The gradient ``G`` of the field, piecewise constant. + diffusivity: The scalar diffusivity ``kappa``. + centroids: The centroids of the cells. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + boundary. + """ + + def __init__( + self, + name: str, + field: Field, + gradient: Field, + diffusivity: ufl.core.expr.Expr | float, + centroids: ufl.core.expr.Expr, + markers: tuple[str, ...] = (), + ): + domain = field.domain + x, n = ufl.SpatialCoordinate(domain), ufl.FacetNormal(domain) + to_boundary = x - centroids + k = n - to_boundary / ufl.dot(to_boundary, n) + inflow = as_expr(diffusivity) * ufl.dot(gradient, k) + super().__init__(name, field, inflow, markers) + + +class LeastSquaresMisfit(Functional): + r"""The misfit of a gradient of piecewise constants to the neighbouring values. + + The gradient of each cell fits the differences of the field to the cells + across its facets by least squares, :eq:`dg-least-squares-misfit`, so it + is exact for linear functions on any mesh. Its variation in the gradient + alone, ``to_residual([gradient])``, gives the equations of the gradient, + the normal equations of the fit, with the field held. Each cell needs + neighbours in as many independent directions as the dimension; on the + boundary, :class:`~sumfem.models.BoundaryMisfit` adds them, e.g. + :class:`LeastSquaresDirichletMisfit` and :class:`LeastSquaresNeumannMisfit`. Args: name: Name of the functional. @@ -532,9 +609,6 @@ class LeastSquaresMisfit(Functional): field: The field ``u``, piecewise constant. centroids: The centroids of the cells, see :class:`NonOrthogonalCorrection`. - value: The boundary value ``g``. - markers: Facet markers of the boundary ``Gamma`` with the value. - Empty for the whole boundary. """ _gradient: Field @@ -543,10 +617,6 @@ class LeastSquaresMisfit(Functional): """The field.""" _centroids: ufl.core.expr.Expr """The centroids of the cells.""" - _value: ufl.core.expr.Expr - """The boundary value.""" - _markers: tuple[str, ...] - """Facet markers of the boundary with the value.""" def __init__( self, @@ -554,27 +624,225 @@ def __init__( gradient: Field, field: Field, centroids: ufl.core.expr.Expr, - value: ufl.core.expr.Expr | float, - markers: tuple[str, ...] = (), ): super().__init__(name) self._gradient = gradient self._field = field self._centroids = centroids - self._value = as_expr(value) - self._markers = tuple(markers) def functional(self) -> ufl.Form: + r"""The misfits to the neighbours, summed over all cells. + + With the centroids :math:`\mathbf{c}_K` and :math:`\mathbf{c}_L` of + the cells on either side of a facet, and the terms of each facet + averaged over it, + + .. math:: + :label: dg-least-squares-misfit + + \begin{aligned} + J(\mathbf{G}, u) &= \sum_K \sum_{L} + \frac{\left( \mathbf{G}_K \cdot (\mathbf{c}_L - \mathbf{c}_K) + - (u_L - u_K) \right)^2}{2\, |\mathbf{c}_L - \mathbf{c}_K|^2}. + \end{aligned} + + Returns: + The form over the interior facets. + """ G, u, domain = self._gradient, self._field, self._gradient.domain - c = self._centroids - x, area = ufl.SpatialCoordinate(domain), ufl.FacetArea(domain) + c, area = self._centroids, ufl.FacetArea(domain) between = c("-") - c("+") difference = u("-") - u("+") - interior = ( - (ufl.dot(between, G("+")) - difference) ** 2 - + (ufl.dot(between, G("-")) - difference) ** 2 - ) / (2 * ufl.dot(between, between) * area("+")) - to_boundary = x - c - misfit = ufl.dot(to_boundary, G) - (self._value - u) - boundary = misfit**2 / (2 * ufl.dot(to_boundary, to_boundary) * area) - return interior * domain.dS() + boundary * domain.ds(*self._markers) + plus = ufl.dot(G("+"), between) - difference + minus = ufl.dot(G("-"), between) - difference + squared = ufl.inner(plus, plus) + ufl.inner(minus, minus) + interior = squared / (2 * ufl.dot(between, between) * area("+")) + return interior * domain.dS() + + +class LeastSquaresDirichletMisfit(BoundaryMisfit): + r"""The misfit of a gradient of piecewise constants to a boundary value. + + The boundary value :math:`g` at the facet's point :math:`\mathbf{x}` + takes the place of the neighbour of :eq:`dg-least-squares-misfit`, with + the centroid :math:`\mathbf{c}_K` of the facet's cell: the misfit and the + weight of :class:`~sumfem.models.BoundaryMisfit`, averaged over each + facet :math:`F`, are + + .. math:: + :label: dg-least-squares-dirichlet-misfit + + \begin{aligned} + e &= \mathbf{G}_K \cdot (\mathbf{x} - \mathbf{c}_K) - (g - u_K), \\ + w &= \frac{1}{|\mathbf{x} - \mathbf{c}_K|^2\, |F|}. + \end{aligned} + + Args: + name: Name of the functional. + gradient: The gradient ``G``, piecewise constant. + field: The field ``u``, piecewise constant. + centroids: The centroids of the cells. + value: The boundary value ``g``. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + boundary. + """ + + def __init__( + self, + name: str, + gradient: Field, + field: Field, + centroids: ufl.core.expr.Expr, + value: ufl.core.expr.Expr | float, + markers: tuple[str, ...] = (), + ): + domain = gradient.domain + to_boundary = ufl.SpatialCoordinate(domain) - centroids + misfit = ufl.dot(gradient, to_boundary) - (as_expr(value) - field) + area = ufl.FacetArea(domain) + weight = 1 / (ufl.dot(to_boundary, to_boundary) * area) + super().__init__(name, misfit, weight, markers) + + +class LeastSquaresNeumannMisfit(BoundaryMisfit): + r"""The misfit of a gradient of piecewise constants to a zero normal derivative. + + On a boundary where the field has no normal derivative, e.g. a wall + without flux, the misfit and the weight of + :class:`~sumfem.models.BoundaryMisfit`, with the outward normal + :math:`\mathbf{n}` and averaged over each facet :math:`F`, are + + .. math:: + :label: dg-least-squares-neumann-misfit + + \begin{aligned} + e &= \mathbf{n} \cdot \mathbf{G}_K, \\ + w &= \frac{1}{|F|}. + \end{aligned} + + Args: + name: Name of the functional. + gradient: The gradient ``G``, piecewise constant. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + boundary. + """ + + def __init__(self, name: str, gradient: Field, markers: tuple[str, ...] = ()): + domain = gradient.domain + normal = ufl.dot(gradient, ufl.FacetNormal(domain)) + super().__init__(name, normal, 1 / ufl.FacetArea(domain), markers) + + +class NormalVelocityJump(Residual): + r"""The jump of the normal component of a velocity across the interior facets. + + The jumps :eq:`dg-normal-velocity-jump` vanish for a velocity of + continuous normal component; for one that jumps, + e.g. the gradient of a pressure of continuous elements, see + :class:`DivergenceCorrection`. + + Args: + name: Name of the model. + field: The field ``u``, of a discontinuous element. + velocity: The velocity ``beta``. + """ + + _field: Field + """The field.""" + _velocity: ufl.core.expr.Expr + """The velocity.""" + + def __init__( + self, + name: str, + field: Field, + velocity: ufl.core.expr.Expr | npt.ArrayLike, + ): + super().__init__(name) + self._field = field + self._velocity = as_expr(velocity) + + def residual(self) -> ufl.Form: + r"""The jumps times the average of the field and the test function. + + With the jump :math:`[\![\boldsymbol{\beta}]\!] \cdot \mathbf{n} = + \boldsymbol{\beta}^+ \cdot \mathbf{n}^+ + \boldsymbol{\beta}^- \cdot + \mathbf{n}^-`, + + .. math:: + :label: dg-normal-velocity-jump + + \begin{aligned} + j(u, w) &= \sum_F \int_F [\![\boldsymbol{\beta}]\!] \cdot \mathbf{n}\, + \{u\, w\} \,\mathrm{d}s. + \end{aligned} + + Returns: + The form over the interior facets. + """ + u, w, domain = self._field, self._field.v, self._field.domain + # Not ufl.jump(beta, n), which is a vector for a constant velocity + normal = ufl.dot(self._velocity, ufl.FacetNormal(domain)) + jump = normal("+") + normal("-") + return jump * ufl.avg(ufl.inner(u, w)) * domain.dS() + + +class DivergenceCorrection(ResidualSum): + r"""The source of a discrete flow that is not free of divergence, removed. + + A discrete velocity :math:`\boldsymbol{\beta}`, e.g. of Taylor-Hood + elements or the gradient of a Darcy pressure, has divergence in the cells + and, if discontinuous, jumps of its normal component across the facets. + With them, the conservative form of advection, the cells' term of + :class:`~sumfem.models.ConservativeAdvection` with :class:`UpwindFlux`, + :class:`~sumfem.models.Outflow` and the inflow + :math:`-\boldsymbol{\beta} \cdot \mathbf{n}\, g`, has a source: by + summation by parts over the cells, it is the convective form of + :class:`~sumfem.models.ConvectiveAdvection`, :class:`InteriorUpwinding` + and :class:`InflowBoundary` plus + + .. math:: + :label: dg-divergence-correction + + \begin{aligned} + s(u, w) &= \sum_K \int_K u\, \nabla \cdot \boldsymbol{\beta}\, w + \,\mathrm{d}x - j(u, w), + \end{aligned} + + with :math:`j` of :eq:`dg-normal-velocity-jump`, where the boundary + without these terms has :math:`\boldsymbol{\beta} \cdot \mathbf{n} = 0`. + By this source, a uniform field is not a solution of the conservative + form, and piles up where the discrete flow converges. The sum removes it, + so that the conservative form becomes the convective one, which keeps a + uniform field uniform for any velocity and degree; the field is then + conserved up to the divergence of the discrete flow, which vanishes as it + converges. It is the sum of: + + - ``"_cells"``: the divergence in the cells, a + :class:`~sumfem.models.Source` of :math:`u \nabla \cdot \boldsymbol{\beta}`, + unless it vanishes, e.g. for a piecewise constant velocity; + - ``"_facets"``: the jumps, :class:`NormalVelocityJump`. + + Of a drift that also has a physical divergence, e.g. by migration, the + conservative form of the whole drift keeps that divergence, and this sum + removes the flow's alone. + + Args: + name: Name of the sum, and prefix of its summands' names. + field: The field ``u``, of a discontinuous element. + velocity: The discrete velocity ``beta`` of the flow. + """ + + def __init__( + self, + name: str, + field: Field, + velocity: ufl.core.expr.Expr | npt.ArrayLike, + ): + beta = as_expr(velocity) + cells = Source(f"{name}_cells", field, field * ufl.div(beta)) + facets = NormalVelocityJump(f"{name}_facets", field, beta) + # Without divergence in the cells, e.g. of a piecewise constant + # velocity, the cells have no term + vanishes = expand_derivatives(cells.residual()).empty() + super().__init__([facets] if vanishes else [cells, facets], name=name) diff --git a/tests/models/test_dg.py b/tests/models/test_dg.py index 71cafb8..567309f 100644 --- a/tests/models/test_dg.py +++ b/tests/models/test_dg.py @@ -19,14 +19,19 @@ ConservativeAdvection, ConvectiveAdvection, Diffusion, + DivergenceCorrection, InflowBoundary, InteriorUpwinding, + LeastSquaresDirichletMisfit, LeastSquaresMisfit, + LeastSquaresNeumannMisfit, NitscheDirichlet, NonOrthogonalCorrection, + NonOrthogonalDirichletCorrection, Outflow, Reaction, Source, + TwoPointDirichlet, TwoPointFlux, UpwindFlux, WeightedInteriorPenalty, @@ -35,6 +40,8 @@ from sumfem.solvers import Solver from sumfem.symbolic import Domain, Field, KnownCoefficient, UFLResidual +from ..conftest import SIDES + CELLS = ["interval", "triangle", "tetrahedron"] """The cell types of the comparisons: simplices, where FFCx evaluates the cell volume of the sizes and distances of the models.""" @@ -207,9 +214,10 @@ def test_upwind_flux(cell, box, compare): @pytest.mark.parametrize("cell", CELLS) def test_two_point_flux_with_its_correction(cell, box, compare): - """The two-point fluxes of piecewise constants, the non-orthogonal - correction and the least-squares gradient, a second unknown, with a - boundary value on marked facets. + """The two-point fluxes of piecewise constants and the non-orthogonal + correction, with the least-squares gradient, a second unknown: a boundary + value on the left side, and a zero normal derivative fitted on the other + marked sides. """ gdim = ufl.Cell(cell).topological_dimension mesh, V = create_dg_space(cell, 0) @@ -249,20 +257,30 @@ def test_two_point_flux_with_its_correction(cell, box, compare): / (2 * ufl.dot(to_b, to_b) * area) * ufl.ds(1) ) + walls = SIDES[1:] if gdim > 1 else SIDES[1:2] + ids = tuple(range(2, 2 + len(walls))) + J += ufl.dot(n, Gh) ** 2 / (2 * area) * ufl.ds(ids) F += ufl.derivative(J, Gh, v) names = {DOMAIN: mesh, "kappa": kappa_h, "centroids": c_h} - plain = UFLResidual("plain", F, [uh, Gh], names=names, markers={"ds": {1: "Left"}}) + sides = {1: "Left", **dict(zip(ids, walls, strict=True))} + plain = UFLResidual("plain", F, [uh, Gh], names=names, markers={"ds": sides}) u = Field("u", domain, ("DG", 0)) G = Field("G", domain, ("DG", 0, (gdim,))) centroids = KnownCoefficient("centroids", domain, ("DG", 0, (gdim,))) x = ufl.SpatialCoordinate(domain) + value, left = 1 + x[gdim - 1], ("Left",) + misfit = ( + LeastSquaresMisfit("c", G, u, centroids) + + LeastSquaresDirichletMisfit("c_left", G, u, centroids, value, left) + + LeastSquaresNeumannMisfit("c_walls", G, walls) + ) model = ( - TwoPointFlux("a", u, kappa, 1 + x[gdim - 1], markers=("Left",)) - + NonOrthogonalCorrection("b", u, G, kappa, centroids, markers=("Left",)) - + LeastSquaresMisfit( - "c", G, u, centroids, 1 + x[gdim - 1], markers=("Left",) - ).to_residual([G]) + TwoPointFlux("a", u, kappa) + + TwoPointDirichlet("a_left", u, kappa, value, left) + + NonOrthogonalCorrection("b", u, G, kappa, centroids) + + NonOrthogonalDirichletCorrection("b_left", u, G, kappa, centroids, left) + + misfit.to_residual([G]) ) plain_values, model_values = create_diffusivity_values(plain, kappa, domain) plain_values["plain.centroids"] = ufl.SpatialCoordinate(plain.unknowns[0].domain) @@ -272,15 +290,52 @@ def test_two_point_flux_with_its_correction(cell, box, compare): ) -def test_conservative_and_convective_upwinding_agree(box, same_assembly): - """For a divergence-free velocity, the conservative form with its upwind - flux, outflow and inflow equals the convective form with its upwinding and - inflow: by summation by parts, their difference is the divergence.""" +def test_the_least_squares_gradient_of_a_linear_field_between_walls_is_exact(box): + """The field x, with its values on the left and right sides and walls at + the bottom and top, where its normal derivative vanishes, as the fit + takes it there: the gradient is (1, 0) in every cell, the corners too.""" + domain = Domain("square", "triangle") + u = Field("u", domain, ("DG", 0)) + G = Field("G", domain, ("DG", 0, (2,))) + centroids = KnownCoefficient("centroids", domain, ("DG", 0, (2,))) + x = ufl.SpatialCoordinate(domain) + misfit = ( + LeastSquaresMisfit("gradient", G, u, centroids) + + LeastSquaresDirichletMisfit("ends", G, u, centroids, x[0], ("Left", "Right")) + + LeastSquaresNeumannMisfit("walls", G, ("Bottom", "Top")) + ) + residual = misfit.to_residual([G]) + disc = discretize([residual], DomainMaps({domain: box("triangle")})) + disc.set({centroids: x}) + disc.function(u).interpolate(lambda p: p[0]) + (gradient,) = Solver(disc[residual]).solve() + values = gradient.x.array.reshape(-1, 2) + assert np.allclose(values, [1.0, 0.0], atol=1e-12) + + +@pytest.mark.parametrize("velocity", ["constant", "diverging", "piecewise"]) +def test_the_divergence_correction_makes_the_conservative_form_convective( + velocity, box, same_assembly +): + """The conservative form with its upwind flux, outflow and inflow, and the + correction of the divergence, equals the convective form with its + upwinding and inflow: by summation by parts, their difference is the + divergence in the cells and the jumps of the normal component across the + facets. For a constant velocity, without either, one with divergence, and + a piecewise constant one, whose normal component jumps; each is tangential + to the bottom and the top and enters through the left side.""" domain = Domain("square", "triangle") u = Field("u", domain, ("DG", 1)) x = ufl.SpatialCoordinate(domain) - beta, g = ufl.as_vector((2.0, 0.0)), 1 + x[1] - n = ufl.FacetNormal(domain) + known = {} + if velocity == "constant": + beta = ufl.as_vector((2.0, 0.0)) + elif velocity == "diverging": + beta = ufl.as_vector((2.0 + x[0], x[1] * (1 - x[1]))) + else: + beta = KnownCoefficient("beta", domain, ("DG", 0, (2,))) + known = {beta: ufl.as_vector((2.0 + x[0] + x[1], 0.0))} + g, n = 1 + x[1], ufl.FacetNormal(domain) convective = ( ConvectiveAdvection("cells", u, beta) + InteriorUpwinding("facets", u, beta) @@ -291,6 +346,7 @@ def test_conservative_and_convective_upwinding_agree(box, same_assembly): + UpwindFlux("facets", u, beta) + Outflow("outflow", u, beta, ("Right",)) + BoundaryFlux("inflow", u, -ufl.dot(beta, n) * g, ("Left",)) + + DivergenceCorrection("divergence", u, beta) ) maps = DomainMaps({domain: box("triangle")}) discretizations = [ @@ -300,6 +356,7 @@ def test_conservative_and_convective_upwinding_agree(box, same_assembly): 0.5, 1.5, discretizations[0].function(u).x.array.size ) for disc in discretizations: + disc.set(known) disc.function(u).x.array[:] = values disc.function(u).x.scatter_forward() same_assembly(discretizations[0][convective], discretizations[1][conservative]) @@ -335,14 +392,21 @@ def test_two_point_fluxes_converge_on_skewed_meshes_only_when_corrected(correct) model = ( Reaction("reaction", {u: 1}, {}, forward_rate=1.0) + Source("source", u, source) - + TwoPointFlux("two_point", u, kappa, exact) + + TwoPointFlux("two_point", u, kappa) + + TwoPointDirichlet("two_point_boundary", u, kappa, exact) ) if correct: G = Field("G", domain, ("DG", 0, (2,))) + misfit = LeastSquaresMisfit( + "gradient", G, u, centroids + ) + LeastSquaresDirichletMisfit("gradient_boundary", G, u, centroids, exact) model = ( model + NonOrthogonalCorrection("correction", u, G, kappa, centroids) - + LeastSquaresMisfit("gradient", G, u, centroids, exact).to_residual([G]) + + NonOrthogonalDirichletCorrection( + "correction_boundary", u, G, kappa, centroids + ) + + misfit.to_residual([G]) ) halves = ufl.conditional(ufl.lt(x[0], 0.5), kappa_left, kappa_right) errors = []