Skip to content

Allow prepared BC data in Python matrix assemblers - #4648

Open
garth-wells wants to merge 28 commits into
mainfrom
python/prepared-matrix-bcs
Open

garth-wells wants to merge 28 commits into
mainfrom
python/prepared-matrix-bcs

Conversation

@garth-wells

@garth-wells garth-wells commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Repeated Python matrix assembly rebuilt the constrained-dof markers, diagonal rows and (for MATIS) the sharing-adjusted diagonal values from DirichletBC objects on every call. This PR lets that data be prepared once and reused.

Fixes #4596. Supersedes #4614.

API

  • dolfinx.fem.prepare_matrix_bcs(a, bcs, diag=1.0) -> MatrixBCData and dolfinx.fem.petsc.prepare_matrix_bcs(A, a, bcs, diag=1.0) -> BlockMatrixBCData.
  • The bcs argument of fem.assemble_matrix, fem.assemble_matrix_fn, fem.petsc.assemble_matrix and fem.petsc.assemble_jacobian accepts either a sequence of DirichletBC or prepared data.
  • Prepared data depends on the function spaces and constrained dofs (and, for PETSc, on whether each diagonal block is assembled or MATIS), not on boundary condition values. It can be reused with any form on the same spaces, e.g. data prepared from a mass matrix for a stiffness matrix, and across nest and blocked PETSc matrices.
  • MatrixBCData and BlockMatrixBCData are frozen dataclasses with flat fields; arrays are read-only. Reuse is checked cheaply (space identity, marker sizes, diagonal row range, PETSc diagonal layout) before the matrix is touched. Data for the wrong matrix type, or single-form data used with a form array, is rejected.
  • diag on assemble_matrix is deprecated: pass prepare_matrix_bcs(..., diag=...) as bcs instead. It still works with a DeprecationWarning, and cannot be combined with prepared data. Boundary conditions given directly use a diagonal of 1.

Library use

  • fem.petsc.LinearProblem and fem.problems.LinearProblem (SuperLU_DIST) prepare the data when bcs is assigned and reuse it on every solve, including the lifting markers.
  • fem.petsc.NonlinearProblem prepares the data, the per-block grouping of conditions and the Jacobian column spaces once. Newton steps reuse them in both the Jacobian and the residual; boundary condition values are still read on every step. The Jacobian callback is the public assemble_jacobian, given the prepared data; each step repeats only its cheap checks.

Other changes

  • LinearProblem.solve and the Jacobian callback overlap assemblyBegin/assemblyEnd of the operator with assembly of the preconditioner and right-hand side.

Testing

  • New test_matrix_bc_data.py and test_petsc_matrix_bc_data.py: repeated assembly without rebuilding (checked by monkeypatching the builders), scalar/vector spaces, real/complex CSR, rectangular forms, the callback assembler, assembled/MATIS/nest/blocked PETSc matrices, reuse across forms and matrix kinds, read-only data, invalid data, and NonlinearProblem Newton steps that do not rebuild BC data, with a preconditioner and changing coefficients, boundary values and conditions (single, blocked, nest, MATIS and nested MATIS; adapted from Cache invariant SNES assembly data in NonlinearProblem #4614).
  • Locally: python/test/unit/{fem,nls,la} 3241 passed serially; the PETSc, BC-data, assembler, problems, Newton and la PETSc tests passed on 2, 3 and 4 MPI ranks. ruff check/ruff format --check pass and Pyrefly reports no new diagnostics.

AI assistance: I used OpenAI Codex and Claude Code (Claude Opus 5.5) to draft parts of this PR. I reviewed, edited, tested, and take responsibility for the final contribution.

🤖 Generated with Claude Code

@garth-wells garth-wells added performance python Pull requests that update Python code labels Oct 18, 2026
garth-wells and others added 9 commits October 24, 2026 13:57
- Share prepared-data validation between the CSR assemblers and
  assemble_matrix_fn, and validate only prepared data, not data
  just built from boundary conditions.
- Build the PETSc MatrixBCData from the private marker and diagonal
  records instead of flattening and repacking them on every assembly.
- Cache PETSc block index sets in prepared data and in LinearProblem,
  rather than rebuilding them on every blocked assembly.
- Attribute the diag DeprecationWarning to the caller, so it is shown
  under default warning filters.
- Raise TypeError when prepared data for the other matrix type is
  passed, instead of iterating it as boundary conditions.
- Check prepared diagonal rows (dtype, local range) and values (shape,
  scalar type), and reject a complex diag for a real scalar type.
- Document the per-block diagonal value layout, including MATIS shares.
- fem.LinearProblem caches prepared CSR BC data.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- fem.MatrixBCData and the PETSc prepared data are frozen, slotted
  dataclasses rather than named tuples, so they are not sequences
  (and cannot be mistaken for a sequence of boundary conditions), and
  field order is not part of the API.
- Rename the PETSc class to BlockMatrixBCData, distinct from
  fem.MatrixBCData.
- Both derive from a private base, so the foreign-data check is a
  plain isinstance test rather than a named-tuple attribute probe.
- Tests use dataclasses.replace, and check both cross-backend
  directions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_prepared_matrix_bcs_invalid_diagonal compiled a float64 form on a
mesh with the default real type, which fails on float32 builds. Create
the mesh as float64 explicitly.

Sphinx (nitpicky) could not resolve the private prepared-BC classes
referenced by the public MatrixBCData/BlockMatrixBCData; ignore them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- NonlinearProblem prepares matrix BC data once and passes it to
  assemble_jacobian, which now accepts prepared data, so Newton steps
  no longer rebuild markers, MATIS diagonal shares and index sets.
- PETSc LinearProblem uses prepare_matrix_bcs instead of rebuilding
  its pieces by hand.
- _assemble_matrix_petsc and _assemble_matrix_csr_markers take the
  prepared data object rather than its unpacked fields.
- Remove an unreachable block-count check and reuse _form_block_spaces
  in _check_preconditioner_spaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MatrixBCData and prepare_matrix_bcs are also used by the callback
assembler, so describe them by the bilinear form they belong to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The nanobind bindings already enforce marker dtype, rank and
contiguity. Keep only the size check, which guards the unchecked
indexing in C++ assembly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@garth-wells
garth-wells marked this pull request as ready for review November 7, 2026 12:03
garth-wells and others added 9 commits November 7, 2026 12:47
BlockMatrixBCData now has flat per-block fields (row_markers,
column_markers, row_spaces, column_spaces, diagonal_rows,
diagonal_values, diagonal_ghosts, index_sets), matching MatrixBCData,
instead of wrapping the private _MatrixBCData and _MatrixDiagData.
Internal helpers take spaces/markers or the prepared data directly.
The Sphinx nitpick exception now covers only the private base class.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Inline the single-use _matrix_index_sets into prepare_matrix_bcs.
- Rename _assemble_matrix_csr_markers to _assemble_matrix_csr_prepared.
- Share one matrix comparison helper in the PETSc BC data tests.
- Fix inaccurate docs: assemble_matrix_fn passes process-local
  indices and never sets the diagonal; NonlinearProblem reuses prepared
  data for the Jacobian as well as the residual; state when PETSc
  prepared data can be reused.
- Make the MatrixBCData/BlockMatrixBCData, prepare_matrix_bcs, bcs and
  diag docstrings shorter and consistent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
prepare_matrix_bcs now builds index sets for any form array, not only
for blocked matrices, so reusing nest-prepared data with a blocked
matrix no longer rebuilds them on every call. Index sets are local
stride sets, so the unused ones for a nest cost almost nothing. Data
prepared for a single form is rejected for a form array.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Group boundary conditions by block once in the NonlinearProblem bcs
  setter and pass them to _assemble_residual, instead of regrouping on
  every residual evaluation.
- Split Jacobian assembly into a private _assemble_jacobian, which
  NonlinearProblem registers with SNES. It checks only the diagonal
  layout of the matrix SNES passes in; the public assemble_jacobian
  keeps the full checks.
- Overlap Jacobian and preconditioner matrix assembly.
- Test that Newton steps neither rebuild nor re-check BC data for
  single, blocked and nest problems.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- LinearProblem.solve called assembleBegin/assembleEnd, which petsc4py
  does not have; use assemblyBegin/assemblyEnd. This broke every
  LinearProblem solve in the previous commit.
- Pass the prepared Jacobian column spaces to the NonlinearProblem
  residual so block lifting no longer re-extracts them each Newton
  step, and check this in the reuse test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Start every sub-vector ghost update before finishing any, so the
neighbour exchanges of the blocks of a nest vector overlap rather than
running one after another. Results are unchanged; the gain is in
latency on multi-node runs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adapt the callback test from #4614: cover single, blocked, nest, MATIS
and nested MATIS layouts with a preconditioner, change coefficients,
boundary values and the conditions between evaluations, and compare
the SNES callbacks with fresh public assembly while the BC preparation
and check helpers are patched to fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
NonlinearProblem registers the public assemble_jacobian with prepared
BC data, so there is one Jacobian code path. Each Newton step repeats
the cheap preconditioner-space and prepared-data checks, but still
reuses the markers, diagonal rows and MATIS sharing data. Clarify the
docs for the u argument of the SNES callbacks.

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

Copilot AI 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.

🟡 Changes recommended

Aliased Jacobian and preconditioner matrices can be modified while assembly is pending, and missing marker-dimensionality checks can allow partial block-matrix modification before validation fails.

2 open issues
What changed in this PR

This PR adds reusable boundary-condition data to Python matrix assembly, reducing repeated setup work in linear solves and Newton callbacks, including MATIS communication.

Changes:

  • Adds prepared BC data APIs for CSR and PETSc matrices and deprecates the assembly-time diag argument.
  • Reuses prepared data in solver wrappers and overlaps matrix assembly and nested-vector ghost updates.
  • Adds regression coverage for repeated assembly, data validation, matrix layouts, and changing boundary conditions.
File Description
python/​test/​unit/​fem/​test_petsc_matrix_bc_data.py Tests PETSc prepared data and nonlinear callback reuse.
python/​test/​unit/​fem/​test_matrix_bc_data.py Tests CSR and callback assembly with prepared data.
python/​test/​unit/​fem/​test_fem_pipeline.py Migrates custom diagonal assembly to prepared data.
python/​test/​unit/​fem/​test_assembler.py Removes an unnecessary explicit diagonal argument.
python/​dolfinx/​la/​petsc.py Overlaps nested-vector ghost updates.
python/​dolfinx/​fem/​problems.py Reuses prepared BC data in SuperLU_DIST solves.
python/​dolfinx/​fem/​petsc.py Adds PETSc preparation APIs and integrates solver caching.
python/​dolfinx/​fem/​assemble.py Adds CSR preparation, validation, and assembly support.
python/​dolfinx/​fem/​__init__.py Exports the new public APIs.
python/​doc/​source/​conf.py Suppresses references to the private prepared-data base class.

Review effort: Balanced

Comment thread python/dolfinx/fem/petsc.py Resolved
Comment thread python/dolfinx/fem/assemble.py Resolved
garth-wells and others added 5 commits November 7, 2026 17:16
A ghosted vector and its duplicate() share PETSc's ghost scatter,
which allows one update in flight. A nest holding both failed with
PETSc error 73 when every sub-vector update was started before any
finished. Update sub-vectors sequentially again, and test a nest of
duplicated sub-vectors.

This reverts commit 4bd5ba3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The bindings convert marker dtype and layout but reject other
dimensions, so for a block matrix a 2D marker was caught only after
earlier blocks were modified. Check dimensionality up front. Document
that the Jacobian and preconditioner matrices passed to
assemble_jacobian must not share storage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Off-process contributions may be summed in a different order, so
compare matrices to a scalar-type-aware relative tolerance rather than
a fixed absolute 1e-12.

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

performance python Pull requests that update Python code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SNES assembly callbacks rebuild per-solve invariants on every call

3 participants