diff --git a/firedrake/assemble.py b/firedrake/assemble.py index c386b38152..72a36fac26 100644 --- a/firedrake/assemble.py +++ b/firedrake/assemble.py @@ -977,6 +977,11 @@ def assemble(self, tensor=None, current_state=None): else: self._check_tensor(tensor) if self._needs_zeroing: + if isinstance(tensor, MatrixBase): + # Attach the boundary conditions here, because the EquationBC + # assemblers will add to this matrix with needs_zeroing=False and + # will eliminate the DirichletBC columns in tensor.bcs. + tensor.bcs = self._bcs # This is a big ol' hack to get subfunctions working op3_tensor = self._as_pyop3_type(tensor) # Use >= instead of == so we also work for Real @@ -1821,7 +1826,10 @@ def collect_lgmaps(self, matrix, indices): # A boundary condition only constrains the argument that shares its space. row_bcs = [bc for bc in self._bcs if bc.parent_function_space.topological == row_space.topological] - col_bcs = [bc for bc in self._bcs + # Eliminate the same DirichletBC columns in the domain rows and in the rows of + # each EquationBC, because the residual lifts the DirichletBCs in all of these + # rows. matrix.bcs includes the DirichletBCs nested inside each EquationBC. + col_bcs = [bc for bc in matrix.bcs if isinstance(bc, DirichletBC) and bc.parent_function_space.topological == column_space.topological] diff --git a/firedrake/bcs.py b/firedrake/bcs.py index 61311671ee..6b3d3fa8e4 100644 --- a/firedrake/bcs.py +++ b/firedrake/bcs.py @@ -676,34 +676,73 @@ def add(self, bc): self.bcs.append(bc) @PETSc.Log.EventDecorator() - def reconstruct(self, field=None, V=None, subu=None, u=None, row_field=None, col_field=None, action_x=None, use_split=False): + def reconstruct(self, field=None, V=None, subu=None, u=None, row_field=None, col_field=None, action_x=None, use_split=False, + form=None, bcs=None): + """Return a new boundary condition built from this one, optionally on some fields of a mixed space. + + Parameters + ---------- + field : tuple[int] | None + The indices of the fields of the original mixed space that ``V`` contains. + If ``None``, keep the function space of this boundary condition. + V : firedrake.functionspaceimpl.WithGeometry | None + The function space of these fields. + subu : firedrake.function.Function | None + The Function to solve for in the new boundary condition. If ``None``, use ``self.u``. + u : ufl.core.expr.Expr | None + The expression that replaces ``self.u`` in the split form. It is used only + when ``field`` is given. + row_field : tuple[int] | None + The fields of the test function in the split form. If ``None``, use ``field``. + col_field : tuple[int] | None + The fields of the trial function in the split form. If ``None``, use ``field``. + action_x : firedrake.function.Function | None + If given, replace a bilinear form with its action on ``action_x``. + use_split : bool + Whether to index ``V`` with ``V.subspaces`` instead of ``V.sub``. + form : ufl.BaseForm | None + The form to use instead of ``self.f``. + bcs : collections.abc.Iterable | None + The boundary conditions of the new boundary condition. They are used without + change. If ``None``, the boundary conditions of this boundary condition are + rebuilt. + + Returns + ------- + EquationBCSplit | None + The new boundary condition, or ``None`` if this boundary condition is not on + one of the fields in ``field``. + """ + if form is None: + form = self.f subu = subu or self.u row_field = row_field or field col_field = col_field or field # define W and form if field is None: - # Returns self W = self._function_space - form = self.f else: assert V is not None, "`V` can not be `None` when `field` is not `None`" W = self.as_subspace(field, V, use_split) if W is None: return - rank = len(self.f.arguments()) + rank = len(form.arguments()) splitter = ExtractSubBlock() - form = splitter.split(self.f, argument_indices=(row_field, col_field)[:rank]) + form = splitter.split(form, argument_indices=(row_field, col_field)[:rank]) if u is not None: form = firedrake.replace(form, {self.u: u}) if action_x is not None: assert len(form.arguments()) == 2, "rank of self.f must be 2 when using action_x parameter" form = ufl_expr.action(form, action_x) - ebc = EquationBCSplit(form, subu, self.sub_domain, V=W) - for bc in self.bcs: - if isinstance(bc, DirichletBC): - ebc.add(bc.reconstruct(V=W, g=bc.function_arg, sub_domain=bc.sub_domain, use_split=use_split)) - elif isinstance(bc, EquationBCSplit): - bc_temp = bc.reconstruct(field=field, V=V, subu=subu, u=u, row_field=row_field, col_field=col_field, action_x=action_x, use_split=use_split) + ebc = EquationBCSplit(form, subu, self.sub_domain, bcs=bcs, V=W) + if bcs is None: + for bc in self.bcs: + if isinstance(bc, DirichletBC): + # Reconstruct the nested DirichletBC on its own field and component, + # which can differ from those of this boundary condition. + bc_temp = bc.reconstruct(field=field, V=V, g=bc.function_arg, sub_domain=bc.sub_domain, use_split=use_split) + elif isinstance(bc, EquationBCSplit): + bc_temp = bc.reconstruct(field=field, V=V, subu=subu, u=u, row_field=row_field, col_field=col_field, action_x=action_x, use_split=use_split) # Due to the "if index", bc_temp can be None if bc_temp is not None: ebc.add(bc_temp) diff --git a/firedrake/matrix_free/operators.py b/firedrake/matrix_free/operators.py index 6cf508a844..e73375884e 100644 --- a/firedrake/matrix_free/operators.py +++ b/firedrake/matrix_free/operators.py @@ -133,12 +133,6 @@ def __init__( if len(self.col_bcs) > 0: self._ybc = Function(test_space.dual()) - self._x_equationbc = None - if any(isinstance(bc, EquationBCSplit) for bc in itertools.chain(*self.bcs)): - # Preserve the original input for EquationBC actions while the - # ordinary form action uses zeroed columns. - self._x_equationbc = Function(trial_space) - # Get size information from template vecs on test and trial spaces trial_vec = trial_space.template_vec test_vec = test_space.template_vec @@ -161,7 +155,7 @@ def __init__( self.bcs_action = [] for bc in self.bcs: if isinstance(bc, EquationBCSplit): - self.bcs_action.append(bc.reconstruct(action_x=self._x_equationbc)) + self.bcs_action.append(bc.reconstruct(action_x=self._x)) self._assemble_action = get_assembler(self.action, bcs=self.bcs_action, @@ -215,9 +209,6 @@ def missingDiagonal(self, mat): def mult(self, mat, X, Y): with self._x.dat.vec_wo as v: X.copy(v) - if self._x_equationbc is not None: - with self._x_equationbc.dat.vec_wo as v: - X.copy(v) # if we are a block on the diagonal, then the matrix has an # identity block corresponding to the Dirichlet boundary conditions. @@ -264,21 +255,23 @@ def multTranspose(self, mat, Y, X): ( a a a a 0 a a ) | ( a a a a 0 a a ) | ( a a a a 0 a a ) | EBC1 - M = ( b b b b b b b ) | | EBC2 DBC1 + M = ( b b b b 0 b b ) | | EBC2 DBC1 ( 0 0 0 0 1 0 0 ) | | | | ( c c c c 0 c c ) | | ( c c c c 0 c c ) | | Multiplication algorithm: - To avoid copys, use same y, and update it from left - (deepest ebc) to right (least deep ebc or domain). - * below can be any number + To avoid copies, use the same y for each action, from the + deepest EquationBC to the domain. Then replace the DirichletBC + entries of the sum with the entries of y on a diagonal block, + or set them to zero on an off-diagonal block. Each * below can + be any number. ( a a a b 0 c c ) ( y0 ) ( a a a b 0 c c ) ( y1 ) ( a a a b 0 c c ) ( y2 ) M^T y = ( a a a b 0 c c ) ( y3 ) - ( 0 0 0 b 1 0 0 ) ( y4 ) + ( 0 0 0 0 1 0 0 ) ( y4 ) ( a a a b 0 c c ) ( y5 ) ( a a a b 0 c c ) ( y6 ) @@ -302,17 +295,11 @@ def multTranspose(self, mat, Y, X): ( a a a a a a a ) ( y1 ) on domain ( a a a a a a a ) ( y2 ) + ( a a a a a a a ) ( 0 ) Update y - ( 0 0 0 0 0 0 0 ) ( 0 ) Zero DBC1 columns + ( a a a a a a a ) ( 0 ) ( a a a a a a a ) ( 0 ) ( a a a a a a a ) ( 0 ) - ( 0 ) - ( 0 ) Add y at the end (DBC1) - ( 0 ) - + ( 0 ) - ( y4 ) - ( 0 ) - ( 0 ) + Replace the DBC1 entry of the sum with y4 """ with self._y.dat.vec_wo as v: @@ -332,30 +319,21 @@ def multTranspose(self, mat, Y, X): for obc in self.bcs: obc.zero(self._y) self._assemble_actionT(tensor=self._xbc) - # mult applies the domain form to x with zeroed DirichletBC - # columns, so the domain adjoint action must not contribute to - # those columns. - for bc in self.col_bcs: - bc.zero(self._xbc) self._xstar += self._xbc else: # No DirichletBC/EquationBC on the rows # Save the domain actionT to self._xstar directly self._assemble_actionT(tensor=self._xstar) - # mult applies the form to x with zeroed DirichletBC columns. - for bc in self.col_bcs: - bc.zero(self._xstar) if self.on_diag: if len(self.col_bcs) > 0: - # Preserve contributions from EquationBCs that overlap - # with the identity rows from DirichletBCs. with self._ybc.dat.vec_wo as v: Y.copy(v) - with self._xstar.dat.vec_ro as xs: - v.axpy(1.0, xs) - for bc in self.col_bcs: - bc.set(self._xstar, self._ybc) + for bc in self.col_bcs: + bc.set(self._xstar, self._ybc) + else: + for bc in self.col_bcs: + bc.zero(self._xstar) with self._xstar.dat.vec_ro as v: v.copy(X) diff --git a/firedrake/solving_utils.py b/firedrake/solving_utils.py index e9c453abee..bfd1eacb9d 100644 --- a/firedrake/solving_utils.py +++ b/firedrake/solving_utils.py @@ -290,6 +290,22 @@ def __init__(self, problem, self.F -= problem.compute_bc_lifting(self.J, self._bc_residual) + # Lift the residual of each EquationBC with its own Jacobian, because + # the EquationBC rows eliminate the same DirichletBC columns as the + # domain rows. + def lift(bc_F, bc_J): + if isinstance(bc_F, DirichletBC): + return bc_F + form = bc_F.f + if problem.is_linear: + form = replace(form, {self._x: zero(self._x.ufl_shape)}) + return bc_F.reconstruct( + form=form - problem.compute_bc_lifting(bc_J.f, self._bc_residual), + bcs=[lift(*pair) for pair in zip(bc_F.bcs, bc_J.bcs, strict=True)], + ) + + self.bcs_F = tuple(lift(*pair) for pair in zip(self.bcs_F, self.bcs_J, strict=True)) + self._assemble_objective = lambda *args, **kwargs: args if self.E: self._assemble_objective = get_assembler(self.E, diff --git a/tests/firedrake/regression/test_matrix_free.py b/tests/firedrake/regression/test_matrix_free.py index 639277980c..44d2754393 100644 --- a/tests/firedrake/regression/test_matrix_free.py +++ b/tests/firedrake/regression/test_matrix_free.py @@ -152,14 +152,27 @@ def assert_matfree_matches_aij(Mmf, Maij): @pytest.mark.parallel(nprocs=[1, 3]) -@pytest.mark.parametrize("case", ["component", "mixed", "mixed_equationbc"]) +@pytest.mark.parametrize("case", ["component", "mixed", "mixed_equationbc", + "equationbc_nested", "mixed_equationbc_nested"]) def test_matrixfree_action_transpose_blocks(case): # mult and multTranspose of the matrix-free operator, and of each # field block from createSubMatrix, must match the aij matrix with the # same bcs. The advection term makes the operator nonsymmetric. mesh = UnitSquareMesh(4, 4) b = Constant([1.0, 0.5]) - if case == "component": + if case == "equationbc_nested": + # Build an EquationBC on side 1 with DirichletBCs at the end points of + # side 1, as in linear_poisson_bbc in test_equation_bcs.py. + V = FunctionSpace(mesh, "CG", 2) + u = TrialFunction(V) + v = TestFunction(V) + a = inner(grad(u), grad(v)) * dx + inner(dot(grad(u), b), v) * dx + t = as_vector([0, 1]) + a1 = (-inner(dot(grad(u), t), dot(grad(v), t)) + inner(u, v)) * ds(1) + ebc = EquationBC(a1 == inner(Constant(0), v) * ds(1), Function(V), 1, + bcs=[DirichletBC(V, 0, ((1, 3), (1, 4)))]) + bcs = [ebc.extract_form("J")] + elif case == "component": V = VectorFunctionSpace(mesh, "CG", 2) u = TrialFunction(V) v = TestFunction(V) @@ -183,6 +196,14 @@ def test_matrixfree_action_transpose_blocks(case): ebc = EquationBC(inner(dot(grad(u), n) - p * n, v) * ds(2) == inner(Constant((0, 0)), v) * ds(2), Function(V), 2, V=V.sub(0)) bcs = [ebc.extract_form("J"), DirichletBC(V.sub(1), 0, 2), DirichletBC(V.sub(0), 0, 1)] + elif case == "mixed_equationbc_nested": + # The velocity EquationBC has a DirichletBC on one velocity + # component at the end points of side 2. The other component + # keeps the EquationBC rows at these nodes. + n = FacetNormal(mesh) + ebc = EquationBC(inner(dot(grad(u), n) - p * n, v) * ds(2) == inner(Constant((0, 0)), v) * ds(2), + Function(V), 2, V=V.sub(0), bcs=[DirichletBC(V.sub(0).sub(1), 0, ((2, 3), (2, 4)))]) + bcs = [ebc.extract_form("J"), DirichletBC(V.sub(0), 0, 1)] Mmf = assemble(a, bcs=bcs, mat_type="matfree").petscmat Maij = assemble(a, bcs=bcs, mat_type="aij").petscmat