Skip to content

Update Multipatch API - #188

Open
FrederikSchnack wants to merge 62 commits into
masterfrom
new_multipatch_api
Open

FrederikSchnack wants to merge 62 commits into
masterfrom
new_multipatch_api

Conversation

@FrederikSchnack

@FrederikSchnack FrederikSchnack commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Generalize symbolic multipatch topology

Summary

This PR removes the assumption that connected faces have the same normal axis and
properly defines orientations for 1D, 2D, and 3D interfaces in SymPDE's multipatch topology,
so that SymPDE can describe 2D and 3D multipatch domains in arbitrary configurations.

It also:

  • supports repeated interfaces between two patches, periodic and self-interfaces;
  • validates the connectivity given to Domain.join();
  • gives every interface a stable name, preserved through mapping and serialization;
  • describes the topology with plain Python data for discretization codes such as
    PSYDAC: the interfaces and boundary sides with patch indices, and the vertices
    and (in 3D) edges of the domain with all their patch incidences;
  • gives every domain a logical and a physical dimension, ldim and pdim, which
    replace dim, so that a surface in 3D has the coordinates [x, y, z] (Domain should know its physical dimension #203);
  • gives discretization codes the full logical transform of every interface
    (normal axes, point and vector-component maps), the orientability of the
    domain, and lookups from patch-local corners, edges and sides to the global
    vertices, edges and interfaces, which 3D multipatch in PSYDAC needs;
  • fixes the plus-side terms of interface integrals (see "Bug fixes");
  • introduces reusable topology plotting and multipatch gallery modules, that were
    exclusively in PSYDAC before. (See Move the multipatch domain gallery to psydac.mapping, and the generic mapping helpers to SymPDE psydac#643)
  • drop python 3.10

Fixes #73, fixes #114, fixes #140, fixes #143, fixes #144, fixes #203.

How to review

The diff is large, but more
than half of it is tests, documentation, the gallery moved from PSYDAC and the
plotting module. Suggested order:

  1. Contract. Read doc/multipatch.rst, the new user-guide page. It states
    what the topology means (sides, orientation, naming, vertices and edges,
    interface transform, orientability) and is what the code and tests check.

  2. Core topology, the part to review closely:

    • sympde/topology/basic.py: Boundary, Interface, the decoding of the
      compact orientation into axis_map, and InterfaceTransform;
    • sympde/topology/domain.py: Domain.join() (validation, naming, ordering),
      serialization, the inspection API and the lookups;
    • sympde/topology/incidence.py: the index-based data classes, the
      union-find that glues vertices and edges, and the orientation of patches.

    Tests: sympde/topology/tests/test_topology.py and test_incidence.py.

  3. Expressions: sympde/topology/mapping.py (interface measures, physical
    coordinates from pdim) and sympde/expr/evaluation.py (splitting interface
    terms into minus and plus parts). Tests: sympde/expr/tests/test_expr.py and
    sympde/topology/tests/test_logical_expr.py.

  4. Dimensions (Domain should know its physical dimension #203): the rename dim → ldim and the new pdim
    (7610473, 92021ef) are mostly mechanical.

  5. Gallery and plotting: sympde/topology/multipatch_gallery.py and
    sympde/utilities/plotting.py are independent of the core. The gallery tests
    check every mapping against the declared topology; skimming the rest is enough.

  6. Housekeeping: Sphinx setup, CHANGELOG, static-analysis fixes, Python 3.9.

Topology of a multipatch domain

A multipatch domain is made of patches, each of which is the image of a
parametric box (a Line, Square or Cube) under an optional mapping.
Patches are glued along their faces, i.e. the sides of their boxes:

Parts of the patches 2D 3D How they are glued
codimension 1 (faces) sides faces in pairs, by one interface each
codimension 2 vertices edges transitively, through chains of interfaces
codimension 3 vertices transitively, through chains of interfaces

Interfaces

An interface glues one face of a patch (its minus side) to one face of a
patch (its plus side), possibly the same patch. Each side is a Boundary
(patch, axis, ext): the patch, the logical axis normal to the face, and the
extremity (-1 for the lower face, +1 for the upper face). The orientation
tells how the tangential coordinates of the two faces correspond (see "Interface
orientation"). A face is either part of exactly one interface or a boundary side
of the domain; Domain.join() rejects a face joined with itself or used in two
interfaces.

Domain.join() creates the interfaces from the given connectivity, and derives
the exterior boundary as all patch faces that are not part of an interface. The
interfaces are stored as symbolic Interface objects:

  • in the args of the domain, sorted by name, so that two domains with the
    same interfaces are equal whatever the order of the connectivity, and a
    domain equals itself after export()/from_file();
  • in domain.interface_map, a mapping from the interface name to the
    interface.

The symbolic objects are what the forms use: integrals over interfaces, jump,
avg, and the mapping of an interface, InterfaceMapping. Every interface has
a unique name, given explicitly or generated as A|B, A|B#2, ... from the
logical patch names. The names are numbered in the order of the faces, so that
they do not depend on the order of the connectivity, and a mapped interface and
its logical interface have the same name, also after reading a file.

Index-based topology for discretization codes

Discretization codes work with patch indices rather than with SymPy objects,
and need to know which degrees of freedom of different patches belong to the
same face, edge or vertex. The new module sympde.topology.incidence describes
the topology of a domain with plain, frozen data classes, in which a patch is
given by its position in domain.patches:

Property Content
domain.indexed_interfaces read-only mapping from interface name to IndexedInterface(name, minus, plus, orientation, axis_map), where each side is a PatchSide(patch_index, axis, ext)
domain.indexed_boundary_sides tuple of PatchSide for the faces that are not part of an interface
domain.vertices tuple of TopologyVertex: all vertices of the domain, each with the patch corners identified with it, and whether it lies on the exterior boundary
domain.edges in 3D, tuple of TopologyEdge: all edges of the domain, each with the patch edges identified with it, their directions, and whether it lies on the exterior boundary
domain.patch_index(patch) position of a patch, given by its interior, a single-patch domain or one of its boundaries

The faces are fully described by the interfaces and the boundary sides. The
vertices (in 2D and 3D) and the edges (in 3D) are needed in addition, because
any number of patches can meet at them, and they are only identified through
chains of interfaces: three patches around one vertex in 2D, or around one edge
in 3D. A conforming discretization has to give their degrees of freedom a single
value, which is what PSYDAC's conforming projections do. is_boundary tells
which of them carry boundary conditions, and the direction (±1) of each edge
incidence gives the sign of the tangential components shared along the edge, as
needed for H(curl). In 2D, the edges of the patches are their sides, so that
domain.edges is only defined in 3D and points to the interfaces otherwise.

A patch-local vertex is a tuple of 0 (lower end) and 1 (upper end) for every
axis, and a patch-local edge has None for the axis along the edge. The
vertices and edges are computed by one union-find over the corners and edges of
all patches, identified through the axis_map of every interface, and checked
in the tests to coincide geometrically for all 3D gallery domains.

Interface transform

axis_map only relates the tangential axes. Interface and IndexedInterface
also give the full transform between the logical coordinates of the two
patches, through the mixin InterfaceTransform:

Member Content
normal_direction -minus.ext * plus.ext
signed_permutation, inverse_signed_permutation (plus_axis, direction) for every minus axis, normal included, and the reverse
permutation_matrix, handedness the signed permutation matrix and its determinant
map_point(eta, minus_bounds, plus_bounds, *, inverse=False) logical coordinates of the minus patch mapped to the plus patch, or back
map_component(k, kind, minus_bounds, plus_bounds, *, inverse=False) (j, factor) with u_minus[k] = factor * u_plus[j], for the tangential H(curl) and the normal H(div) components

map_component only relates the components that a conforming field keeps
continuous, and raises a ValueError for the others: only the tangential
columns of the Jacobians of the two mappings match on an interface, so the
other relations, and those of L² densities, only hold if the geometry is C¹
across it. The H(div) factor follows PullBack, with the signed Jacobian
determinant. The bounds of the logical coordinates default to (0, 1) and must
be given for patches with other bounds. Both maps are tested on every face pair
and orientation (map_point in 1D, 2D and 3D, map_component in 2D and 3D),
and map_component also against the pull-backs of smooth fields on the gallery
domains.

Orientability

domain.patch_handedness gives one sign per patch such that
s[plus] == s[minus] * interface.handedness for every interface, with +1 for
the first patch of every connected component, or None if the domain is not
orientable; domain.is_orientable tells whether these signs exist. If the
mappings have ldim == pdim and match on the interfaces, the signs of their
Jacobian determinants follow these signs, which the tests check on the gallery,
including left-handed and mixed-handedness patches. Non-orientable domains, such
as a Möbius strip or the twisted strip of the gallery, remain valid topologies;
discretizations of oriented quantities such as H(div) fields should check
is_orientable.

Reverse lookups

domain.vertex_of(patch_index, corner), domain.edge_of(patch_index, logical_edge) (3D, also returns the direction of the patch edge) and
domain.side_of(patch_index, axis, ext) (the IndexedInterface or the boundary
PatchSide) go from patch-local entities to global ones. A vertex or an edge
may contain the same patch more than once if a patch is glued to itself, so
incidences are keyed by (patch_index, logical_corner) or
(patch_index, logical_edge). side_of does not tell which side of the
interface the given side is: interface.plus == PatchSide(patch_index, axis, ext) decides whether to pass inverse=True to map_point and map_component.

Interface orientation

Domain.join() accepts each interface as:

(minus_side, plus_side, orientation)
(minus_side, plus_side, orientation, name)

Each side is (patch, axis, extremity), where axis is the logical axis normal to the face, patch is a patch object
or its position in the patches sequence and extremity is -1 or +1.
interfaces= is an alias for connectivity=; passing both is an error.

For example, two cube faces with different normal axes can be joined as:

from sympde.api import Cube, Domain

A = Cube('A')
B = Cube('B')

domain = Domain.join(
    patches=[A, B],
    interfaces=[(
        (A, 0, +1),
        (B, 1, -1),
        (-1, +1, -1),
    )],
    name='Omega',
)

Orientation is read from the ordered minus side to the ordered plus side:

Patch dimension Orientation Meaning
1D None An endpoint has no tangential coordinate
2D +1 or -1 Preserve or reverse the edge coordinate
3D (flag, sign1, sign2) Preserve/exchange the two face axes and orient each correspondence

All 3D entries are +1 or -1. flag=+1 preserves the order of the two
tangential axes; flag=-1 exchanges them.

Interface.axis_map exposes the decoded, dimension-independent
correspondence as (minus_axis, plus_axis, direction) entries. For the
example above:

interface = domain.interface_map['A|B']

assert interface.orientation == (-1, +1, -1)
assert interface.axis_map == ((1, 2, +1), (2, 0, -1))
assert domain.indexed_interfaces['A|B'].axis_map == interface.axis_map

The face-normal correspondence remains available from
interface.minus.axis and interface.plus.axis; it is not repeated in
axis_map. This is the orientation format currently and later used in PSYDAC.

Supported topology

The joined-domain implementation now supports:

  • interfaces between faces with different normal axes;
  • all two edge orientations and all eight quadrilateral-face orientations;
  • more than one interface between the same pair of patches;
  • periodic and self-interfaces (see also Add periodicity information to logical domain #120);
  • explicit interface names, preserved during serialization;
  • induced subdomains that retain internal interfaces and expose cut
    interfaces as exterior boundaries; and
  • transitive vertex classes in 2D and 3D, and edge classes in 3D.

Domain.join() rejects patches with different logical or physical dimensions
(#140), patches of which only some have a mapping, interfaces that join a face
with itself, and faces that are part of more than one interface. An empty
one-patch join still returns the original patch. A one-patch join with declared
connectivity follows the normal join path, allowing a genuine self-interface.
Passing an already joined multipatch domain as one atomic patch is rejected
explicitly.

Mapped domains preserve the logical interface, compact orientation,
InterfaceMapping, and patch mappings. Interface stores mapping and
logical_domain in its args, so that it can be reconstructed with
interface.func(*interface.args). Interface integrals use the minus side as
their canonical parameterization instead of assuming one shared normal axis.
Terms that only involve the plus side are moved to the plus face, with its own
normal axis, surface measure and outward normal.

Inspection API

Symbolic views with a stable cardinality:

  • domain.patches: tuple of top-dimensional patches;
  • domain.interface_map: interface-name-to-Interface mapping, ordered by name;
  • domain.boundary_sides: tuple of the faces that make up domain.boundary;
  • Boundary.domain and Boundary.axis: the patch of a side and its normal axis;
  • Interface.axis_map: decoded orientation.

Dimensions (#203): every domain has a logical dimension ldim and a physical
dimension pdim, the physical dimension of its mapping, or ldim without a
mapping. All patches of a domain have the same pdim, which the Domain
constructor and Domain.join() check. For a boundary or an interface, ldim
and pdim are those of its patches, and intrinsic_dim (ldim - 1) is the
dimension of the side itself. The physical coordinates of a mapped domain are
built from pdim, and LogicalExpr and TerminalExpr map all of them; vector
function spaces keep ldim components.

Index-based data for discretization codes: domain.indexed_interfaces,
domain.indexed_boundary_sides, domain.vertices, domain.edges,
domain.patch_index(), the interface transform, domain.is_orientable,
domain.patch_handedness, domain.vertex_of(), domain.edge_of() and
domain.side_of(), see "Index-based topology for discretization codes".

The established domain.interior, domain.boundary and domain.interfaces
properties remain available.

Serialization

Serialized interfaces now always contain the minus side, plus side, and
compact orientation. Interface dictionary keys are restored as interface
names instead of being regenerated.

Exterior boundaries use one list representation, including an empty list for
fully closed domains. The reader still accepts the historical single-boundary
dictionary and can derive missing boundary metadata from connectivity.
Stored exterior boundaries are checked against the derived topology.

Domains whose patches are InteriorDomain objects without a dtype (#144)
have no parametric box from which the boundary could be derived. Their
exterior boundaries and interfaces are restored as they were stored,
including boundaries without an axis or extremity. Such patches are only
supported without a mapping.

Files whose interfaces omit orientation are rejected because orientation
cannot be inferred reliably from axes or extremities. Such files must be
regenerated or migrated with an explicitly confirmed orientation for every
interface.

Topology inspection and plotting

The new module sympde.utilities.plotting provides plot_domain(),
format_topology() and print_topology(). plot_domain() and
print_topology() are also available in sympde.api. The old plotting
functions in sympde.utilities.utils are removed.

plot_domain() handles ordinary and topology-annotated 2D and 3D plots and
returns its Matplotlib figure. In topology mode, each side of an interface is
drawn inside its own patch, the minus side solid and the plus side dashed, with
arrows along the tangential coordinate of the minus side and its image on the
plus side, so that a reversing interface (such as the twisted strip) shows
opposite arrows. Vertices are marked white on the boundary and black in the
interior, patches are coloured with a colour-blind safe palette, and a legend
explains the styles. print_topology() gives the same topology as text,
including the axis map of every interface. Matplotlib is only imported when a
domain is plotted, so importing sympde.utilities.plotting or sympde.api
does not load it.

Multipatch gallery

This formerly was in psydac/feec/multipatch_domain_utilities.py.

sympde.topology.multipatch_gallery provides explicit symbolic builders for
2D domains (squares, annuli, L-shape, pretzels, twisted strip, ...) and 3D
domains (two cubes, oriented cubes, three patches around one edge, hollow or
solid torus), and includes an integrated plotting function.

The gallery can be plotted from Python with plot_multipatch_domain() or run
as a module:

python -m sympde.topology.multipatch_gallery two_cube \
    --topology --no-show --output two_cube.png

TransposedPolarMapping, TransposedTargetMapping and TransposedCzarnyMapping,
whose angle and radius coordinates are swapped, are now part of SymPDE's
analytical mappings because they are reusable coordinate transformations rather
than discretization details. All analytical mappings, including TorusMapping
and TwistedTargetMapping, are available in sympde.api.

The twisted strip is a topological example only: it is a Möbius strip, which is
not orientable, and its mappings do not match on its second interface.

Bug fixes

  • Plus-side interface terms. A term that only involves the plus side, e.g.
    plus(u)*plus(v) or plus(v)*f, is moved to the plus face. On interfaces
    between faces with different normal axes, which this PR introduces, it kept the
    surface measure of the minus face. In linear forms, it also kept the normal
    vector of the interface instead of the outward normal of the plus face, and
    evaluated the measure in the coordinates of the mixed terms. These two bugs of
    linear forms are already on master, so the results of such linear forms
    change.
  • Domain.get_interface() always failed; it now returns the interfaces that
    join two patches.
  • split() split a Line domain with wrong bounds and an invalid interface.
  • Domain.from_file() raises a ValueError, instead of a KeyError, when an
    interface references an unknown patch, and restores the interface names and
    exterior boundaries as they were stored (Inconsistent from_file when reading a topological domain from a file, that has been exported #144).

Breaking changes

Previous API or data Replacement
Boundary.join(other, ornt=...) Boundary.join(other, orientation)
Interface(..., ornt=...) Interface(..., orientation)
interface.ornt interface.orientation
interface.axis interface.minus.axis and interface.plus.axis
Edge Boundary
interface connectivity dictionaries (minus, plus, orientation[, name]) tuples
serialized interface without orientation explicit compact orientation
domain.corners, domain.get_shared_corners(), CornerBoundary, CornerInterface domain.vertices
generated names of interfaces between mapped patches, e.g. F(A)|G(B) names built from the logical patches, e.g. A|B
interfaces ordered as given in the connectivity, and numbered A|B, A|B#2 in that order interfaces ordered by name, and numbered in the order of their faces
Domain(..., connectivity=[...]) silently keeping one of several interfaces with the same name ValueError
Domain.join() accepting patches of different physical dimensions, mapped and unmapped patches together, a face joined with itself or a face in two interfaces ValueError
plot_2d(), plot_3d(), plot_2d_single_patch(), plot_3d_single_patch() plot_domain()
sympde.utilities.utils.plot_domain sympde.api.plot_domain
domain.dim on all domain classes, including boundary.dim and interface.dim domain.ldim (and domain.pdim)
Domain(name, dim=...), InteriorDomain(name, dim=...), NCube(name, dim, ...) ldim=...; Mapping(name, dim=...) is unchanged
dim in the dtype parameters of a generic NCube stored in a file ldim
physical coordinates of a mapped domain with pdim > ldim, e.g. [x, y] for a surface in 3D [x, y, z], also in LogicalExpr and TerminalExpr
Domain(...) accepting interiors of different physical dimensions ValueError
domain.subdomains domain.patches
domain.connectivity (the property; the connectivity argument of Domain and Domain.join() is unchanged) domain.interface_map
Domain.set_interfaces(), item assignment of Connectivity, Connectivity.patches none: the interfaces of a domain are read-only
Domain.get_boundary(axis, ext) returning one of several matching sides of a multipatch domain ValueError; pass patch=
plus-side terms of interface linear forms (wrong normal sign and measure coordinates) corrected results, see "Bug fixes"
Python 3.9 Python 3.10 or newer

No default orientation is introduced. Callers must state the intended
topology explicitly.

Consequences for downstream projects

I searched the default branches of the three projects that depend on SymPDE
for the APIs changed here.

PSYDAC (devel) uses the API replaced here, and can use the new index-based
data instead of computing it:

  • About 65 uses of .dim on domains, and one Domain(..., dim=...), become
    .ldim and ldim=... (Domain should know its physical dimension #203).

  • .ornt (8 uses in cad/geometry.py, api/fem.py, api/fem_bilinear_form.py,
    feec/conforming_projectors.py and cad/tests/test_geometry.py) becomes
    .orientation; the matching of the tangential axes and their flips are given
    by axis_map.

  • interface.axis (api/fem.py, api/fem_bilinear_form.py,
    feec/conforming_projectors.py) becomes interface.minus.axis and
    interface.plus.axis.

  • get_corners() (feec/conforming_projectors.py) reads domain.corners, which
    is removed: it can be replaced by domain.vertices, and its boundary_only
    filter by vertex.is_boundary; the 3D conforming projections can use
    domain.edges.

  • from sympde.utilities.utils import plot_domain (fem/tests/test_dirichlet_projectors.py
    and five notebooks in examples/notebooks/) becomes
    from sympde.api import plot_domain.

  • Omega.subdomains (examples/notebooks/fem_L2_projection.ipynb) becomes
    Omega.patches.

  • Not breaking, but needed for repeated interfaces (Allow connecting two patches with multiple interfaces #114):
    construct_connectivity() (fem/partitioning.py) keys the interfaces by
    patch pair (i, j), which loses repeated interfaces. It can be replaced by
    domain.indexed_interfaces, keyed by interface name, together with the
    (i, j) keys of linalg/block.py.

  • get_patch_index_from_face() and the domains.index(...) calls can be
    replaced by domain.patch_index(), and
    psydac/feec/multipatch_domain_utilities.py can be removed in favour of the
    gallery.

  • Where PSYDAC builds the full transform between the logical coordinates of
    the two sides of an interface itself (quadrature points, interface matrices,
    MPI decomposition), it can use signed_permutation, map_point and
    map_component. Note that map_component assumes the signed Jacobian
    determinant of PullBack, whereas feec/pull_push.py and
    feec/pushforward.py use its absolute value.

  • The 3D conforming projections can use domain.vertex_of(), edge_of() and
    side_of(), and should reject non-orientable domains with
    domain.is_orientable.

  • Interface linear forms with plus-side terms give different (corrected)
    results, see "Bug fixes".

The Domain.join() calls of PSYDAC already pass interface tuples with an
orientation, and PSYDAC already requires Python 3.10 or newer.

IGA-Python:

  • 10 calls with dim= on domains and 2 uses of .dim (chapter1/topology.md)
    become ldim (Domain should know its physical dimension #203).
  • chapter4/poisson-two-subdomains-nitsche.ipynb joins two patches with
    connectivity = [((0,0,1),(1,0,-1))], without an orientation. This already
    fails with SymPDE 0.20.0, and needs an explicit orientation, e.g.
    [((0,0,1),(1,0,-1),1)].

GeLaTo: 31 calls Domain('Omega', dim=DIM) in its tests become
Domain('Omega', ldim=DIM) (#203).

Current limitations

  • SymPDE validates topology but does not numerically prove that mapped faces
    coincide or satisfy the declared parameterization.
  • In the solid torus of the gallery, the faces collapsed onto the centreline
    remain boundary sides and must be excluded when imposing boundary
    conditions.
  • Compact orientations are defined for logical dimensions 1, 2, and 3.
  • Vector function spaces keep ldim components on domains with pdim > ldim;
    whether vector fields on a surface should have pdim components is a
    separate modelling question.
  • Interfaces join whole faces, with matching parametrizations: T-junctions and
    partial faces cannot be described.
  • Non-orientable domains are accepted; domain.is_orientable must be checked
    where orientation matters.
  • Not changed here, and the same on master: avg() is never evaluated, and
    jump()/avg() fail or are wrong on compound expressions (avg() is never evaluated, and jump()/avg() fail or are wrong on compound expressions #208); write
    plus()/minus() out instead. Functional and Norm turn interface and
    boundary integrals into volume integrals (Functional silently turns interface and boundary integrals into volume integrals #207).

Some plots

1_three_patch_interior_vertex 2_two_patch_twisted_strip 3_hollow_torus 4_three_patch_interior_edge

Represent interface orientation explicitly and expose a signed tangential axis map that supports cross-axis 3D faces.

Support repeated and self interfaces, stable multipatch views, induced subdomains, dimension-independent shared vertices, mapped interface metadata, collision-safe names, and robust topology serialization. Tighten public validation and cover the new contract with logical, mapped, subset, periodic, and round-trip tests.
Move domain plotting into a dedicated lazy-loaded module and provide shared 2D/3D rendering with optional interface, axis-map, and vertex annotations.

Add textual topology inspection, reusable 2D/3D gallery domain builders, an executable gallery CLI, and integration tests without making Matplotlib an import-time dependency of sympde.
Use MathJax for rendered mathematics, configure the existing FEEC bibliography explicitly, and remove obsolete imgmath and LaTeX configuration.

Also normalize the TerminalExpr parameter documentation so strict autodoc builds remain warning-free.
Add a user guide for constructing, inspecting, validating, plotting, subsetting, and serializing logical and mapped multipatch domains in 1D, 2D, and 3D.

Document the downstream axis-map contract, intentional API and file-format migrations, Edge removal, current limitations, and validation responsibilities.
Comment thread sympde/topology/domain.py Resolved
@yguclu yguclu mentioned this pull request Oct 20, 2026
Adapt the multipatch changes to the conventions introduced by #193 and #194:

- Import objects from their defining modules in the tests and in
  multipatch_gallery.py, since the package initializers are now empty.
- Empty sympde/utilities/__init__.py again, and export plot_domain in
  sympde.api from sympde.utilities.plotting.
- Restore the version of sympde/utilities/utils.py from this branch, which
  only contains lambdify_sympde: the merge had brought back the old
  plotting functions.
- Allow passing mapping and logical_domain of an Interface positionally,
  so that it can be reconstructed from its args.
- Use orientation instead of ornt in test_structural_arguments_are_sympy_objects.
Move the Matplotlib imports from the top of sympde/utilities/plotting.py into
_plot_domain_2d and _plot_domain_3d, so that importing the module (or
sympde.api) does not load Matplotlib (see #180).
Import from sympde.api in the examples of Interface and Domain.join, and
refer to Domain by its defining module in the plotting docstrings, since
the package initializers are empty after #194.
Import from sympde.api in the examples of doc/multipatch.rst, and add
collect_topology_vertices and print_topology to sympde.api, since the
documentation uses them. Point the migration table to sympde.api.plot_domain.
Describe the changes of this PR, and remove duplicated and outdated entries
from the Unreleased section.
Resolve the merge conflict in the docstring of Domain.join: the doctests of
this branch replace the code block that #191 had added on master, since
they render correctly and show the same 2D connectivity.
@yguclu

yguclu commented Oct 20, 2026

Copy link
Copy Markdown
Member

Thanks for this PR!

I have merged master into your branch and tried to resolve all the conflicts... I hope I have not introduced big problems! Accordingly, I have updated the PR description (see the new section "Integration with the public API and the SymPy upgrade"). I also removed the disclaimer: since the PR is squash-merged, the description becomes the commit message, where it is not really useful. I left the section "Some plots" where it is, but I will make sure that it is not included in the final merge commit.

Could you also have a look at #140? Domain.join still does not check that all patches have the same physical dimension pdim

@yguclu

yguclu commented Oct 22, 2026

Copy link
Copy Markdown
Member

Will this PR also close #114?

@FrederikSchnack

Copy link
Copy Markdown
Contributor Author

Will this PR also close #114?

Yes, it should. See the two patch twisted strip example. I will update the description.
I will get back to this PR now, and also look into #140. And I'm not sure if this is also a good place for #200 .

@campospinto
campospinto self-requested a review October 22, 2026 12:48
@yguclu yguclu self-assigned this Oct 22, 2026
@yguclu

yguclu commented Oct 22, 2026

Copy link
Copy Markdown
Member

Will this PR also close #114?

Yes, it should. See the two patch twisted strip example. I will update the description. I will get back to this PR now, and also look into #140. And I'm not sure if this is also a good place for #200 .

Issue #200 is explicitly fixed by the small PR #201, which can be merged very soon. I will ask for a small check to be added to todict in the same PR, which should not conflict with your (much larger) PR

@yguclu

yguclu commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

I have just created the new issue #203. Naturally, that should be fixed in this PR once #201 is merged

Joining a planar patch with a surface in 3D created an inconsistent
domain. Check that all patches have the same physical dimension, which
is the logical dimension for a patch without a mapping, and document
the requirement in the docstring and in the multipatch documentation.

Fixes #140.
A domain whose patches are InteriorDomain objects without a dtype was
exported with `dtype: [None, None]`, and reading it back failed at
`assert all(dtype)`. Such patches have no parametric box from which
Domain.join could derive the boundary, and their boundaries may have no
axis or extremity.

Rebuild these domains directly from the stored interiors, boundaries
and interfaces, keeping their names and orientations. A file in which
only some patches have a dtype is rejected, and mapped patches without
a dtype are not supported.

Fixes #144.
The interfaces were stored in `args` in the order in which they were
given, so that two joins of the same patches with the interfaces in a
different order compared unequal. Since Domain.from_file reads them
sorted by name, a domain also compared unequal to itself after an
export/from_file round trip whenever the interface names were not in
alphabetical order.

Store the interfaces sorted by name, and reject an iterable of
interfaces with duplicate names, which used to silently drop all but
the last one.
The logical interface names (A|B, A|B#2) were generated separately from
the physical ones (F(A)|G(B), ...), in the order of the connectivity,
and were not serialized. Domain.from_file reads the interfaces sorted by
name and passes their stored names as explicit names, so after a round
trip the logical names could end up on different interfaces. Explicit
names were also not given to the logical interfaces.

Generate one name per interface from the logical patch names, and give
it to both the mapped and the logical interface. The names are then
preserved by export/from_file, and joining mapped patches names the
interfaces like mapping a joined logical domain.
A domain only knew its logical dimension, so that the physical
coordinates of a surface in 3D were [x, y] instead of [x, y, z], and
the physical dimension was recomputed from the mappings in several
places. Add the properties ldim and pdim to the domain classes: pdim is
the physical dimension of the mapping, or ldim without a mapping. For a
boundary or an interface, they are the dimensions of its patches; the
dimension of the side itself remains intrinsic_dim.

- The Domain constructor checks that all interiors have the same
  physical dimension, which was only checked by Domain.join().
- The physical coordinates of a mapped domain are built from pdim.
- LogicalExpr and TerminalExpr use pdim where they enumerate the
  physical coordinates and the components of the mapping, so that all
  of them are mapped on a surface in 3D.
- Domain.todict(), Domain.join() and plot_domain() use pdim instead of
  recomputing it from the mappings.

The dim property is kept for now as an alias of ldim.

Part of #203.
A domain now has a logical and a physical dimension, so that `dim` is
ambiguous. Replace the `dim` property and the `dim` constructor argument
of the domain classes (Domain, InteriorDomain, NCubeInterior, NCube,
Union, Boundary, Interface, ...) by `ldim`, without keeping `dim` as an
alias, and update their uses in SymPDE, the tests and the
documentation. Also remove Boundary.patch_dim and Interface.patch_dim,
which are the same as ldim.

The `dim` argument of the mappings, a shorthand for ldim = pdim = dim,
is kept, as well as the dimension of the differential forms in
sympde.exterior. The parameters of a generic NCube stored in a file are
now `ldim`, `min_coords` and `max_coords`.

Part of #203.
It used the nonexistent attribute self.interface, and compared the sides
of the interfaces with the given domains, so that it always failed.
Return the interfaces that join two patches, in either order, which may
be several (#114), one self-interface, or none.
Domain.from_file() raised a bare KeyError when an interface of the file
references a patch that is not in the file, while an unknown patch in a
boundary already raised a ValueError.
The example showed the side names A_0 and B_1, while Domain.export()
writes the names of the boundaries, \Gamma_2 and \Gamma_3, with the keys
in the order of the file.
Domain.interface_map and Domain.connectivity returned the Connectivity
of the domain, which could be changed with item assignment or with
Domain.set_interfaces(), without changing the args and the hash of the
domain. Remove Connectivity.__setitem__ and Domain.set_interfaces(),
copy the dictionary given to Connectivity, and remove the unused
Connectivity.patches, which returned a list shared by all instances.

Also fix split(), which cut a Line domain into two Lines with wrong
bounds and stored a pair of boundaries as an interface: join the two
Lines with Domain.join().
On a multipatch domain, Domain.get_boundary(axis, ext) returned the
first exterior side with this axis and extremity, whatever its patch.
Add an optional patch argument, and raise a ValueError when several
patches have such a side and no patch is given.
Interface.minus_side and Interface.plus_side were aliases of
Interface.minus and Interface.plus, Boundary.normal_axis of
Boundary.axis, and Boundary.patch of Boundary.domain. Keep one name for
each, and document that Boundary.domain is the patch of the side.
It returned the same tuple of patch interiors as the new
Domain.patches, whose name matches the multipatch vocabulary of
Domain.join(), Domain.patch_index() and PatchSide, while
Domain.get_subdomain() returns a domain made of several patches.
It returned the same read-only mapping as the new Domain.interface_map,
while the connectivity argument of Domain and Domain.join() is the list
of interfaces they are created from. Keep the name connectivity for the
argument only.
The sides are those of domain.boundary, and the vertices and edges of
the domain already tell whether they lie on the boundary with
is_boundary. Rename Domain.exterior_sides to Domain.boundary_sides and
Domain.indexed_exterior_sides to Domain.indexed_boundary_sides, and say
boundary side instead of exterior side in the documentation and the
error messages.
Port the two mappings added to psydac.feec.multipatch_domain_utilities in PSYDAC #634, next to TransposedPolarMapping. Like it, they are TargetMapping and CzarnyMapping with the angle and radius coordinates swapped, which PSYDAC uses for its polar CONGA projections on (theta, s) coordinates.

Port the test of PSYDAC #634, which checks that the three transposed mappings equal the original ones with swapped logical coordinates and that the determinant of their Jacobian changes sign. It replaces the previous test of TransposedPolarMapping.

Make all analytical mappings available in sympde.api: add the three transposed mappings, TorusMapping and TwistedTargetMapping, and test that the API contains every mapping defined in sympde.topology.analytical_mapping.
LogicalExpr parametrizes an interface integral by its minus face, and
builds the surface measure from the Jacobian without the column of
interface.minus.axis. When _split_expr_over_interface moves a term with
only plus-side functions to interface.plus, it replaced the mapping but
kept that axis, so the measure used a tangent of the minus face when
minus.axis != plus.axis. Use the plus normal axis instead, in the
bilinear and linear branches.

The linear branch also differed from the bilinear one in two other
ways: it did not replace the interface by its minus or plus side in the
boundary expressions, so TerminalExpr evaluated the plus-side measure
in the x_plus coordinates of mixed terms, and it did not flip the
normal vector on the plus side, whose outward normal is the opposite
of the interface normal. Do both as in the bilinear branch.

Test the surface measures on both sides of a cross-axis polar pair and
of the two_cube gallery domain, and the sign of the normal derivative
on both sides of an interface, for linear and bilinear forms.

Add a changelog entry for the two fixes of the linear branch, which are
already on master. The cross-axis measure was never released, since
master required equal normal axes on both sides of an interface.
Interface.axis_map only relates the tangential axes of the two faces,
so every discretization code rebuilds the full transform between the
logical coordinates of the two patches, including the normal axes and
the affine map that uses the patch bounds. PSYDAC does it in several
places.

Add the mixin InterfaceTransform, used by Interface and
IndexedInterface, with normal_direction (-minus.ext * plus.ext),
signed_permutation and inverse_signed_permutation (the plus axis and
direction of every minus axis, normal included, and the reverse),
permutation_matrix, handedness (its determinant) and map_point(), which
maps logical coordinates from the minus to the plus patch, or the
reverse with inverse=True, for given bounds of the logical coordinates.

Add map_component(), which relates the logical components of H(curl)
and H(div) fields on both sides, following the pull-backs of PullBack:
the tangential covariant components, and the normal contravariant Piola
component with the signed Jacobian determinant. Only the tangential
columns of the Jacobians of the two mappings match on the interface, so
the other components, and L2 densities, have no relation unless the
geometry is smooth across it. map_component() raises a ValueError for
them, and for a component outside range(ldim), since a negative index
would silently select a component from the end.

Test every pair of faces and orientation in 1D, 2D and 3D: the
consistency with axis_map, the inverse and the determinant, the images
of the corners against the identification of the domain vertices, the
round trip, face and Jacobian of map_point with non-unit bounds, and the
signs and inverse of map_component. Check map_component with the
pull-backs of smooth fields at the interfaces of the gallery domains and
of a patch pair whose geometry is not smooth across the interface, on
which the L2 relation fails, as it does on the gallery domain pretzel_f.
Document the transform in the multipatch user guide.
Domain.join() accepts non-orientable gluings without telling, and the
patches of a mapped domain may be left-handed, with different
handedness on different patches. Discretizations of oriented quantities
such as H(div) fields must know whether the domain is orientable.

Add Domain.patch_handedness, one sign per patch such that the sign of
the plus patch of every interface is the sign of its minus patch times
the handedness of the interface, with +1 for the first patch of every
connected component, or None if the domain is not orientable, and
Domain.is_orientable. They are computed by the new function
orient_patches() of sympde.topology.incidence. If the mappings have
ldim == pdim and match on the interfaces, the signs of their Jacobian
determinants follow these signs, so that a non-orientable domain with
ldim == pdim cannot be realized geometrically. Non-orientable domains
are still accepted, since they are valid topologies.

Test the signs against the Jacobian determinants of the gallery domains,
including those with left-handed and mixed-handedness patches, and
non-orientable self-interfaces, cycles and connected components. Mark
the twisted strip of the gallery, a Möbius strip whose mappings do not
match on one interface, as a topological diagnostic, and document the
orientability in the multipatch user guide.
Domain.vertices and Domain.edges list the patch-local corners and edges
of every global vertex and edge, but conforming projectors need the
reverse: the vertex, edge or side that a corner, edge or side of a patch
belongs to.

Add Domain.vertex_of(), Domain.edge_of(), which also returns the
direction of the patch edge relative to the first incidence of the
edge, and Domain.side_of(), which returns the indexed interface or the
boundary side that contains a side of a patch. Their lookup tables are
computed when they are first needed, like the vertices and edges.

The incidences of a vertex or an edge may contain the same patch more
than once if a patch is glued to itself. Document that they must be
keyed by the patch index and the logical corner or edge.
Document also how to tell whether a side is the minus or the plus side
of the interface returned by side_of(), which decides whether
map_point() and map_component() need inverse=True.

Test that every corner, edge and side of the patches of the gallery
domains is found once and agrees with the vertices, edges, interfaces
and boundary sides, the lookups on a single-patch 3-torus, and the
errors for unknown entities.
Pylint (E1120, reported by Codacy) does not see through the star
unpacking of two lists in the call of _check_pullbacks() and reports a
missing argument. Pass the four arguments by name of their variables.
The plotting module re-derived topology that Domain now provides, and
split its drawing into many small helpers, several of them used once.

Use domain.indexed_interfaces and PatchSide.patch_index instead of a
patch-to-index dictionary, domain.indexed_boundary_sides instead of
recomputing the exterior faces from the interfaces, and the vertices
alone for the neighbours in the colouring of the patches, since patches
that share an interface share its vertices. Import _patch_name from
sympde.topology.incidence instead of duplicating it.

Inline the helpers used once, merge _face_points into _map_face, and
draw the shared topology annotations in plot_domain instead of in two
copies for 2D and 3D. Remove the unused fields of the plot model, build
the outline of a 2D patch from its sampled faces instead of sampling
them again, and name these face_samples.

The plots are unchanged: all gallery domains, with and without topology
and isolines, give identical images. The colouring test now derives the
neighbours from the vertices and interfaces itself.
The mapped and the logical patches are both sorted by name, and the
mapped names can sort differently from the logical ones. A position in
logical_domain.patches was then the wrong position in patches, so
get_boundary and get_interface picked the wrong patch when given a
logical one. Match the logical domain of each mapped patch instead.
The Domain.join docstring said that the positions in the input list
define the patch indices. This only holds for the integers given in the
connectivity: the joined domain sorts its patches by name, and all of
its patch indices are positions in domain.patches. Say so in the
docstrings of join and patches, and in the multipatch documentation.

Zero-pad the row and the column in the patch names of
build_cartesian_multipatch_domain_2d, so that the name order is the
row-major order of the layout also with ten or more rows or columns.
_plus_side_measure matched exactly the symbol
JacobianSymbol(mapping.plus, axis=interface.minus.axis). If LogicalExpr
built the measure differently, nothing matched, and cross-axis
interfaces silently got the wrong surface measure again.

Replace every JacobianSymbol of mapping.plus with an axis instead, which
LogicalExpr only creates for surface measures, and raise an error when a
nonzero plus-side expression contains none.
patch_index scanned the patches with deep SymPy comparisons, and
get_interface called it twice for every interface. indexed_interfaces
and patch_handedness were rebuilt on every access, while vertices and
edges were cached.

Look up patches in a cached dictionary of the mapped and the logical
interiors, let get_interface filter the indexed interfaces by patch
index, and cache indexed_interfaces and patch_handedness like the
vertices and the edges.

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

None yet

Projects

None yet

2 participants