Skip to content

Default to pre_apply_bcs=False - #5185

Open
pbrubeck wants to merge 3 commits into
pbrubeck/equationbc-matfree-aijfrom
pbrubeck/default-pre-apply-bcs
Open

pbrubeck wants to merge 3 commits into
pbrubeck/equationbc-matfree-aijfrom
pbrubeck/default-pre-apply-bcs

Conversation

@pbrubeck

@pbrubeck pbrubeck commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

AI assistance: Claude Code (Claude Opus 5.5) helped to write the changes for EquationBC and this description.

Summary

Fixes #5177

Stacked on #5766, which eliminates the same Dirichlet columns from the domain rows and from each EquationBC row, and lifts each EquationBC residual with its own Jacobian.

This PR changes the default model for DirichletBC to pre_apply_bcs=False, deprecating pre_apply_bcs=True.

In the deprecation era, pre_apply_bcs=True only applies bcs at the beginning of the solve, and _SNESContext becomes independent of pre_apply_bcs, which means that the residual lifting term is always computed (it will be zero when the bcs are satisfied).

We also make sure that bcs are always pre applied if restrict=True, and for this case we never compute the residual lifting term.

On an unrestricted space, the solver lifts the Dirichlet conditions around the current state $u$:

r = u - g on the Dirichlet nodes, r = 0 elsewhere
F_lifted(u) = F(u) - J(u) r

This is $F(u - r)$ to first order, and $u - r$ takes the boundary values $g$. For a linear problem it is exactly $F(u - r)$, so the linear case uses the same code.

The same model now also applies to the Dirichlet conditions inside an EquationBC:

 solve(F == 0, u, bcs=[EquationBC(G == 0, u, 1, bcs=[DirichletBC(...)])])
-  apply the DirichletBC inside the EquationBC to u before the linearisation
+  linearise around the supplied u for every DirichletBC

Changes for users

Change Before After
Default pre_apply_bcs in solve and NonlinearVariationalSolver True False
pre_apply_bcs=True supported DeprecationWarning
DirichletBC inside an EquationBC applied to the initial guess linearised around the initial guess
Scalar DirichletBC value on a vector-valued space fails in the boundary residual applies to every component

Implementation details

  • _SNESContext no longer takes pre_apply_bcs. It adds the lifting term when problem.restrict is False, and it zeroes the boundary rows of the residual when problem.restrict is True. The solver applies the Dirichlet conditions to the initial guess only for pre_apply_bcs=True or on a restricted space, because PETSc cannot update excluded degrees of freedom.
  • The multigrid coarsening (firedrake/mg/ufl_utils.py) and AuxiliaryOperatorSNES no longer apply the boundary conditions themselves.
  • DirichletBC.apply(r, u=u) subtracts a scalar value with the Assigner, which broadcasts it to every component.

Limitations

  • The lifting adds one coefficient to each residual kernel on an unrestricted space, also when the initial guess already satisfies the boundary conditions. TSFC compiles the lifting term into the same kernels as the residual, so the solver does not do an extra loop over the mesh. If the Jacobian is an assembled matrix, the lifting is a separate matrix-vector product.

Evidence

test_nested_dirichletbc_linearises_at_initial_guess solves one Newton step (snes_type: ksponly) from $u = 0$ for

F(u; v) = (grad u, grad v) + (u**2, v)               in the domain
G(u; v) = (u_y, v_y) + (u**2, v)                     on boundary 1
u = 1 at the corner of boundaries 1 and 3            DirichletBC inside the EquationBC

At $u = 0$ the u**2 terms do not change the linearised equations, so the exact solution of the linearised problem is the constant 1.

  • Before: the solver applies the corner value before the linearisation. errornorm(Constant(1), u) = 0.0528 for both aij and matfree, so the test fails.
    After: errornorm(Constant(1), u) < 1e-12 for both aij and matfree, on 1 and 3 processes.
  • tests/firedrake/equation_bcs/test_equation_bcs.py: 22 passed, 2 skipped on 1 process, and 5 passed on 3 processes.

Merge Danger

Door: two-way

pre_apply_bcs=True is deprecated, not removed, so users can get the old behaviour back for one solve.

Blast Radius: solvers

Every nonlinear solve with a DirichletBC on an unrestricted space now evaluates the lifted residual. Iteration counts and the first residual norm can change, most for initial guesses that do not satisfy the boundary conditions.

🤖 Drafted with Claude Code

@pbrubeck
pbrubeck force-pushed the pbrubeck/default-pre-apply-bcs branch from 51dda7d to 5631a68 Compare June 17, 2026 10:23
Comment thread firedrake/solving_utils.py Outdated
Ftrial = problem.compute_bc_lifting(self.J, trial, L=problem.L)
self.F = ufl.replace(Ftrial, {trial: self._x - self._bc_residual})
else:
self.F -= problem.compute_bc_lifting(self.J, self._bc_residual)

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.

With pre_apply_bcs=False, we are adding this extra term to the residual F (more code to compile and execute). However this can be prevented in the linear case, as I explain in the comment.

For the nonlinear case, there is a way to reduce execution time by assuming that bc_residual is only supported on cells that along the boundary. We could restrict the integrals in J onto that subset of cells.

@pbrubeck pbrubeck Jun 17, 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.

Note that pre_apply_bcs=True implies that self._bc_residual = 0 throughout the solve (if the Newton updates satisfy homogenous BCs by solving the bc identity matrix exactly), and this is why we did not have this term before.

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.

We could probably lazily assemble this individual term only when bc_residual is nonzero.

@pbrubeck
pbrubeck force-pushed the pbrubeck/default-pre-apply-bcs branch 2 times, most recently from 8e15f0b to 83292ee Compare June 17, 2026 11:10
Comment thread firedrake/solving_utils.py Outdated
self.F = ufl.replace(self.F, {self._x: ufl.zero(self._x.ufl_shape)})

self.F -= problem.compute_bc_lifting(self.J, self._bc_residual)
if problem.is_linear and hasattr(problem, "L"):

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.

Ideally we would be testing isinstance(problem, LinearVariationProblem), but by doing this I am avoiding a cyclic import. I can have a go at fixing the cyclic import if that is preferred.

@pbrubeck
pbrubeck force-pushed the pbrubeck/default-pre-apply-bcs branch from 83292ee to 7f7a302 Compare June 17, 2026 11:18
if bcs and any(isinstance(bc, EquationBC) for bc in bcs):
restrict = False
self.restrict = restrict and bcs
self.restrict = restrict and bool(bcs)

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 was setting self.restrict = bcs

@pbrubeck pbrubeck Jun 17, 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.

I am casting bool(bcs) because the default is bcs=None, and it's too early to extract_bcs(bcs), which parses bcs into an iterable

Comment thread firedrake/solving_utils.py Resolved
Comment thread firedrake/variational_solver.py Outdated
problem.u_restrict.assign(problem.u)

if self._ctx.pre_apply_bcs:
if self.pre_apply_bcs or problem.restrict:

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.

In the deprecation era, pre_apply_bcs=True only applies bcs at the beginning of the solve, and _SNESContext becomes independent of pre_apply_bcs, which means that the residual lifting term is always computed (it will be zero when the bcs are satisfied)

@stefanozampini

Copy link
Copy Markdown
Contributor

@pbrubeck What happened with this MR? I want to stress again that pre_apply_bcs=True is simply the wrong approach with inexact Newton, because you cannot expect approximate linear solves to exactly resolve the diagonal equations of the BC dofs

@pbrubeck
pbrubeck marked this pull request as ready for review December 2, 2026 19:15
@pbrubeck pbrubeck added the LLM used An LLM was used in the production of this PR label Dec 2, 2026
@pbrubeck
pbrubeck changed the base branch from main to pbrubeck/equationbc-matfree-aij December 3, 2026 10:04
@pbrubeck
pbrubeck force-pushed the pbrubeck/default-pre-apply-bcs branch from 1107748 to 28ab38f Compare December 3, 2026 10:04
@pbrubeck pbrubeck added the base:main Run this PR using a main (dev) build label Dec 3, 2026
@pbrubeck
pbrubeck added this pull request to stack #5768 December 3, 2026 10:11
pbrubeck and others added 3 commits December 3, 2026 10:30
DirichletBC.apply(r, u=u) computed u - g in UFL, which fails when a
vector-valued space has a scalar value, for example bc.set_value(7).
Copy u and subtract the scalar in place with the Assigner, which
broadcasts it to every component. Keep the single assignment of u - g
when the shapes match, so that no new kernels are compiled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Change the default of pre_apply_bcs to False in solve and in
NonlinearVariationalSolver, and deprecate pre_apply_bcs=True. On an
unrestricted space the solver now always lifts the Dirichlet conditions
around the current state u: it assembles F(u) - J(u) r, where r = u - g
on the Dirichlet nodes and r = 0 elsewhere. This is F(u - r) to first
order, and exactly F(u - r) for a linear problem, so the linear case
uses the same code. pre_apply_bcs=True only applies the boundary
conditions to the initial guess.

On a restricted space PETSc cannot update the excluded nodes, so the
solver always applies the boundary conditions to the initial guess and
adds no lifting term.

The DirichletBCs inside an EquationBC follow the same model: the solver
linearises around the supplied initial guess for every Dirichlet
condition. The multigrid coarsening and AuxiliaryOperatorSNES no longer
apply the boundary conditions themselves.

assemble(a, tensor=A, bcs=bcs) now sets A.bcs to bcs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The H1 error is 1.9e-12 at the tolerance of the Krylov solver, which is
above the earlier limit of 1e-12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbrubeck
pbrubeck force-pushed the pbrubeck/default-pre-apply-bcs branch from 28ab38f to efb5e04 Compare December 3, 2026 10:35

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

base:main Run this PR using a main (dev) build 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.

SNES updates can be inconsistent with default DirichletBC treatment

2 participants