diff --git a/firedrake/slate/slac/optimise.py b/firedrake/slate/slac/optimise.py index f21188b548..f0a034c0a7 100644 --- a/firedrake/slate/slac/optimise.py +++ b/firedrake/slate/slac/optimise.py @@ -86,6 +86,8 @@ def _push_diag_scalar_mul(expr, self, diag): @_push_diag.register(Solve) @_push_diag.register(Mul) @_push_diag.register(Tensor) +@_push_diag.register(AssembledVector) +@_push_diag.register(Reciprocal) def _push_diag_stop(expr, self, diag): """Diagonal Tensors cannot be pushed further into this set of nodes.""" expr = type(expr)(*map(self, expr.children, repeat(False))) if not expr.terminal else expr @@ -99,16 +101,6 @@ def _push_diag_block(expr, self, diag): return DiagonalTensor(expr) if diag else expr -@_push_diag.register(AssembledVector) -@_push_diag.register(Reciprocal) -def _push_diag_vectors(expr, self, diag): - """DiagonalTensors should not be pushed onto rank-1 tensors.""" - if diag: - raise AssertionError("It is not legal to define DiagonalTensors on rank-1 tensors.") - else: - return expr - - @_push_diag.register(DiagonalTensor) def _push_diag_diag(expr, self, diag): """DiagonalTensors are either pushed down or ignored when wrapped into another DiagonalTensor.""" diff --git a/firedrake/slate/slac/utils.py b/firedrake/slate/slac/utils.py index e66988f8e3..e7c0bdae29 100644 --- a/firedrake/slate/slac/utils.py +++ b/firedrake/slate/slac/utils.py @@ -70,9 +70,13 @@ def _slate2gem_block(expr, self): def _slate2gem_diagonal(expr, self): if not self.matfree: A, = map(self, expr.children) - assert A.shape[0] == A.shape[1] - i, j = (Index(extent=s) for s in A.shape) - return ComponentTensor(Product(Indexed(A, (i, i)), Delta(i, j)), (i, j)) + i, j = (Index(extent=s) for s in expr.shape) + # A rank-1 child holds the entries of the diagonal matrix, and a rank-2 child holds them on its diagonal + if len(A.shape) == 1: + a_ii = Indexed(A, (i,)) + else: + a_ii = Indexed(A, (i, i)) + return ComponentTensor(Product(a_ii, Delta(i, j)), (i, j)) else: raise NotImplementedError("Diagonals on Slate expressions are \ not implemented in a matrix-free manner yet.") diff --git a/firedrake/slate/slate.py b/firedrake/slate/slate.py index 835023dcb8..47085b5fea 100644 --- a/firedrake/slate/slate.py +++ b/firedrake/slate/slate.py @@ -1539,11 +1539,33 @@ def arguments(self): class DiagonalTensor(UnaryOp): - """An abstract Slate class representing the diagonal of a tensor. + """An abstract Slate class representing a diagonal matrix. - .. warning:: + As with :func:`numpy.diag`, the operand can be a matrix or a vector. + For a square rank-2 tensor, this is the matrix that keeps only the + diagonal entries of the operand. For a rank-1 tensor that is defined on + the function space ``V``, this is the matrix from ``V`` to the dual of + ``V`` that has the entries of the operand on its diagonal. For example, if + ``m`` is a :class:`~.Cofunction` that holds the row sums of a mass matrix, + then ``DiagonalTensor(AssembledVector(m))`` is the lumped mass matrix. - This class will raise an error if the tensor is not square. + .. note:: + + A bare assembly of a DiagonalTensor built from an + :class:`AssembledVector` follows the same rule as + :class:`AssembledVector`: each cell gets the global values of the + vector. Thus use it in a product with a tensor that is assembled cell + by cell, for example ``DiagonalTensor(AssembledVector(m)).inv * Tensor(a)``. + + Parameters + ---------- + A : TensorBase + A square rank-2 tensor or a rank-1 tensor. + + Raises + ------ + ValueError + If ``A`` is not a square rank-2 tensor or a rank-1 tensor. """ diagonal = True @@ -1554,10 +1576,11 @@ def __new__(cls, A): def __init__(self, A): """Constructor for the Diagonal class.""" - assert A.rank == 2, "The tensor must be rank 2." - assert A.shape[0] == A.shape[1], ( - "The diagonal can only be computed on square tensors." - ) + if A.rank == 2: + if A.shape[0] != A.shape[1]: + raise ValueError(f"Expecting a square matrix, not a matrix with shape {A.shape}.") + elif A.rank != 1: + raise ValueError(f"Expecting a tensor of rank 1 or 2, not of rank {A.rank}.") super(DiagonalTensor, self).__init__(A) @@ -1566,12 +1589,14 @@ def arg_function_spaces(self): """Returns a tuple of function spaces that the tensor is defined on. """ - tensor, = self.operands - return tuple(arg.function_space() for arg in tensor.arguments()) + return tuple(arg.function_space() for arg in self.arguments()) def arguments(self): """Returns a tuple of arguments associated with the tensor.""" tensor, = self.operands + if tensor.rank == 1: + arg, = tensor.arguments() + return (arg, arg.reconstruct(number=arg.number()+1)) return tensor.arguments() def _output_string(self, prec=None): diff --git a/tests/firedrake/slate/test_assemble_tensors.py b/tests/firedrake/slate/test_assemble_tensors.py index 245bd11e2d..4f5b057f40 100644 --- a/tests/firedrake/slate/test_assemble_tensors.py +++ b/tests/firedrake/slate/test_assemble_tensors.py @@ -336,6 +336,30 @@ def test_diagonal(mass, matrix_mixed_nofacet): assert np.allclose(ref3, np.diag(res3), rtol=1e-14) +@pytest.mark.parametrize("make_operator, make_diagonal", [ + pytest.param(lambda D: D, lambda m: m, id="diagonal"), + pytest.param(lambda D: D.inv, lambda m: 1/m, id="inverse"), +]) +def test_diagonal_tensor_from_assembled_vector_times_tensor(make_operator, make_diagonal): + base = UnitSquareMesh(1, 1, quadrilateral=True) + mesh = ExtrudedMesh(base, 2) + V = FunctionSpace(mesh, "DQ", 0, vfamily="CG", vdegree=1) + Q = FunctionSpace(mesh, "DQ", 0, vfamily="DG", vdegree=0) + u = TrialFunction(V) + v = TestFunction(V) + q = TrialFunction(Q) + one = Function(V).assign(1) + # The row sums of the mass matrix, which differ at the dofs shared by two cells + m = assemble(action(inner(u, v)*dx, one)) + P_form = inner(q, v)*dx + + D = DiagonalTensor(AssembledVector(m)) + res = assemble(make_operator(D) * Tensor(P_form)).M.values + P = assemble(P_form).M.values + ref = np.diag(make_diagonal(m.dat.data_ro)) @ P + assert np.allclose(res, ref, rtol=1e-14) + + def test_reciprocal(mesh): function_space = FunctionSpace(mesh, "DG", 0) # test reciprocal of vector built from diagonal