Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions firedrake/slate/slac/optimise.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""
Expand Down
10 changes: 7 additions & 3 deletions firedrake/slate/slac/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
43 changes: 34 additions & 9 deletions firedrake/slate/slate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)

Expand All @@ -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):
Expand Down
24 changes: 24 additions & 0 deletions tests/firedrake/slate/test_assemble_tensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading