Skip to content

Support string subdomain_id in ufl.Measure, DirichletBC and Submesh - #5199

Open
pbrubeck wants to merge 29 commits into
mainfrom
pbrubeck/feature/region-names
Open

pbrubeck wants to merge 29 commits into
mainfrom
pbrubeck/feature/region-names

Conversation

@pbrubeck

@pbrubeck pbrubeck commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Users can now refer to a subdomain by its name instead of its integer subdomain id. The names come from the mesh file, or from the cell_subdomain_names and facet_subdomain_names arguments of Mesh and of every utility mesh.

from firedrake import *
import netgen.occ as ngocc

# 1. Generate geometry & name boundaries natively in Netgen
wp = ngocc.WorkPlane()
box = wp.Rectangle(1, 1).Face()
box.edges.Max(ngocc.Y).name = "inlet"
box.faces.name = "fluid_domain"
ngmesh = ngocc.OCCGeometry(box, dim=2).GenerateMesh(maxh=0.1)

# 2. Native Firedrake Mesh captures the names automatically
mesh = Mesh(ngmesh)

# 3. Explicitly map a single string name to multiple disjoint entity IDs

# 4. Clean, human-readable API usage
V = FunctionSpace(mesh, "CG", 1)

# DirichletBC automatically maps "inlet" to the correct face ID
bc = DirichletBC(V, 0.0, "inlet")  

# SubMesh automatically maps "fluid_domain" using the correct keyword argument
submesh = Submesh(mesh, subdomain_id="fluid_domain")

# Form language integration: UFL Measures accept string region names directly
f = Function(V)
L = f * dx(subdomain_id="fluid_domain")

The mesh readers put each name on the DMPlex as a label, and Firedrake stores the names on the mesh topology. Firedrake changes names into subdomain ids where each API reads them:

Mesh(meshfile)
  read the DMPlex
    Gmsh, Netgen    one label for each name (PETSc use_regions, ngsPETSc)
    Exodus          one label for each side set name
    CGNS            one label for each facet group (-dm_plex_cgns_parallel)
  topology.subdomain_names[dim][name] = [subdomain ids]

Mesh(..., cell_subdomain_names={name: ids},       # add names by hand, ids is an int
          facet_subdomain_names={name: ids})      # or a sequence of ints
UnitSquareMesh(..., facet_subdomain_names=...)   # utility meshes pass them to Mesh

mesh.parse_subdomain_id(dim, subdomain_id)        # change names into subdomain ids
  called by DirichletBC(V, g, "inlet")
            RestrictedFunctionSpace(V, boundary_set=["inlet"])
            Submesh(mesh, subdomain_id="fluid_domain")
            compile_form, for ds("inlet") and dx("fluid_domain")
  • on_boundary, everywhere, otherwise, top and bottom keep their meaning.
  • A name that is not on the mesh raises a ValueError that lists the available names.
  • A name can map to several subdomain ids. In a nested tuple, which is an intersection of subdomain ids, the name stays one entry.
  • compile_form changes names into subdomain ids before the cache lookup. So the cache key holds the subdomain ids that the names map to when the form is compiled.
  • The Netgen and Boussinesq demos now use names instead of GetRegionNames.

Implementation details

  • Gmsh files are now read with -dm_plex_gmsh_use_regions -dm_plex_gmsh_use_generic. The generic labels (Cell Sets, Face Sets and so on) supply the subdomain ids as before. The name labels are removed before distribution.
  • The CGNS parallel reader gives the subdomain ids of facet groups. Firedrake gives each named group an unused positive subdomain id, in alphabetical order.
  • Netgen names come from the labels that Add a label for each named Netgen region to the DMPlex NGSolve/ngsPETSc#134 adds. The same PR adds a Cell Sets label when all cells are in one named region. Without it, dx("fluid_domain") in the code block above resolves to dx(1) and integrates over nothing.

Limitations

  • CheckpointFile does not keep the names, because they are not on the DMPlex after distribution.
  • Netgen vertex names are not imported, because ngsPETSc puts no labels on vertices.
  • A Gmsh element in several physical groups is only in the subdomain id of its first group. So the name of a later group does not include that element.

Evidence

The tests compare assembled values or subdomain ids with values computed in a different way:

  • Before: each test fails, because the API does not accept a string or the mesh has no names.
    After: each test passes.
    • test_dirichletbc_facet_subdomain_names
    • test_restricted_function_space_accepts_subdomain_name
    • test_submesh_accepts_subdomain_name
    • test_measure_accepts_subdomain_name_with_domain, ..._with_inferred_domain
    • test_cell_subdomain_names_name_cell_subdomain_ids, test_facet_subdomain_names_name_facet_subdomain_ids
    • test_gmsh_subdomain_names_are_loaded, test_cgns_subdomain_names, test_netgen_subdomain_names_are_loaded, test_exodus_mesh

test_netgen_subdomain_names_are_loaded fails with ngsPETSc main and passes with the ngsPETSc branch.

Merge Danger

Door: two-way

Integer subdomain ids work as before. Names are new API. They can stay, or they can be removed later.

Blast Radius: mesh-loading

  • Gmsh: the generic labels, and so the integer subdomain ids, do not change. PETSc inserts only the first tag of an element in them.
  • Gmsh: a physical name that is also the name of a PETSc label (depth, celltype, marker, Cell Sets, ...) is not imported.
  • The commit DROP BEFORE MERGE: Install the ngsPETSc branch with region labels installs the ngsPETSc branch in CI. Drop it after Add a label for each named Netgen region to the DMPlex NGSolve/ngsPETSc#134 merges, and run CI again.

Disclaimer: This PR was implemented with Codex and Claude Code (Claude Opus 5.5).

🤖 Generated with Claude Code

pbrubeck and others added 4 commits November 26, 2026 23:31
…on-names

# Conflicts:
#	demos/netgen/netgen_mesh.py.rst
#	firedrake/bcs.py
#	firedrake/mesh.py
#	firedrake/tsfc_interface.py
FEniCS/ufl#493 has been merged, so CI's UFL main already supports
string subdomain ids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Resolve region names once in compile_form, before the cached
  _compile_form, instead of in both the hashkey and the body.
- Use UFL's integral type tables to find the entity dimension.
- Share one entity dimension check between rename_subdomain and
  parse_subdomain_id, and flatten the parse_subdomain_id helpers.
- Read Gmsh physical names on rank 0 only, stop at $Entities/$Nodes
  when there is no $PhysicalNames block, and gather names on the
  internal communicator.
- Declare region_names on ExtrudedMeshTopology, which does not call
  AbstractMeshTopology.__init__.
- Remove a leftover print(labels) from the Netgen demo.
- Move the tests from test_region_names.py (deleted in the previous
  commit) into the existing test files for each feature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbrubeck pbrubeck added the LLM used An LLM was used in the production of this PR label Nov 27, 2026
Share one helper between the Gmsh and Exodus readers, give every rank
the full CGNS name list, store region names in a plain dict, and read
Netgen names next to the other readers. Wrap a string subdomain before
the names are resolved in DirichletBC and RestrictedFunctionSpace, so
that a name given to an already restricted space is also resolved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbrubeck
pbrubeck marked this pull request as ready for review November 27, 2026 01:52
Comment thread firedrake/tsfc_interface.py Resolved
pbrubeck and others added 11 commits November 27, 2026 17:22
Use the terms of the rest of the codebase: subdomain names and
subdomain ids, not region names, tags or markers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ngsPETSc now marks each named Netgen region in a DMPlex label with that
name, like the PETSc Gmsh reader does. Read these labels in the same way
for Gmsh and Netgen meshes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Drop this commit once NGSolve/ngsPETSc#134 merges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Convert point coordinates to a tuple before passing them to DirichletBC, and demonstrate vector-valued Constants in both demos.

Assisted-by: OpenAI Codex
Assisted-by: OpenAI Codex
Assisted-by: OpenAI Codex
Assisted-by: OpenAI Codex
@pbrubeck
pbrubeck requested a review from connorjward November 30, 2026 14:15
Comment thread firedrake/mesh.py
@PETSc.Log.EventDecorator()
def _from_gmsh(filename: str, comm: MPI.Comm, geometric_dim: int | None) -> tuple[PETSc.DMPlex, list[tuple[int, int, str]]]:
"""Read the mesh and physical names from a Gmsh file."""
options = {"dm_plex_gmsh_use_regions": True, "dm_plex_gmsh_use_generic": True}

@pbrubeck pbrubeck Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@connorjward It turns out that PETSc is able to load the string subdomain ids from gmsh as individual, single-valued DMLabels, so I opened NGSolve/ngsPETSc#134 to deal with string subdomain_id uniformly in netgen.

The approach in this PR is to pop all such single-valued labels and keep the usual multivalued "Facet Sets" label. subdomain_id consumers call mesh.parse_subdomain_ids() to turn user inputs into the standard tuple[int] format

@connorjward connorjward left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Questions about the API. This is nearly very nice.

