From 8a5310d3d7044b8082c0b90ed26c556cd5303a1f Mon Sep 17 00:00:00 2001 From: Jorgen Schartum Dokken Date: Tue, 1 Dec 2026 11:44:55 +0000 Subject: [PATCH 1/2] Add Indicator function and remove some duplicate tests. --- docs/api/symbolic.md | 3 + docs/getting_started/05_mesh_data.py | 151 +++++++++++++++++++++--- src/sumfem/discrete/discretization.py | 33 +++++- src/sumfem/symbolic/__init__.py | 13 +- src/sumfem/symbolic/domains.py | 86 ++++++++++++++ src/sumfem/symbolic/terminals.py | 90 +++++++++++++- tests/discrete/test_discretization.py | 83 +++++++++++++ tests/discrete/test_weighted_average.py | 24 ++-- tests/symbolic/test_terminals.py | 31 +++++ 9 files changed, 483 insertions(+), 31 deletions(-) diff --git a/docs/api/symbolic.md b/docs/api/symbolic.md index d31bbd1..5cee86c 100644 --- a/docs/api/symbolic.md +++ b/docs/api/symbolic.md @@ -43,6 +43,9 @@ .. autoclass:: KnownCoefficient :members: +.. autoclass:: Indicator + :members: + .. autofunction:: as_expr .. autofunction:: value_at_defaults diff --git a/docs/getting_started/05_mesh_data.py b/docs/getting_started/05_mesh_data.py index 2146c6e..8007d0c 100644 --- a/docs/getting_started/05_mesh_data.py +++ b/docs/getting_started/05_mesh_data.py @@ -19,6 +19,7 @@ # - 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 @@ -26,7 +27,7 @@ # {py:class}`dolfinx.mesh.Mesh` with its # {py:class}`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 @@ -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 # - @@ -45,15 +48,21 @@ # {py:meth}`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, @@ -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 @@ -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() @@ -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 ` 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 `, 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 `: +# +# $$ +# \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) diff --git a/src/sumfem/discrete/discretization.py b/src/sumfem/discrete/discretization.py index 58b279e..a4745e5 100644 --- a/src/sumfem/discrete/discretization.py +++ b/src/sumfem/discrete/discretization.py @@ -44,6 +44,7 @@ Field, FieldRole, FieldTerminal, + Indicator, KnownCoefficient, Parameter, TimeDerivative, @@ -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() @@ -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]: @@ -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): diff --git a/src/sumfem/symbolic/__init__.py b/src/sumfem/symbolic/__init__.py index 3f9f317..26dc24e 100644 --- a/src/sumfem/symbolic/__init__.py +++ b/src/sumfem/symbolic/__init__.py @@ -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, @@ -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 @@ -99,6 +107,7 @@ "Domain", "Field", "KnownCoefficient", + "Indicator", "Residual", "Parameter", "PiGroup", diff --git a/src/sumfem/symbolic/domains.py b/src/sumfem/symbolic/domains.py index 89bd178..e2c8aba 100644 --- a/src/sumfem/symbolic/domains.py +++ b/src/sumfem/symbolic/domains.py @@ -2,10 +2,12 @@ import functools import typing +from collections.abc import Mapping import basix import dolfinx import dolfinx.mesh +import numpy.typing as npt import ufl from basix.ufl import element from ufl.domain import extract_domains @@ -14,6 +16,9 @@ from ..error_handling import ComponentError, check_name, qualified_name from .coordinates import Cartesian, CoordinateSystem +if typing.TYPE_CHECKING: + from .terminals import Indicator + __all__ = [ "MEASURE_ENTITY_TYPE", "EntityType", @@ -139,6 +144,9 @@ class Domain(ufl.Mesh): _measures: dict[MeasureName, ufl.Measure] """Measure over the whole domain, per integral type, created on first use.""" + _indicators: dict[tuple[str, ...], Indicator] + """Indicator of each set of cell markers, created on first use.""" + _one_sided: dict[str, tuple[Subdomain, str | None]] """Facet markers seen from one side: the subdomain of cells on that side, and its own facet marker, or ``None`` for its whole boundary.""" @@ -174,6 +182,7 @@ def __init__( self._name = name self._markers = {dim: {} for dim in range(self.tdim + 1)} self._measures = {} + self._indicators = {} self._one_sided = {} self._interfaces = {} self._length_scale = float(length_scale) @@ -337,6 +346,83 @@ def measure( subdomain_id = self.marker_ids(markers, entity_type) if markers else None return base(subdomain_id, metadata=metadata, degree=degree) + def indicator(self, *markers: str) -> Indicator: + """The indicator of the cells with any of some markers. + + One on those cells and zero on the others, see + :class:`~sumfem.symbolic.terminals.Indicator`. Indicators are cached, + so the same markers, in the same order, give the same indicator, and + the discretization fills one function for them. + + Args: + markers: Cell markers, at least one. + + Returns: + The indicator. + """ + from .terminals import Indicator + + if markers not in self._indicators: + self._indicators[markers] = Indicator(self, markers) + return self._indicators[markers] + + def piecewise( + self, + values: Mapping[str | tuple[str, ...], ufl.core.expr.Expr | npt.ArrayLike], + ) -> ufl.core.expr.Expr: + r"""One expression over the union of regions, each region's value on it. + + For the regions :math:`D_i` and their values :math:`K_i`, the keys + and values of ``values``, built from the :meth:`indicator` + :math:`\chi_{D_i}` of each region: + + .. math:: + :label: domain-piecewise + + \begin{aligned} + K(\mathbf{x}) &= \begin{cases} + K_i & \text{if } \mathbf{x} \in D_i, \\ + 0 & \text{if } \mathbf{x} \notin \textstyle\bigcup_i D_i, + \end{cases} \\ + D_i \cap D_j &= \emptyset \text{ for } i \neq j. + \end{aligned} + + Note: + A cell takes its region's value through nested conditionals on the + indicators, so a value that is infinite or not a number outside its + region is never used there, unlike in the sum + :math:`\sum_i \chi_{D_i} K_i`, which can be written with + :meth:`indicator`. + + Example: + A diffusivity of the electrode and of the channels. On an + interior facet, ``K("+")`` and ``K("-")`` are its values in the + two cells that share the facet, in an order the mesh gives each + facet. A term that is unchanged when they swap, such as their + harmonic mean in an interior penalty, needs no orientation, and + takes the value of both regions on a facet between them:: + + channels = ("InletChannel", "OutletChannel") + K = domain.piecewise({"Electrode": K_E, channels: K_C}) + mean = 2 * K("+") * K("-") / (K("+") + K("-")) + penalty = mean / h * ufl.jump(c) * ufl.jump(v) * domain.dS() + + Args: + values: The value :math:`K_i` of each region :math:`D_i`. A key + is a cell marker, or a tuple of cell markers whose cells + together make the region. A value is an expression, e.g. a + parameter or an expression of a field, or a number. + + Returns: + The expression. + + Raises: + ComponentError: Without regions, or if the values differ in shape. + """ + from .terminals import create_piecewise + + return create_piecewise(self, values) + # Shortcuts for measure() with the integral type bound. Each takes # (*markers, degree=None, metadata=None). dx = functools.partialmethod(measure, "dx") diff --git a/src/sumfem/symbolic/terminals.py b/src/sumfem/symbolic/terminals.py index 534bddf..8d8710c 100644 --- a/src/sumfem/symbolic/terminals.py +++ b/src/sumfem/symbolic/terminals.py @@ -25,6 +25,7 @@ import numbers import typing import weakref +from collections.abc import Mapping import basix.ufl import numpy as np @@ -39,7 +40,7 @@ from ..error_handling import ComponentError, check_name, qualified_name from .domains import Domain, domain_of from .elements import ElementSpec, as_element -from .expressions import evaluate_constant +from .expressions import as_expr, evaluate_constant from .si import Unit, has_units, si_factor, to_si _PIOLA = ( @@ -55,6 +56,7 @@ "Field", "FieldRole", "FieldTerminal", + "Indicator", "KnownCoefficient", "Parameter", "TimeDerivative", @@ -648,3 +650,89 @@ def element(self) -> AbstractFiniteElement: def doc(self) -> str: """Description of the data.""" return self._doc + + +class Indicator(KnownCoefficient): + r"""The indicator of marked cells: one on them and zero on the others. + + For a region :math:`R` of cells, + + .. math:: + :label: indicator + + \begin{aligned} + \chi_R(\mathbf{x}) &= \begin{cases} + 1 & \text{if } \mathbf{x} \in R, \\ + 0 & \text{otherwise}, + \end{cases} + \end{aligned} + + in DG0, filled by the discretization from the cell markers of its mesh + and not settable. Create it with + :meth:`~sumfem.symbolic.domains.Domain.indicator`, and build an + expression with a value per region with + :meth:`~sumfem.symbolic.domains.Domain.piecewise`, which takes on each + side of an interior facet the value of that side's region. + + Args: + domain: The domain of the markers. + markers: The cell markers, at least one. + + Raises: + ComponentError: Without markers. + """ + + _markers: tuple[str, ...] + """The cell markers.""" + + def __init__(self, domain: Domain, markers: tuple[str, ...]): + if not markers: + raise ComponentError("An indicator needs at least one cell marker.") + super().__init__( + f"{domain.name}.indicator[{','.join(markers)}]", + domain, + ("DG", 0), + doc=f"One on the cells marked {', '.join(markers)}, zero elsewhere", + ) + self._markers = tuple(markers) + + @property + def markers(self) -> tuple[str, ...]: + """The cell markers.""" + return self._markers + + +def create_piecewise( + domain: Domain, + values: Mapping[str | tuple[str, ...], ufl.core.expr.Expr | npt.ArrayLike], +) -> ufl.core.expr.Expr: + """Create one expression over the union of regions, each region's value on it. + + See :meth:`~sumfem.symbolic.domains.Domain.piecewise`, which calls it. + + Args: + domain: The domain of the regions. + values: The value of each region, by its key, a cell marker or a + tuple of cell markers. + + Returns: + The expression. + + Raises: + ComponentError: Without regions, or if the values differ in shape. + """ + if not values: + raise ComponentError("A piecewise expression needs at least one region.") + regions = [ + (domain.indicator(*((key,) if isinstance(key, str) else key)), as_expr(v)) + for key, v in values.items() + ] + shapes = {value.ufl_shape for _, value in regions} + if len(shapes) > 1: + raise ComponentError( + f"The values of a piecewise expression differ in shape: {shapes}." + ) + expression = ufl.zero(*shapes.pop()) + for chi, value in reversed(regions): + expression = ufl.conditional(ufl.eq(chi, 1.0), value, expression) + return expression diff --git a/tests/discrete/test_discretization.py b/tests/discrete/test_discretization.py index d744bf1..642388a 100644 --- a/tests/discrete/test_discretization.py +++ b/tests/discrete/test_discretization.py @@ -11,6 +11,7 @@ import ufl from sumfem.discrete import DomainMaps, MeshData, counterpart, discretize +from sumfem.models import Source from sumfem.post_processing import error, norm from sumfem.solvers import Solver from sumfem.symbolic import ( @@ -468,3 +469,85 @@ def test_discretizations_on_the_same_maps_share_submeshes(toy): assert first.function(s) is not second.function(s) assert first.function(s).function_space.mesh is maps.mesh(gamma) assert second.function(s).function_space.mesh is maps.mesh(gamma) + + +RECTANGLE = (3.0, 2.0, 2.0) +"""The length and the height of the rectangle of :func:`create_split_rectangle`, +and where it is split, off its middle, so that the areas of the region, of +the rest and of the whole, and the length of the interface, differ.""" + + +def create_split_rectangle() -> MeshData: + """Create a rectangle split into an electrode and a channel. + + Returns: + The mesh, see ``RECTANGLE``, with the cell markers ``"Electrode"`` + left of the split and ``"Channel"`` right of it. + """ + length, height, split = RECTANGLE + mesh = dolfinx.mesh.create_rectangle( + MPI.COMM_WORLD, [[0.0, 0.0], [length, height]], [6, 4] + ) + eps = 1e-10 + return MeshData.from_locators( + mesh, + { + 2: { + "Electrode": lambda x: x[0] <= split + eps, + "Channel": lambda x: x[0] >= split - eps, + } + }, + ) + + +def test_an_indicator_is_one_on_its_cells(): + """The area of the region, the area of the union of both markers, and, + with the ghosts on the other side of a process boundary, the length of + the interface.""" + length, height, split = RECTANGLE + domain = Domain("rectangle", "triangle") + electrode = domain.indicator("Electrode") + both = domain.indicator("Electrode", "Channel") + u = Field("u", domain, ("DG", 0)) + models = [Source("electrode", u, electrode), Source("both", u, both)] + disc = discretize(models, DomainMaps({domain: create_split_rectangle()})) + assert disc.assemble_scalar(electrode * domain.dx()) == pytest.approx( + split * height + ) + assert disc.assemble_scalar(both * domain.dx()) == pytest.approx(length * height) + jump = electrode("+") - electrode("-") + assert disc.assemble_scalar(jump**2 * domain.dS()) == pytest.approx(height) + with pytest.raises(TypeError, match="cannot be set"): + disc.set({electrode: 2.0}) + + +def test_a_piecewise_expression_keeps_a_value_that_is_infinite_outside_its_region(): + """A porosity of one in the channel makes ``1 / (1 - porosity)`` infinite + there: the sum written with the indicators multiplies it by zero, not a + number, and the piecewise expression does not take it.""" + length, height, split = RECTANGLE + domain = Domain("rectangle", "triangle") + porosity = domain.piecewise({"Electrode": 0.5, "Channel": 1.0}) + electrode, channel = domain.indicator("Electrode"), domain.indicator("Channel") + values = { + "piecewise": domain.piecewise( + {"Electrode": 1.0 / (1.0 - porosity), "Channel": 3.0} + ), + "sum": electrode / (1.0 - porosity) + channel * 3.0, + } + u = Field("u", domain, ("DG", 0)) + models = [Source(f"source_{name}", u, v) for name, v in values.items()] + disc = discretize(models, DomainMaps({domain: create_split_rectangle()})) + totals = {name: disc.assemble_scalar(v * domain.dx()) for name, v in values.items()} + assert np.isnan(totals["sum"]) + assert totals["piecewise"] == pytest.approx( + 2.0 * split * height + 3.0 * (length - split) * height + ) + + +def test_an_indicator_needs_its_markers_on_the_mesh(square): + domain = Domain("square", "triangle") + u = Field("u", domain, ("DG", 0)) + model = Source("source", u, domain.indicator("Electrode")) + with pytest.raises(KeyError, match="Electrode"): + discretize([model], DomainMaps({domain: square()})) diff --git a/tests/discrete/test_weighted_average.py b/tests/discrete/test_weighted_average.py index abfa1bc..d901b75 100644 --- a/tests/discrete/test_weighted_average.py +++ b/tests/discrete/test_weighted_average.py @@ -2,10 +2,10 @@ The method in plain UFL, ``tests/ufl_files/weighted_average.py``, with a diffusivity ``K`` that jumps between the left and the right half of the unit -square. The plain DG0 diffusivity of the file is replaced by a known -coefficient in DG0, set after discretization by interpolating the -diffusivity of each half. Its interior facet terms take ``K("+")`` and -``K("-")``, the values of the two cells of each facet. +square. The plain DG0 diffusivity of the file is replaced by +:meth:`~sumfem.symbolic.domains.Domain.piecewise` over the cell markers of +the halves. Its interior facet terms take ``K("+")`` and ``K("-")``, the +values of the two cells of each facet. The manufactured solution has a boundary layer at the outflow, scaled by ``K_L / K``: since ``cos(pi x)`` vanishes at ``x = 1/2``, both the solution @@ -25,7 +25,7 @@ from sumfem.discrete import DomainMaps, MeshData, discretize from sumfem.post_processing import error from sumfem.solvers import Solver -from sumfem.symbolic import Domain, KnownCoefficient, UFLResidual +from sumfem.symbolic import Domain, UFLResidual UFL_FILE = pathlib.Path(__file__).parents[1] / "ufl_files" / "weighted_average.py" """The method in plain UFL, with discontinuous elements of degree one.""" @@ -68,7 +68,7 @@ def test_the_weighted_average_problem_converges_across_a_jump(contrast): sides.""" plain = runpy.run_path(str(UFL_FILE)) domain = Domain("square", "triangle") - kappa = KnownCoefficient("kappa", domain, ("DG", 0)) + kappa = domain.piecewise({"LeftHalf": KAPPA_L, "RightHalf": KAPPA_L * contrast}) x = ufl.SpatialCoordinate(domain) beta = ufl.as_vector((0.0, SPEED)) exact = create_exact_solution(x, kappa) @@ -93,17 +93,19 @@ def test_the_weighted_average_problem_converges_across_a_jump(contrast): terminals={plain[name]: value for name, value in values.items()}, ) - halves = ufl.conditional(ufl.lt(x[0], 0.5), KAPPA_L, KAPPA_L * contrast) + halves = { + "LeftHalf": lambda x: x[0] <= 0.5 + 1e-10, + "RightHalf": lambda x: x[0] >= 0.5 - 1e-10, + } errors = [] # Even numbers of cells, so that the line between the halves lies on facets for n in (16, 32, 64): 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}) + marked = MeshData.from_locators(mesh, {2: halves}) + disc = discretize([model], DomainMaps({domain: marked})) (solution,) = Solver(disc[model]).solve() - y = ufl.SpatialCoordinate(mesh) - errors.append(error(solution, create_exact_solution(y, disc[kappa]))) + errors.append(error(solution, disc[exact])) rates = np.log2(np.array(errors[:-1]) / np.array(errors[1:])) assert rates.min() > 2 - 0.15 diff --git a/tests/symbolic/test_terminals.py b/tests/symbolic/test_terminals.py index ee4cb3e..a532fa6 100644 --- a/tests/symbolic/test_terminals.py +++ b/tests/symbolic/test_terminals.py @@ -208,6 +208,37 @@ def test_known_coefficient(domain): assert h.element == as_element(("DG", 0), domain) +def test_an_indicator_is_one_per_set_of_markers(domain): + indicator = domain.indicator("Left", "Right") + assert indicator is domain.indicator("Left", "Right") + assert indicator is not domain.indicator("Left") + assert indicator.markers == ("Left", "Right") + assert indicator.element == as_element(("DG", 0), domain) + assert extract_unique_domain(indicator) is domain + with pytest.raises(ComponentError, match="at least one cell marker"): + domain.indicator() + + +def test_a_piecewise_expression_is_built_from_the_indicators(domain): + """Each region's value goes with its indicator, a tuple of markers is one + region, and the values stay symbolic.""" + k = Parameter("k", domain) + u = Field("u", domain, ("DG", 1)) + K = domain.piecewise({"Left": k, ("Top", "Bottom"): 1 + u**2}) + left, rest = domain.indicator("Left"), domain.indicator("Top", "Bottom") + expected = ufl.conditional( + ufl.eq(left, 1.0), k, ufl.conditional(ufl.eq(rest, 1.0), 1 + u**2, ufl.zero()) + ) + assert K == expected + + +def test_a_piecewise_expression_needs_regions_of_one_shape(domain): + with pytest.raises(ComponentError, match="at least one region"): + domain.piecewise({}) + with pytest.raises(ComponentError, match="differ in shape"): + domain.piecewise({"Left": 1.0, "Right": [1.0, 2.0]}) + + @pytest.mark.parametrize("name", ["", "a b"]) def test_invalid_terminal_names(domain, name): with pytest.raises(ComponentError): From bdd8837a4af84ef2fab6edb791337017e39318b4 Mon Sep 17 00:00:00 2001 From: Jorgen Schartum Dokken Date: Tue, 1 Dec 2026 12:09:53 +0000 Subject: [PATCH 2/2] Split CI --- .github/workflows/docs.yml | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 5d097e3..6e56921 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -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 }} @@ -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