diff --git a/docs/api/models.md b/docs/api/models.md index 8570a64..95a6fb6 100644 --- a/docs/api/models.md +++ b/docs/api/models.md @@ -48,6 +48,34 @@ :members: ``` +## Facets of discontinuous fields + +```{eval-rst} +.. autoclass:: WeightedInteriorPenalty + :members: + +.. autoclass:: NitscheDirichlet + :members: + +.. autoclass:: InteriorUpwinding + :members: + +.. autoclass:: InflowBoundary + :members: + +.. autoclass:: UpwindFlux + :members: + +.. autoclass:: TwoPointFlux + :members: + +.. autoclass:: NonOrthogonalCorrection + :members: + +.. autoclass:: LeastSquaresMisfit + :members: +``` + ## Interfaces ```{eval-rst} diff --git a/docs/tutorials/13_weighted_averages.py b/docs/tutorials/13_weighted_averages.py index b475ffb..f8184cd 100644 --- a/docs/tutorials/13_weighted_averages.py +++ b/docs/tutorials/13_weighted_averages.py @@ -194,46 +194,19 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f): # # The symmetric term keeps the diffusion symmetric in $u$ and $w$, as it is in # $a_\mathcal{K}$ of {eq}`weighted-by-parts`, and the penalty makes it stable -# for a large enough $\alpha$. A model holds the terms, a -# {py:class}`Residual ` as -# in {doc}`../getting_started/02_components`: - - -# + -class WeightedInteriorPenalty(symbolic.Residual): - """The weighted interior penalty of the diffusion on the interior facets. - - Args: - name: Name of the model. - field: The unknown, of a discontinuous element. - diffusivity: The diffusivity, constant in each cell. - penalty: The penalty constant. - """ - - def __init__(self, name, field, diffusivity, penalty): - super().__init__(name) - self.field = field - self.diffusivity = symbolic.as_expr(diffusivity) - self.penalty = symbolic.as_expr(penalty) - - def residual(self): - 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) - 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 - return (penalty - consistency) * domain.dS() - - -# - +# for a large enough $\alpha$. The model +# {py:class}`WeightedInteriorPenalty ` +# holds the terms, a {py:class}`Residual ` as in +# {doc}`../getting_started/02_components`. Its constructor keeps the +# arguments, as UFL expressions by {py:func}`as_expr `, +# and its residual builds the terms from them: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: WeightedInteriorPenalty +# :start-at: def __init__ +# :prepend: class WeightedInteriorPenalty(Residual): +# ``` # Where $\kappa^+ = \kappa^-$, $a_I$ is the symmetric interior penalty # method; where $\kappa$ jumps, it takes the diffusivity of each side. @@ -265,32 +238,15 @@ def residual(self): # In terms of fluxes, the two terms are upwinding, and for degree zero they # make the method for the flow the upwind finite volume scheme of Section 9.2 # of {footcite}`EYMARD2000713`, which also takes the boundary value where the -# flow enters, as the inflow term below does. A model holds them: - - -# + -class InteriorUpwinding(symbolic.Residual): - """The centered term of the flow and its upwinding on the interior facets. - - Args: - name: Name of the model. - field: The unknown, of a discontinuous element. - velocity: The velocity of the flow. - """ - - def __init__(self, name, field, velocity): - super().__init__(name) - self.field = field - self.velocity = symbolic.as_expr(velocity) - - def residual(self): - u, w = self.field, self.field.v - flux = ufl.dot(ufl.avg(self.velocity), ufl.FacetNormal(u.domain)("+")) - upwinding = 0.5 * abs(flux) * ufl.jump(w) - return (-flux * ufl.avg(w) + upwinding) * ufl.jump(u) * u.domain.dS() - - -# - +# flow enters, as the inflow term below does. +# {py:class}`InteriorUpwinding ` holds them: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: InteriorUpwinding +# :start-at: def __init__ +# :prepend: class InteriorUpwinding(Residual): +# ``` # Swapping the names of the sides leaves $b_I$ unchanged too. # @@ -312,40 +268,14 @@ def residual(self): # \end{aligned} # $$ (weighted-nitsche) # -# A model holds them: - - -# + -class NitscheBoundary(symbolic.Residual): - """Nitsche's terms of the diffusion with the boundary value. - - Args: - name: Name of the model. - field: The unknown, of a discontinuous element. - diffusivity: The diffusivity. - boundary_value: The boundary value. - penalty: The penalty constant. - """ - - def __init__(self, name, field, diffusivity, boundary_value, penalty): - super().__init__(name) - self.field = field - self.diffusivity = symbolic.as_expr(diffusivity) - self.boundary_value = symbolic.as_expr(boundary_value) - self.penalty = symbolic.as_expr(penalty) - - def residual(self): - u, w, kappa = self.field, self.field.v, self.diffusivity - n = ufl.FacetNormal(u.domain) - h = ufl.CellVolume(u.domain) / ufl.FacetArea(u.domain) - difference = u - self.boundary_value - flux_u = ufl.dot(kappa * ufl.grad(u), n) - flux_w = ufl.dot(kappa * ufl.grad(w), n) - penalty = self.penalty * kappa / h * difference * w - return (penalty - flux_u * w - difference * flux_w) * u.domain.ds() - - -# - +# {py:class}`NitscheDirichlet ` holds them: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: NitscheDirichlet +# :start-at: def __init__ +# :prepend: class NitscheDirichlet(Residual): +# ``` # Nitsche's method imposes the boundary value on the diffusion. The flow takes # it where it enters, where $\boldsymbol{\beta} \cdot \mathbf{n} < 0$, by the @@ -361,34 +291,14 @@ def residual(self): # \end{aligned} # $$ (weighted-inflow) # -# A model holds it: - - -# + -class InflowBoundary(symbolic.Residual): - """The boundary value where the flow enters. - - Args: - name: Name of the model. - field: The unknown, of a discontinuous element. - velocity: The velocity of the flow. - boundary_value: The boundary value. - """ - - def __init__(self, name, field, velocity, boundary_value): - super().__init__(name) - self.field = field - self.velocity = symbolic.as_expr(velocity) - self.boundary_value = symbolic.as_expr(boundary_value) - - def residual(self): - u, w = self.field, self.field.v - flux = ufl.dot(self.velocity, ufl.FacetNormal(u.domain)) - inflow = 0.5 * (abs(flux) - flux) - return inflow * (u - self.boundary_value) * w * u.domain.ds() - - -# - +# {py:class}`InflowBoundary ` holds it: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: InflowBoundary +# :start-at: def __init__ +# :prepend: class InflowBoundary(Residual): +# ``` # With the upwinding and the inflow term, and $\mu_0 > 0$ in # {eq}`weighted-assumptions`, the flow and the reaction control $u$ and its @@ -418,37 +328,14 @@ def residual(self): # \end{aligned} # $$ (weighted-two-point) # -# A model holds them: - - -# + -class TwoPointFlux(symbolic.Residual): - """The two-point fluxes of the diffusion of piecewise constants. - - Args: - name: Name of the model. - field: The unknown, piecewise constant. - diffusivity: The diffusivity, constant in each cell. - boundary_value: The boundary value. - """ - - def __init__(self, name, field, diffusivity, boundary_value): - super().__init__(name) - self.field = field - self.diffusivity = symbolic.as_expr(diffusivity) - self.boundary_value = symbolic.as_expr(boundary_value) - - def residual(self): - u, w, domain = self.field, self.field.v, self.field.domain - kappa, d = self.diffusivity, domain.topological_dimension - delta = d / (d + 1) * ufl.CellVolume(domain) / ufl.FacetArea(domain) - transmissibility = 1 / (delta("+") / kappa("+") + delta("-") / kappa("-")) - interior = transmissibility * ufl.jump(u) * ufl.jump(w) - boundary = kappa / delta * (u - self.boundary_value) * w - return interior * domain.dS() + boundary * domain.ds() - - -# - +# {py:class}`TwoPointFlux ` holds them: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: TwoPointFlux +# :start-at: def __init__ +# :prepend: class TwoPointFlux(Residual): +# ``` # The two-point flux is consistent only where the segment between the # centroids $\mathbf{c}^\pm$ of the two cells of a facet is orthogonal to it @@ -477,44 +364,16 @@ def residual(self): # $$ (weighted-correction) # # The centroids are a known coefficient, the coordinates interpolated into -# piecewise constants. A model holds the correction: - - -# + -class NonOrthogonalCorrection(symbolic.Residual): - """The flux along the facets that two-point fluxes miss on non-orthogonal meshes. - - Args: - name: Name of the model. - field: The unknown, piecewise constant. - gradient: The gradient of the unknown, piecewise constant. - diffusivity: The diffusivity, constant in each cell. - centroids: The centroids of the cells. - """ - - def __init__(self, name, field, gradient, diffusivity, centroids): - super().__init__(name) - self.field, self.gradient, self.centroids = field, gradient, centroids - self.diffusivity = symbolic.as_expr(diffusivity) - - def residual(self): - 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) - between = c("-") - c("+") - 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() - - -# - +# piecewise constants. +# {py:class}`NonOrthogonalCorrection ` +# holds the correction: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: NonOrthogonalCorrection +# :start-at: def __init__ +# :prepend: class NonOrthogonalCorrection(Residual): +# ``` # The gradient is a second unknown, fitted in each cell by least squares to # the values in the neighbouring cells, and to the boundary value on its @@ -532,47 +391,16 @@ def residual(self): # {py:class}`Functional ` of the gradient and the # 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: - - -# + -class LeastSquaresMisfit(symbolic.Functional): - """The misfit of a gradient of piecewise constants to the neighbouring values. - - Args: - name: Name of the functional. - gradient: The gradient, piecewise constant. - field: The unknown, piecewise constant. - centroids: The centroids of the cells. - boundary_value: The boundary value. - """ - - def __init__(self, name, gradient, field, centroids, boundary_value): - super().__init__(name) - self.gradient, self.field, self.centroids = gradient, field, centroids - self.boundary_value = symbolic.as_expr(boundary_value) - - def functional(self): - G, u, domain, c = ( - self.gradient, - self.field, - self.gradient.domain, - self.centroids, - ) - x, area = ufl.SpatialCoordinate(domain), 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.boundary_value - u) - boundary = misfit**2 / (2 * ufl.dot(to_boundary, to_boundary) * area) - return interior * domain.dS() + boundary * domain.ds() - - -# - +# of the gradient, the normal equations of the fit. +# {py:class}`LeastSquaresMisfit ` is that +# functional: +# +# ```{literalinclude} ../../src/sumfem/models/dg.py +# :language: python +# :pyobject: LeastSquaresMisfit +# :start-at: def __init__ +# :prepend: class LeastSquaresMisfit(Functional): +# ``` # ### The weighted-average method # @@ -615,29 +443,29 @@ def create_weighted_average_residual( Returns: The sum of the model of the equation and the models of the facets. """ - flow = InteriorUpwinding("interior_flow", u, beta) + InflowBoundary( + flow = models.InteriorUpwinding("interior_flow", u, beta) + models.InflowBoundary( "inflow", u, beta, g ) if u.ufl_element().degree > 0: return ( create_advection_diffusion_reaction(u, kappa, beta, mu, f) - + WeightedInteriorPenalty("interior_diffusion", u, kappa, penalty) - + NitscheBoundary("boundary_diffusion", u, kappa, g, penalty) + + models.WeightedInteriorPenalty("interior_diffusion", u, kappa, penalty) + + models.NitscheDirichlet("boundary_diffusion", u, kappa, g, penalty) + flow ) model = ( models.Reaction("reaction", {u: 1}, {}, forward_rate=mu) + models.Source("source", u, f) - + TwoPointFlux("two_point", u, kappa, g) + + models.TwoPointFlux("two_point", u, kappa, g) + flow ) if correct: shape = (u.domain.geometric_dimension,) G = symbolic.Field("G", u.domain, ("DG", 0, shape)) - misfit = LeastSquaresMisfit("gradient", G, u, centroids, g) + misfit = models.LeastSquaresMisfit("gradient", G, u, centroids, g) model = ( model - + NonOrthogonalCorrection("correction", u, G, kappa, centroids) + + models.NonOrthogonalCorrection("correction", u, G, kappa, centroids) + misfit.to_residual([G]) ) return model @@ -1111,7 +939,7 @@ def create_continuous_galerkin_problem(u, kappa, beta, mu, f, g): # a finite volume scheme of first order, which needs the non-orthogonal # correction where the facets are not orthogonal to the segments between the # centroids. -# + # ## References # # ```{footbibliography} diff --git a/src/sumfem/models/__init__.py b/src/sumfem/models/__init__.py index ccb415a..4acc5c7 100644 --- a/src/sumfem/models/__init__.py +++ b/src/sumfem/models/__init__.py @@ -7,6 +7,13 @@ - Boundaries: :class:`BoundaryFlux`, :class:`Outflow`, and constraints with Lagrange multipliers, :class:`BoundaryConstraint` and :class:`DirichletMultiplier`. +- 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`. - 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, @@ -29,6 +36,16 @@ from .advection import Advection, ConservativeAdvection, ConvectiveAdvection from .boundary import BoundaryConstraint, BoundaryFlux, DirichletMultiplier, Outflow from .charge import Conduction +from .dg import ( + InflowBoundary, + InteriorUpwinding, + LeastSquaresMisfit, + NitscheDirichlet, + NonOrthogonalCorrection, + TwoPointFlux, + UpwindFlux, + WeightedInteriorPenalty, +) from .diffusion import Accumulation, Diffusion, Poisson, Source from .flow import ( Brinkman, @@ -83,6 +100,14 @@ "GradDiv", "DirichletMultiplier", "Outflow", + "InflowBoundary", + "InteriorUpwinding", + "LeastSquaresMisfit", + "NitscheDirichlet", + "NonOrthogonalCorrection", + "TwoPointFlux", + "UpwindFlux", + "WeightedInteriorPenalty", "Poisson", "Source", "apply_coefficient", diff --git a/src/sumfem/models/dg.py b/src/sumfem/models/dg.py new file mode 100644 index 0000000..4ba937c --- /dev/null +++ b/src/sumfem/models/dg.py @@ -0,0 +1,580 @@ +"""Facet terms of discontinuous Galerkin and finite volume discretizations. + +The terms of a scalar equation of advection and diffusion on the facets of a +field of a discontinuous element, which the cell terms of +: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 +problems with discontinuous coefficients derives them and compares them. +""" + +from __future__ import annotations + +import numpy.typing as npt +import ufl + +from sumfem.symbolic import Field, Functional, Residual, as_expr + +__all__ = [ + "InflowBoundary", + "InteriorUpwinding", + "LeastSquaresMisfit", + "NitscheDirichlet", + "NonOrthogonalCorrection", + "TwoPointFlux", + "UpwindFlux", + "WeightedInteriorPenalty", +] + + +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. + Sum it with :class:`~sumfem.models.Diffusion` for the cells and + :class:`NitscheDirichlet` on the boundary; for piecewise constants, use + :class:`TwoPointFlux` instead. + + Args: + name: Name of the model. + field: The field ``u``, of a discontinuous element. + diffusivity: The scalar diffusivity ``kappa``. + penalty: The penalty constant ``alpha``, e.g. ten times the square of + the degree. + """ + + _field: Field + """The field.""" + _diffusivity: ufl.core.expr.Expr + """The diffusivity.""" + _penalty: ufl.core.expr.Expr + """The penalty constant.""" + + def __init__( + self, + name: str, + field: Field, + diffusivity: ufl.core.expr.Expr | float, + penalty: ufl.core.expr.Expr | float, + ): + super().__init__(name) + self._field = field + self._diffusivity = as_expr(diffusivity) + self._penalty = as_expr(penalty) + + def residual(self) -> ufl.Form: + 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) + 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 + 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. + + Args: + name: Name of the model. + field: The field ``u``. + diffusivity: The scalar diffusivity ``kappa``. + value: The boundary value ``g``. + penalty: The penalty constant ``alpha``. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + boundary. + """ + + _field: Field + """The field.""" + _diffusivity: ufl.core.expr.Expr + """The diffusivity.""" + _value: ufl.core.expr.Expr + """The boundary value.""" + _penalty: ufl.core.expr.Expr + """The penalty constant.""" + _markers: tuple[str, ...] + """Facet markers of the boundary.""" + + def __init__( + self, + name: str, + field: Field, + diffusivity: ufl.core.expr.Expr | float, + value: ufl.core.expr.Expr | float, + penalty: 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._penalty = as_expr(penalty) + self._markers = tuple(markers) + + def residual(self) -> ufl.Form: + u, w, domain = self._field, self._field.v, self._field.domain + kappa = self._diffusivity + n = ufl.FacetNormal(domain) + difference = u - self._value + 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 + 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) + `_). For piecewise constants it + is the upwind finite volume scheme. Sum it with + :class:`~sumfem.models.ConvectiveAdvection` and :class:`InflowBoundary`; + for a velocity that is not divergence free, use the conservative form, + :class:`UpwindFlux`. + + 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: + 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() + + +class InflowBoundary(Residual): + 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}`, + + .. 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, + \end{aligned} + + the upwinding of :class:`InteriorUpwinding` with the boundary value as + the value outside the domain. Where the flow leaves, it vanishes. + + Args: + name: Name of the model. + field: The field ``u``. + velocity: The velocity ``beta``. + value: The boundary value ``g``. + markers: Facet markers of the boundary ``Gamma``. Empty for the whole + 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, + field: Field, + velocity: ufl.core.expr.Expr | npt.ArrayLike, + value: ufl.core.expr.Expr | float, + markers: tuple[str, ...] = (), + ): + super().__init__(name) + self._field = field + self._velocity = as_expr(velocity) + 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 + flux = ufl.dot(self._velocity, ufl.FacetNormal(domain)) + inflow = 0.5 * (abs(flux) - flux) + return inflow * (u - self._value) * w * domain.ds(*self._markers) + + +class UpwindFlux(Residual): + 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, + + .. 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. + \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`. + + 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: + 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() + + +class TwoPointFlux(Residual): + 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 + + .. math:: + :label: dg-two-point-flux + + \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. + \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. + + 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, + 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 + 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) + + +class NonOrthogonalCorrection(Residual): + 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 + :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`: + + .. math:: + :label: dg-non-orthogonal-correction + + \begin{aligned} + \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. + \end{aligned} + + On meshes whose facets are orthogonal to the segments between the + centroids, e.g. crossed meshes of squares, it vanishes. + + 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, 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, + field: Field, + 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) + between = c("-") - c("+") + 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) + + +class LeastSquaresMisfit(Functional): + r"""The misfit of a gradient of piecewise constants to the neighbouring values. + + 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, + + .. 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} + + 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 functional. + gradient: The gradient ``G``, piecewise constant. + 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 + """The gradient.""" + _field: Field + """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, + name: str, + 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: + G, u, domain = self._gradient, self._field, self._gradient.domain + c = self._centroids + x, area = ufl.SpatialCoordinate(domain), 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) diff --git a/tests/models/test_dg.py b/tests/models/test_dg.py new file mode 100644 index 0000000..71cafb8 --- /dev/null +++ b/tests/models/test_dg.py @@ -0,0 +1,400 @@ +"""The facet models of discontinuous fields against plain UFL, and their convergence. + +Each model is compared with its terms written in plain UFL, on fields of a +discontinuous element and a diffusivity constant in each cell, so that it +jumps between cells. The convergence tests solve with the models. +""" + +from mpi4py import MPI + +import dolfinx.mesh +import numpy as np +import pytest +import ufl +from basix.ufl import element + +from sumfem.discrete import DomainMaps, MeshData, discretize +from sumfem.models import ( + BoundaryFlux, + ConservativeAdvection, + ConvectiveAdvection, + Diffusion, + InflowBoundary, + InteriorUpwinding, + LeastSquaresMisfit, + NitscheDirichlet, + NonOrthogonalCorrection, + Outflow, + Reaction, + Source, + TwoPointFlux, + UpwindFlux, + WeightedInteriorPenalty, +) +from sumfem.post_processing import norm +from sumfem.solvers import Solver +from sumfem.symbolic import Domain, Field, KnownCoefficient, UFLResidual + +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.""" + +DOMAIN = "box" +"""The name of the symbolic domain of both formulations, see ``compare``.""" + + +def create_dg_space(cell, degree, shape=()): + """Create a plain UFL mesh and a space of discontinuous Lagrange elements on it. + + Args: + cell: The cell type. + degree: The degree of the elements. + shape: The value shape. + + Returns: + The mesh and the space. + """ + gdim = ufl.Cell(cell).topological_dimension + mesh = ufl.Mesh(element("Lagrange", cell, 1, shape=(gdim,))) + return mesh, ufl.FunctionSpace(mesh, element("DG", cell, degree, shape=shape)) + + +def create_diffusivity(mesh, domain): + """Create a diffusivity constant in each cell for both formulations. + + Args: + mesh: The plain UFL mesh. + domain: The symbolic domain of the model. + + Returns: + The plain coefficient and the model's known coefficient. + """ + cell = mesh.ufl_cell().cellname + kappa_h = ufl.Coefficient(ufl.FunctionSpace(mesh, element("DG", cell, 0))) + return kappa_h, KnownCoefficient("kappa", domain, ("DG", 0)) + + +def create_diffusivity_values(plain, kappa, domain): + """Create the values of the diffusivity of both formulations. + + Args: + plain: The ``UFLResidual``, whose diffusivity is named ``"kappa"``. + kappa: The model's known coefficient. + domain: The symbolic domain of the model. + + Returns: + The values of each, an expression of the coordinates interpolated into + each cell, so that it jumps between cells. + """ + xh = ufl.SpatialCoordinate(plain.unknowns[0].domain) + x = ufl.SpatialCoordinate(domain) + return {"plain.kappa": 1 + 3 * xh[0] ** 2}, {kappa: 1 + 3 * x[0] ** 2} + + +@pytest.mark.parametrize("cell", CELLS) +def test_weighted_interior_penalty(cell, box, compare): + """The weighted averages and the penalty of a diffusivity that jumps.""" + mesh, V = create_dg_space(cell, 2) + uh, w = ufl.Coefficient(V), ufl.TestFunction(V) + domain = Domain(DOMAIN, cell) + kappa_h, kappa = create_diffusivity(mesh, domain) + kp, km = kappa_h("+"), kappa_h("-") + n, h = ( + ufl.FacetNormal(mesh)("+"), + ufl.avg(ufl.CellVolume(mesh) / ufl.FacetArea(mesh)), + ) + flux_u = (km * kp * ufl.grad(uh)("+") + kp * km * ufl.grad(uh)("-")) / (kp + km) + flux_w = (km * kp * ufl.grad(w)("+") + kp * km * ufl.grad(w)("-")) / (kp + km) + gamma = kp * km / (kp + km) + F = ( + 10.0 * gamma / h * ufl.jump(uh) * ufl.jump(w) + - ufl.dot(flux_u, n) * ufl.jump(w) + - ufl.dot(flux_w, n) * ufl.jump(uh) + ) * ufl.dS + plain = UFLResidual("plain", F, uh, names={DOMAIN: mesh, "kappa": kappa_h}) + + u = Field("u", domain, ("DG", 2)) + model = WeightedInteriorPenalty("a", u, kappa, 10.0) + compare( + plain, + [plain.field], + model, + [u], + box(cell), + [create_diffusivity_values(plain, kappa, domain)], + ) + + +@pytest.mark.parametrize("cell", CELLS) +def test_nitsche_dirichlet(cell, box, compare): + """Nitsche's terms of a boundary value on marked facets.""" + gdim = ufl.Cell(cell).topological_dimension + mesh, V = create_dg_space(cell, 1) + uh, w = ufl.Coefficient(V), ufl.TestFunction(V) + domain = Domain(DOMAIN, cell) + kappa_h, kappa = create_diffusivity(mesh, domain) + xh, n = ufl.SpatialCoordinate(mesh), ufl.FacetNormal(mesh) + g, h = 1 + xh[gdim - 1], ufl.CellVolume(mesh) / ufl.FacetArea(mesh) + flux_u, flux_w = ( + kappa_h * ufl.dot(ufl.grad(uh), n), + kappa_h * ufl.dot(ufl.grad(w), n), + ) + F = (5.0 * kappa_h / h * (uh - g) * w - flux_u * w - (uh - g) * flux_w) * ufl.ds(1) + names = {DOMAIN: mesh, "kappa": kappa_h} + plain = UFLResidual("plain", F, uh, names=names, markers={"ds": {1: "Left"}}) + + u = Field("u", domain, ("DG", 1)) + x = ufl.SpatialCoordinate(domain) + model = NitscheDirichlet("a", u, kappa, 1 + x[gdim - 1], 5.0, markers=("Left",)) + compare( + plain, + [plain.field], + model, + [u], + box(cell), + [create_diffusivity_values(plain, kappa, domain)], + ) + + +@pytest.mark.parametrize("cell", CELLS) +def test_upwinding_in_convective_form(cell, box, compare): + """Upwinding on the interior facets and the inflow of a boundary value, by + a velocity that varies in space and enters through the left side. + """ + gdim = ufl.Cell(cell).topological_dimension + mesh, V = create_dg_space(cell, 1) + uh, w = ufl.Coefficient(V), ufl.TestFunction(V) + xh, n = ufl.SpatialCoordinate(mesh), ufl.FacetNormal(mesh) + beta_h = ufl.as_vector([1.0 + i + xh[i] for i in range(gdim)]) + flux = ufl.dot(ufl.avg(beta_h), n("+")) + g, flux_b = 1 + xh[gdim - 1], ufl.dot(beta_h, n) + F = ( + 0.5 * abs(flux) * ufl.jump(uh) * ufl.jump(w) - flux * ufl.jump(uh) * ufl.avg(w) + ) * ufl.dS + F += 0.5 * (abs(flux_b) - flux_b) * (uh - g) * w * ufl.ds(1) + plain = UFLResidual( + "plain", F, uh, names={DOMAIN: mesh}, markers={"ds": {1: "Left"}} + ) + + domain = Domain(DOMAIN, cell) + u = Field("u", domain, ("DG", 1)) + x = ufl.SpatialCoordinate(domain) + beta = ufl.as_vector([1.0 + i + x[i] for i in range(gdim)]) + model = InteriorUpwinding("a", u, beta) + InflowBoundary( + "b", u, beta, 1 + x[gdim - 1], markers=("Left",) + ) + compare(plain, [plain.field], model, [u], box(cell)) + + +@pytest.mark.parametrize("cell", CELLS) +def test_upwind_flux(cell, box, compare): + """The upwind flux of the conservative form on the interior facets.""" + gdim = ufl.Cell(cell).topological_dimension + mesh, V = create_dg_space(cell, 1) + uh, w = ufl.Coefficient(V), ufl.TestFunction(V) + xh = ufl.SpatialCoordinate(mesh) + beta_h = ufl.as_vector([1.0 + i + xh[i] for i in range(gdim)]) + flux = ufl.dot(ufl.avg(beta_h), ufl.FacetNormal(mesh)("+")) + F = (flux * ufl.avg(uh) + 0.5 * abs(flux) * ufl.jump(uh)) * ufl.jump(w) * ufl.dS + plain = UFLResidual("plain", F, uh, names={DOMAIN: mesh}) + + domain = Domain(DOMAIN, cell) + u = Field("u", domain, ("DG", 1)) + x = ufl.SpatialCoordinate(domain) + model = UpwindFlux("a", u, ufl.as_vector([1.0 + i + x[i] for i in range(gdim)])) + compare(plain, [plain.field], model, [u], box(cell)) + + +@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. + """ + gdim = ufl.Cell(cell).topological_dimension + mesh, V = create_dg_space(cell, 0) + Q = ufl.FunctionSpace(mesh, element("DG", cell, 0, shape=(gdim,))) + W = ufl.MixedFunctionSpace(V, Q) + uh, Gh = ufl.Coefficient(V), ufl.Coefficient(Q) + w, v = ufl.TestFunctions(W) + domain = Domain(DOMAIN, cell) + kappa_h, kappa = create_diffusivity(mesh, domain) + c_h = ufl.Coefficient(Q) + xh, n, area = ( + ufl.SpatialCoordinate(mesh), + ufl.FacetNormal(mesh), + ufl.FacetArea(mesh), + ) + g = 1 + xh[gdim - 1] + delta = gdim / (gdim + 1) * ufl.CellVolume(mesh) / area + T = 1 / (delta("+") / kappa_h("+") + delta("-") / kappa_h("-")) + between = c_h("-") - c_h("+") + k = n("+") - between / ufl.dot(between, n("+")) + k_b = n - (xh - c_h) / ufl.dot(xh - c_h, n) + kappa_T = (delta("+") + delta("-")) * T + F = (T * ufl.jump(uh) - kappa_T * ufl.dot(k, ufl.avg(Gh))) * ufl.jump(w) * ufl.dS + F += (kappa_h / delta * (uh - g) - kappa_h * ufl.dot(k_b, Gh)) * w * ufl.ds(1) + difference = uh("-") - uh("+") + J = ( + ( + (ufl.dot(between, Gh("+")) - difference) ** 2 + + (ufl.dot(between, Gh("-")) - difference) ** 2 + ) + / (2 * ufl.dot(between, between) * area("+")) + * ufl.dS + ) + to_b = xh - c_h + J += ( + (ufl.dot(to_b, Gh) - (g - uh)) ** 2 + / (2 * ufl.dot(to_b, to_b) * area) + * ufl.ds(1) + ) + 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"}}) + + u = Field("u", domain, ("DG", 0)) + G = Field("G", domain, ("DG", 0, (gdim,))) + centroids = KnownCoefficient("centroids", domain, ("DG", 0, (gdim,))) + x = ufl.SpatialCoordinate(domain) + 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]) + ) + plain_values, model_values = create_diffusivity_values(plain, kappa, domain) + plain_values["plain.centroids"] = ufl.SpatialCoordinate(plain.unknowns[0].domain) + model_values[centroids] = x + compare( + plain, plain.unknowns, model, [u, G], box(cell), [(plain_values, model_values)] + ) + + +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.""" + 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) + convective = ( + ConvectiveAdvection("cells", u, beta) + + InteriorUpwinding("facets", u, beta) + + InflowBoundary("inflow", u, beta, g, markers=("Left",)) + ) + conservative = ( + ConservativeAdvection("cells", u, beta) + + UpwindFlux("facets", u, beta) + + Outflow("outflow", u, beta, ("Right",)) + + BoundaryFlux("inflow", u, -ufl.dot(beta, n) * g, ("Left",)) + ) + maps = DomainMaps({domain: box("triangle")}) + discretizations = [ + discretize([model], maps) for model in (convective, conservative) + ] + values = np.random.default_rng(seed=MPI.COMM_WORLD.rank).uniform( + 0.5, 1.5, discretizations[0].function(u).x.array.size + ) + for disc in discretizations: + disc.function(u).x.array[:] = values + disc.function(u).x.scatter_forward() + same_assembly(discretizations[0][convective], discretizations[1][conservative]) + + +def create_exact_solution(x, kappa, kappa_left): + """Create a solution that varies along a jump at x = 1/2, continuous with its flux. + + Args: + x: The spatial coordinates. + kappa: The diffusivity, constant on each half. + kappa_left: The diffusivity of the left half. + + Returns: + The solution. + """ + return ufl.sin(ufl.pi * x[1]) * (1 + kappa_left * (x[0] - 0.5) / kappa) + + +@pytest.mark.parametrize("correct", [True, False]) +def test_two_point_fluxes_converge_on_skewed_meshes_only_when_corrected(correct): + """Diffusion and reaction of piecewise constants across a jump, on crossed + meshes sheared at the jump and compressed on its left: with the correction + the error falls at first order, without it the rate falls.""" + kappa_left, kappa_right = 0.1, 0.01 + domain = Domain("square", "triangle") + kappa = KnownCoefficient("kappa", domain, ("DG", 0)) + centroids = KnownCoefficient("centroids", domain, ("DG", 0, (2,))) + u = Field("u", domain, ("DG", 0)) + x = ufl.SpatialCoordinate(domain) + exact = create_exact_solution(x, kappa, kappa_left) + source = -ufl.div(kappa * ufl.grad(exact)) + exact + model = ( + Reaction("reaction", {u: 1}, {}, forward_rate=1.0) + + Source("source", u, source) + + TwoPointFlux("two_point", u, kappa, exact) + ) + if correct: + G = Field("G", domain, ("DG", 0, (2,))) + model = ( + model + + NonOrthogonalCorrection("correction", u, G, kappa, centroids) + + LeastSquaresMisfit("gradient", G, u, centroids, exact).to_residual([G]) + ) + halves = ufl.conditional(ufl.lt(x[0], 0.5), kappa_left, kappa_right) + errors = [] + for n in (16, 32, 64): + mesh = dolfinx.mesh.create_unit_square( + MPI.COMM_WORLD, n, n, diagonal=dolfinx.mesh.DiagonalType.crossed + ) + p = mesh.geometry.x + left = p[:, 0] < 0.5 + p[left, 0] += 0.05 * np.sin(2 * np.pi * p[left, 0]) + p[:, 1] += 0.05 * np.sin(np.pi * p[:, 1]) * np.sin(2 * np.pi * p[:, 0]) + disc = discretize([model], DomainMaps({domain: MeshData(mesh)})) + known = {kappa: halves, centroids: x} + disc.set({c: value for c, value in known.items() if c in disc}) + solution = Solver(disc[model]).solve()[0] + y = ufl.SpatialCoordinate(mesh) + errors.append( + norm(solution - create_exact_solution(y, disc[kappa], kappa_left)) + ) + rates = np.log2(np.array(errors[:-1]) / np.array(errors[1:])) + assert (rates.min() > 1 - 0.15) == correct + + +def test_weighted_interior_penalty_converges_across_a_jump(): + """Diffusion and reaction of a field of degree one across a jump, with the + weighted interior penalty and Nitsche's terms: rate two.""" + kappa_left, kappa_right = 0.1, 0.01 + domain = Domain("square", "triangle") + kappa = KnownCoefficient("kappa", domain, ("DG", 0)) + u = Field("u", domain, ("DG", 1)) + x = ufl.SpatialCoordinate(domain) + exact = create_exact_solution(x, kappa, kappa_left) + source = -ufl.div(kappa * ufl.grad(exact)) + exact + model = ( + Diffusion("diffusion", u, kappa) + + Reaction("reaction", {u: 1}, {}, forward_rate=1.0) + + Source("source", u, source) + + WeightedInteriorPenalty("interior", u, kappa, 10.0) + + NitscheDirichlet("boundary", u, kappa, exact, 10.0) + ) + halves = ufl.conditional(ufl.lt(x[0], 0.5), kappa_left, kappa_right) + errors = [] + for n in (8, 16, 32): + mesh = dolfinx.mesh.create_unit_square( + MPI.COMM_WORLD, n, n, diagonal=dolfinx.mesh.DiagonalType.crossed + ) + disc = discretize([model], DomainMaps({domain: MeshData(mesh)})) + disc.set({kappa: halves}) + solution = Solver(disc[model]).solve()[0] + y = ufl.SpatialCoordinate(mesh) + errors.append( + norm(solution - create_exact_solution(y, disc[kappa], kappa_left)) + ) + rates = np.log2(np.array(errors[:-1]) / np.array(errors[1:])) + assert rates.min() > 2 - 0.15