Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/api/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@

.. autoclass:: DirichletMultiplier
:members:

.. autoclass:: BoundaryMisfit
:members:
```

## Facets of discontinuous fields
Expand All @@ -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
Expand Down
61 changes: 51 additions & 10 deletions docs/tutorials/13_weighted_averages.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,13 +291,15 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f):
# \end{aligned}
# $$ (weighted-inflow)
#
# {py:class}`InflowBoundary <sumfem.models.InflowBoundary>` holds it:
# {py:class}`InflowBoundary <sumfem.models.InflowBoundary>` holds it, as the
# inflow $q$ of a {py:class}`BoundaryFlux <sumfem.models.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
Expand Down Expand Up @@ -328,13 +330,24 @@ def create_advection_diffusion_reaction(u, kappa, beta, mu, f):
# \end{aligned}
# $$ (weighted-two-point)
#
# {py:class}`TwoPointFlux <sumfem.models.TwoPointFlux>` holds them:
# {py:class}`TwoPointFlux <sumfem.models.TwoPointFlux>` holds $a_I^0$, as the
# flux $\hat{F}$ of an {py:class}`InteriorFlux <sumfem.models.InteriorFlux>`,
# whose residual is $\sum_F \int_F \hat{F}\, [\![w]\!] \,\mathrm{d}s$, and
# {py:class}`TwoPointDirichlet <sumfem.models.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
Expand Down Expand Up @@ -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 <sumfem.models.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
Expand All @@ -392,15 +414,28 @@ 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 <sumfem.models.LeastSquaresMisfit>` is that
# functional:
# {py:class}`LeastSquaresMisfit <sumfem.models.LeastSquaresMisfit>` holds the
# terms of the neighbouring cells:
#
# ```{literalinclude} ../../src/sumfem/models/dg.py
# :language: python
# :pyobject: LeastSquaresMisfit
# :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 <sumfem.models.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
#
Expand Down Expand Up @@ -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
Expand Down
41 changes: 34 additions & 7 deletions src/sumfem/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -84,6 +103,7 @@
"ConvectiveAdvection",
"BoundaryConstraint",
"BoundaryFlux",
"BoundaryMisfit",
"Conduction",
"Diffusion",
"InterfaceLagrangeMultiplier",
Expand All @@ -100,11 +120,18 @@
"GradDiv",
"DirichletMultiplier",
"Outflow",
"DivergenceCorrection",
"InflowBoundary",
"InteriorFlux",
"InteriorUpwinding",
"LeastSquaresDirichletMisfit",
"LeastSquaresMisfit",
"LeastSquaresNeumannMisfit",
"NitscheDirichlet",
"NonOrthogonalCorrection",
"NonOrthogonalDirichletCorrection",
"NormalVelocityJump",
"TwoPointDirichlet",
"TwoPointFlux",
"UpwindFlux",
"WeightedInteriorPenalty",
Expand Down
82 changes: 79 additions & 3 deletions src/sumfem/models/boundary.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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)
Loading