'''
def __init__(self, V, g, bc_point):
super().__init__(V, g, bc_point)
super().__init__(V, g, tuple(bc_point))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems like this might break user's code in a very subtle way. The DirichletBC constructor is definitely public API since we have demos encouraging users to subclass it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can go away if as_tuple treated ufl.Expr as a sequence

Comment thread firedrake/mesh.py Outdated
raise ValueError(f"Invalid entity dimension {dim} for mesh of dimension {mesh_dim}")
return dim

def rename_subdomain(self, dim, subdomain_id, subdomain_name):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"rename" indicates that the previous label is now invalid, which I don't think is the case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about tag_subdomain?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could do. Pretty sure "label" is the predominant terminology for this sort of thing though.

This seems like it could basically be achieved with RelabeledMesh.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm reading your last message as "don't use re- in the name because it might confuse users and they might associate this with RelabeledMesh, which creates a new Mesh"

assert e.ierr == 56
def exodus_mesh() -> MeshGeometry:
if "exodusii" not in get_external_packages():
pytest.skip("PETSc was built without ExodusII support")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be @pytest.mark.skipexodusii in conftest.py. Otherwise we won't test this if CI stops install exodusii (which it must do already?)

If we aren't testing exodusii then we really should be.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mesh.rename_subdomain(1, [1, 2], "vertical")
V = FunctionSpace(mesh, "CG", 1)

assert RestrictedFunctionSpace(V, "vertical").boundary_set == frozenset({1, 2})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems strange to me that the strings just refer to the integer IDs. I would have expected that Vr.boundary_set == "vertical".

A much nicer API would be the ability to label an arbitrary portion of the domain with a new string label, rather than only be able to rename the union of existing integer labels.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can take baby steps towards that goal

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR is just adding a layer on top of the int labels. If we want to, we can change the internals as a separate refactor

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR just seems like, whilst it is moving in the right direction, it is also moving sideways and adding things that will have to be fixed later on. You are adding infrastructure that you later intend to remove.

The string stuff for netgen is really good. I wonder if that could land without touching the existing integer subdomain ID stuff. This is quite a complex PR as it stands.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The existing subdomain id mechanism isn't really touched. What we have for netgen is exactly the same code path as gmsh.

Could you propose the redesign that you want?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe my suggestion is that rename_subdomain be made an internal API (as well as being renamed). I don't think it's at all natural for a user, but it does make sense when interfacing with gmsh.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There was some discussion about this API at a meeting a while ago. The conclusion was that we also wanted to let the user be able to attach their own string IDs to any given mesh.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The conclusion was that we also wanted to let the user be able to attach their own string IDs to any given mesh.

Absolutely. But us giving them an API where they have to have first labelled the IDs with (possibly multiple) integers, and only then can they assign a string, is bizarre IMO.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's not the intention. If they define their own mesh file, they can label it with string IDs. If they are using a utiility mesh, we let them override the integer IDs with their own strings.

Comment thread tests/firedrake/regression/test_bcs.py Outdated

def test_dirichletbc_accepts_subdomain_name():
mesh = UnitSquareMesh(2, 2)
mesh.rename_subdomain(1, [1, 2], "vertical")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we have something about this in the BC part of the manual?

pbrubeck and others added 3 commits November 30, 2026 22:54
Document which mesh formats load subdomain names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CI built PETSc without ExodusII, so the fixture in test_exodus_mesh.py
skipped every ExodusII test. Download ExodusII and CGNS in the install
action and mark the tests with skipexodusii, which never skips on CI.
Treat every dependency that conftest.py does not import as an external
package of PETSc, so that a new PETSc package needs only a new marker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No test read a Triangle or a CGNS mesh file. Check the volume and the
boundary ids of a Triangle mesh of the unit square, and the volume of
a unit square that PETSc writes to a CGNS file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbrubeck
pbrubeck changed the base branch from main to pbrubeck/test/mesh-formats November 30, 2026 23:12
… pbrubeck/feature/region-names

# Conflicts:
#	tests/firedrake/regression/test_exodus_mesh.py
@pbrubeck
pbrubeck added this pull request to stack #5752 November 30, 2026 23:15
@pbrubeck
pbrubeck removed this pull request from stack #5752 December 1, 2026 09:22
@pbrubeck
pbrubeck force-pushed the pbrubeck/test/mesh-formats branch from 1fa82c0 to acecfef Compare December 1, 2026 09:26
@pbrubeck
pbrubeck changed the base branch from pbrubeck/test/mesh-formats to main December 1, 2026 09:34
pbrubeck and others added 3 commits December 1, 2026 15:49
Mesh(coordinates, tolerance=...) returned before it read the tolerance,
so the new mesh always had the default tolerance of 0.5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each utility mesh passes the keyword arguments that it does not use to
Mesh, so that all Mesh options, for example the tolerance, can be set
on a utility mesh. The annulus and solid torus meshes now call Mesh
instead of make_mesh_from_coordinates, so that they also receive them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace the public MeshGeometry.name_subdomain with the keyword
arguments cell_subdomain_names and facet_subdomain_names of Mesh and of
the utility meshes. Each argument maps a name to one subdomain id or a
sequence of them:

    mesh = UnitSquareMesh(2, 2, facet_subdomain_names={"vertical": [1, 2]})
    bc = DirichletBC(V, 0, "vertical")

Mesh stores these names together with the names that it loads from the
mesh file. If a name occurs in both, it refers to the ids from both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

LLM used An LLM was used in the production of this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants