Skip to content
Merged
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
22 changes: 16 additions & 6 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,18 +70,14 @@ jobs:
image: ${{ matrix.image }}
asset: ${{ matrix.asset }}

deploy:
assemble:
needs: [plan, build]
# Publish whatever built: other versions keep their archived build
if: ${{ !cancelled() && needs.plan.result == 'success' }}
runs-on: ubuntu-latest
permissions:
contents: write # To keep the builds in the docs-archive release
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
pages: read # For the base path of the site, from configure-pages
env:
GH_TOKEN: ${{ github.token }}

Expand Down Expand Up @@ -143,6 +139,20 @@ jobs:
with:
path: site

# A job of its own: in the job that uploads the page artifact, deploy-pages can list the run's
# artifacts before the new one shows up, and fail (actions/deploy-pages#451). Re-running this
# job alone then deploys the artifact that is already uploaded.
deploy:
needs: assemble
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}

steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v5
3 changes: 3 additions & 0 deletions docs/api/symbolic.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
.. autoclass:: KnownCoefficient
:members:

.. autoclass:: Indicator
:members:

.. autofunction:: as_expr

.. autofunction:: value_at_defaults
Expand Down
151 changes: 135 additions & 16 deletions docs/getting_started/05_mesh_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
# - Create a {py:class}`sumfem.discrete.MeshData`, a mesh with named markers,
# from locator functions, from existing mesh tags, and from a Gmsh model
# - Look up the entities of a marker
# - Build an expression with a value on each region of marked cells
#
# A model refers to parts of its domain by marker names, e.g. a Dirichlet
# condition on `"Boundary"` or an integral `domain.ds("Inlet")`. A
# {py:class}`MeshData <sumfem.discrete.MeshData>` stores a
# {py:class}`dolfinx.mesh.Mesh` with its
# {py:class}`MeshTags <dolfinx.mesh.MeshTags>`, and for each entity dimension
# the tag values of each marker name. Below, each way of creating one marks the
# boundary of the unit square `"Boundary"`.
# boundary of the rectangle $[0, W] \times [0, H]$ `"Boundary"`.

# +
from mpi4py import MPI
Expand All @@ -35,8 +36,10 @@
import dolfinx.mesh
import gmsh
import numpy as np
import ufl

from sumfem import discrete
from sumfem import discrete, models, solvers, symbolic
from sumfem.post_processing import error

# -

Expand All @@ -45,15 +48,21 @@
# {py:meth}`from_locators <sumfem.discrete.MeshData.from_locators>` takes, for
# each entity dimension and marker name, a function of the coordinates as
# {py:func}`dolfinx.mesh.locate_entities` takes. With `boundary=True`, the
# facets are only looked for on the boundary. Here the cells of the left half
# are marked too:
# facets are only looked for on the boundary. Here the cells of the left and
# the right half are marked too:

square = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 16, 16)
tdim = square.topology.dim
width, height = 2.0, 1.5
rectangle = dolfinx.mesh.create_rectangle(
MPI.COMM_WORLD, [[0.0, 0.0], [width, height]], [16, 12]
)
tdim = rectangle.topology.dim
from_locators = discrete.MeshData.from_locators(
square,
rectangle,
{
tdim: {"LeftHalf": lambda x: x[0] <= 0.5 + 1e-10},
tdim: {
"LeftHalf": lambda x: x[0] <= width / 2 + 1e-10,
"RightHalf": lambda x: x[0] >= width / 2 - 1e-10,
},
tdim - 1: {"Boundary": lambda x: np.full(x.shape[1], True)},
},
boundary=True,
Expand Down Expand Up @@ -91,13 +100,13 @@ def print_markers(mesh_data):
# marker may stand for several values, e.g. `{"Walls": (2, 3)}`.

boundary_tag = 1
square.topology.create_connectivity(tdim - 1, tdim)
boundary_facets = dolfinx.mesh.exterior_facet_indices(square.topology)
rectangle.topology.create_connectivity(tdim - 1, tdim)
boundary_facets = dolfinx.mesh.exterior_facet_indices(rectangle.topology)
facet_tags = dolfinx.mesh.meshtags(
square, tdim - 1, boundary_facets, np.full_like(boundary_facets, boundary_tag)
rectangle, tdim - 1, boundary_facets, np.full_like(boundary_facets, boundary_tag)
)
from_tags = discrete.MeshData.from_meshtags(
square, {facet_tags: {"Boundary": (boundary_tag,)}}
rectangle, {facet_tags: {"Boundary": (boundary_tag,)}}
)

# The tag values differ from those `from_locators` chose, but the name marks
Expand All @@ -119,13 +128,13 @@ def print_markers(mesh_data):
gmsh.initialize()
gmsh.option.setNumber("General.Terminal", 0)
if MPI.COMM_WORLD.rank == 0:
gmsh.model.add("square")
surface = gmsh.model.occ.addRectangle(0.0, 0.0, 0.0, 1.0, 1.0)
gmsh.model.add("rectangle")
surface = gmsh.model.occ.addRectangle(0.0, 0.0, 0.0, width, height)
gmsh.model.occ.synchronize()
sides = [tag for _, tag in gmsh.model.getBoundary([(2, surface)], oriented=False)]
gmsh.model.addPhysicalGroup(2, [surface], tag=1, name="Square")
gmsh.model.addPhysicalGroup(2, [surface], tag=1, name="Rectangle")
gmsh.model.addPhysicalGroup(1, sides, tag=2, name="Boundary")
gmsh.option.setNumber("Mesh.CharacteristicLengthMax", 1 / 16)
gmsh.option.setNumber("Mesh.CharacteristicLengthMax", width / 16)
gmsh.model.mesh.generate(2)
gmsh_data = dolfinx.io.gmsh.model_to_mesh(gmsh.model, MPI.COMM_WORLD, 0, gdim=2)
gmsh.finalize()
Expand All @@ -135,3 +144,113 @@ def print_markers(mesh_data):
# model written with `"Boundary"` is discretized on any of these:

print_markers(from_gmsh)

# ## A value on each region
#
# A quantity that differs between regions of cells, e.g. the diffusivity of
# two materials, can be written as an expression of the markers of the
# regions. {py:meth}`piecewise <sumfem.symbolic.Domain.piecewise>` takes the
# value $K_i$ of each region $D_i$, given by its cell markers, and builds
#
# $$
# \begin{aligned}
# K(\mathbf{x}) &= \begin{cases}
# K_i & \text{if } \mathbf{x} \in D_i, \\
# 0 & \text{if } \mathbf{x} \text{ is in no region}.
# \end{cases}
# \end{aligned}
# $$ (mesh-data-piecewise)
#
# The regions must not overlap. The discretization finds the region of each
# cell from the markers of the mesh. A value $K_i$ is a number or any UFL
# expression, e.g. a {py:class}`Parameter <sumfem.symbolic.Parameter>`, set
# after discretization, or an expression of a field. Here $K$ is a
# diffusivity, of a liquid on the left half $D_L$ of the rectangle and of the
# liquid in a porous medium of porosity $\varepsilon$ on the right half $D_R$,
# corrected by {py:func}`bruggeman <sumfem.models.bruggeman>`:
#
# $$
# \begin{aligned}
# K_L &= K_0, \\
# K_R &= \varepsilon^{3/2} K_0.
# \end{aligned}
# $$ (mesh-data-bruggeman)
#
# The porosity is a parameter, so $K_R$ is an expression:

domain = symbolic.Domain("rectangle", "triangle")
K_0 = 1.0
porosity = symbolic.Parameter("porosity", domain, default=0.4)
K_L, K_R = K_0, models.bruggeman(K_0, porosity)
K = domain.piecewise({"LeftHalf": K_L, "RightHalf": K_R})

# In a model, it is an expression like any other. Unlike the hydrogen transport
# of {doc}`../tutorials/11_lagrange_multipliers`, with a field in each material
# coupled across the interface, $u$ is one field on both halves, and only its
# diffusivity jumps. We illustrate this with the diffusion
# $-\nabla \cdot (K \nabla u) = 0$, with $u$ given on the boundary, and the
# manufactured solution
#
# $$
# \begin{aligned}
# u(\mathbf{x}) &= \begin{cases}
# -q x / K_L & \text{if } \mathbf{x} \in D_L, \\
# 1 + q (W - x) / K_R & \text{if } \mathbf{x} \in D_R,
# \end{cases}
# \end{aligned}
# $$ (mesh-data-two-materials)
#
# where $q$ is the flux $-K\, \partial_x u$, the same through both halves:
#
# $$
# \begin{aligned}
# q &= -\frac{2 K_L K_R}{W (K_L + K_R)}.
# \end{aligned}
# $$ (mesh-data-flux)


# +
def create_exact_solution(x):
"""Create the exact solution, linear in x on each half.

Args:
x: The spatial coordinates.

Returns:
The solution as an expression.
"""
q = -2 * K_L * K_R / (width * (K_L + K_R))
left = -q * x[0] / K_L
right = 1 + q * (width - x[0]) / K_R
return ufl.conditional(ufl.le(x[0], width / 2), left, right)


u = symbolic.Field("u", domain, ("Lagrange", 1))
diffusion = models.Diffusion("diffusion", u, K)
exact = create_exact_solution(ufl.SpatialCoordinate(domain))
bcs = [symbolic.DirichletBC(u, "Boundary", exact)]
# -

# Each half is a union of cells, so the exact solution is linear on each cell,
# and the linear Lagrange solution matches it to round-off. `disc[exact]` is
# the exact solution in the discrete functions, with the value of the
# porosity:

disc = discrete.discretize([diffusion], discrete.DomainMaps({domain: from_locators}))
(solution,) = solvers.Solver(disc[diffusion], bcs).solve()
print(f"L2 error: {error(solution, disc[exact]):.2e}")
assert error(solution, disc[exact]) < 1e-10

# On an interior facet, `K("+")` and `K("-")` are the values in the two cells
# that share it, which a term on interior facets needs, e.g. the weighted
# averages of {py:class}`~sumfem.models.WeightedInteriorPenalty`, with a
# diffusivity that jumps between the halves in
# {doc}`../tutorials/13_weighted_averages`. The two values differ only on the
# facets between the halves, so the squared jump integrates to the squared
# difference of $K_L$ and $K_R$ times the length of the interface, the height
# $H$ of the rectangle:

jump = disc.assemble_scalar((K("+") - K("-")) ** 2 * domain.dS())
print(f"Integral of the squared jump of K: {jump:.6f}")
K_R_value = models.bruggeman(K_0, disc.value(porosity))
assert np.isclose(jump, (K_L - K_R_value) ** 2 * height)
33 changes: 32 additions & 1 deletion src/sumfem/discrete/discretization.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
Field,
FieldRole,
FieldTerminal,
Indicator,
KnownCoefficient,
Parameter,
TimeDerivative,
Expand Down Expand Up @@ -271,6 +272,8 @@ def _create(self, terminal: ufl.Coefficient) -> dolfinx.fem.Function:
f"{terminal.name!r} is a placeholder for a time derivative. "
"Replace it with a time-stepping scheme before discretizing."
)
elif isinstance(terminal, Indicator):
function = self._create_indicator(terminal)
elif isinstance(terminal, Parameter | KnownCoefficient):
space = self._shared_space(
domain_of(terminal.ufl_function_space()), terminal.ufl_element()
Expand All @@ -288,6 +291,28 @@ def _create(self, terminal: ufl.Coefficient) -> dolfinx.fem.Function:
)
return function

def _create_indicator(self, indicator: Indicator) -> dolfinx.fem.Function:
"""Create the function of an indicator, one on its marked cells.

Args:
indicator: The indicator.

Returns:
The piecewise constant function, with its ghost values.

Raises:
KeyError: If the mesh of its domain lacks one of its markers.
"""
domain = domain_of(indicator.ufl_function_space())
space = self._shared_space(domain, indicator.ufl_element())
function = dolfinx.fem.Function(space, name=indicator.name)
marked = self.maps.mesh_data(domain)
tdim = marked.mesh.topology.dim
cells = np.concatenate([marked.entities(tdim, m) for m in indicator.markers])
function.x.array[space.dofmap.list[cells, 0]] = 1.0
function.x.scatter_forward()
return function

def _by_name(
self, kind: type[Field | Parameter | KnownCoefficient]
) -> Mapping[str, dolfinx.fem.Function]:
Expand Down Expand Up @@ -384,10 +409,16 @@ def set(
Raises:
ValueError: If a sympy quantity has the wrong dimension, or an
expression the wrong shape.
TypeError: For an expression given to a parameter.
TypeError: For an expression given to a parameter, or any value
given to an :class:`~sumfem.symbolic.terminals.Indicator`.
"""
for key, value in values.items():
terminal = self.terminal(key)
if isinstance(terminal, Indicator):
raise TypeError(
f"Indicator {terminal.name!r} follows from the markers of "
"the mesh, and cannot be set."
)
function = self.function(terminal)
unit = _unit_of(terminal)
if _is_symbolic(value):
Expand Down
13 changes: 11 additions & 2 deletions src/sumfem/symbolic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
:class:`Weighted`: coordinate systems of domains, which weight their
integrals, e.g. for axisymmetric or radially symmetric bodies.
- :class:`Field`, :class:`Parameter`, :class:`KnownCoefficient`: the named
objects residuals and functionals are written with, with units.
objects residuals and functionals are written with, with units, and the
:class:`Indicator` of marked cells, from :meth:`Domain.indicator`, which
:meth:`Domain.piecewise` builds expressions with a value per region from.
- :class:`Residual`: a reusable contribution to a residual, summed with
``+`` into a :class:`ResidualSum`.
- :class:`Functional`: a reusable contribution to a scalar functional,
Expand Down Expand Up @@ -51,7 +53,13 @@
from .domains import Domain, Subdomain
from .expressions import as_expr
from .system import System, build_system
from .terminals import Field, KnownCoefficient, Parameter, value_at_defaults
from .terminals import (
Field,
Indicator,
KnownCoefficient,
Parameter,
value_at_defaults,
)
from .time import Clock, Dt
from .transfer import Assignment, Interpolation, Transfer, Transferable
from .ufl_forms import UFLResidual
Expand Down Expand Up @@ -99,6 +107,7 @@
"Domain",
"Field",
"KnownCoefficient",
"Indicator",
"Residual",
"Parameter",
"PiGroup",
Expand Down
Loading