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
4 changes: 2 additions & 2 deletions finat/finiteelementbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,8 @@ def _stack_tabulations(self, order, ps, entity=None, coordinate_mapping=None):
multiindex = tuple(chain(self.get_indices(), self.get_value_indices()))

def concatenate(alpha):
# The point indices are free in each table, so promote them to a
# shape before concatenating the tables along it.
# The point indices of each table are free indices.
# Promote them to a shape that Concatenate can join.
pieces = [broadcast_tensor(gem.Indexed(table[alpha], multiindex),
sub.indices)
for table, sub in zip(tables, ps.point_sets)]
Expand Down
23 changes: 14 additions & 9 deletions finat/point_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import numpy

from FIAT.precision import calibrate_tolerance

import gem
from gem.utils import safe_repr

Expand Down Expand Up @@ -47,6 +49,14 @@ def expression(self):
"""GEM expression describing the points, with free indices
``self.indices`` and shape (point dimension,)."""

def almost_equal(self, other, tolerance=None):
"""Approximate numerical equality of point sets."""
if type(self) is not type(other) or self.points.shape != other.points.shape:
return False
if tolerance is None:
tolerance = calibrate_tolerance(1e-12, self.points.dtype)
return numpy.allclose(self.points, other.points, rtol=0, atol=tolerance)

@cached_property
def point_sets(self):
"""The point sets this point set is a union of.
Expand Down Expand Up @@ -172,12 +182,6 @@ def indices(self):
def expression(self):
return gem.partial_indexed(gem.Literal(self.points), self.indices)

def almost_equal(self, other, tolerance=1e-12):
"""Approximate numerical equality of point sets"""
return type(self) is type(other) and \
self.points.shape == other.points.shape and \
numpy.allclose(self.points, other.points, rtol=0, atol=tolerance)


class GaussLegendrePointSet(PointSet):
"""Gauss-Legendre quadrature points on the interval.
Expand Down Expand Up @@ -234,7 +238,7 @@ def expression(self):
result.append(gem.Indexed(point_set.expression, (i,)))
return gem.ListTensor(result)

def almost_equal(self, other, tolerance=1e-12):
def almost_equal(self, other, tolerance=None):
"""Approximate numerical equality of point sets"""
return type(self) is type(other) and \
len(self.factors) == len(other.factors) and \
Expand Down Expand Up @@ -309,9 +313,10 @@ def indices(self):

@cached_property
def expression(self):
raise NotImplementedError("Symbolic point expression is not yet implemented for FacetPointSet.")
shape = tuple(i.extent for i in self.indices) + (self.dimension,)
return gem.partial_indexed(gem.Literal(self.points.reshape(shape)), self.indices)

def almost_equal(self, other, tolerance=1e-12):
def almost_equal(self, other, tolerance=None):
"""Approximate numerical equality of point sets"""
return type(self) is type(other) and \
self.cell == other.cell and \
Expand Down
12 changes: 9 additions & 3 deletions finat/quadrature.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
from gem.utils import safe_repr

from finat.point_set import (GaussLegendrePointSet, GaussLobattoLegendrePointSet,
KMVPointSet, PointSet, TensorPointSet)
KMVPointSet, PointSet, PointSingleton,
TensorPointSet)


def make_quadrature(ref_el, degree, scheme="default"):
Expand Down Expand Up @@ -64,7 +65,10 @@ def make_quadrature(ref_el, degree, scheme="default"):
point_set = GaussLegendrePointSet(fiat_rule.get_points())
else:
fiat_rule = fiat_scheme(ref_el, degree, scheme)
point_set = PointSet(fiat_rule.get_points())
if ref_el.get_spatial_dimension() == 0:
point_set = PointSingleton(fiat_rule.get_points()[0])
else:
point_set = PointSet(fiat_rule.get_points())

return QuadratureRule(point_set, fiat_rule.get_weights(), ref_el=ref_el, io_ornt_map_tuple=fiat_rule._intrinsic_orientation_permutation_map_tuple)

Expand Down Expand Up @@ -151,7 +155,9 @@ def point_set(self):

@cached_property
def weight_expression(self):
return gem.Indexed(gem.Literal(self.weights), self.point_set.indices)
indices = self.point_set.indices
shape = tuple(i.extent for i in indices)
return gem.Indexed(gem.Literal(self.weights.reshape(shape)), indices)


class TensorProductQuadratureRule(AbstractQuadratureRule):
Expand Down
10 changes: 4 additions & 6 deletions finat/quadrature_element.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from finat.point_set import UnknownPointSet, FacetPointSet

import numpy

import FIAT
Expand All @@ -9,6 +7,7 @@
from gem.utils import cached_property

from finat.finiteelementbase import FiniteElementBase
from finat.point_set import FacetPointSet, UnionPointSet, UnknownPointSet
from finat.quadrature import make_quadrature, AbstractQuadratureRule, QuadratureRule


Expand Down Expand Up @@ -204,15 +203,14 @@ def _summand_rules(self):

:returns: one :class:`~finat.quadrature.QuadratureRule` for each
point set of a :class:`~finat.point_set.UnionPointSet` rule, in
the order they are stacked, or an empty tuple if the rule has a
single point set.
the order they are stacked, or an empty tuple for other rules.

A union of point sets is how the points of a direct sum are stacked,
so splitting it back up recovers a rule for each summand, each on
the points its own functionals evaluate on.
"""
rule_ps = self._rule.point_set
if len(rule_ps.point_sets) == 1:
rule_ps = self._point_set
if not isinstance(rule_ps, UnionPointSet):
return ()

rules = []
Expand Down
30 changes: 28 additions & 2 deletions finat/tensor_product.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@

import FIAT
from FIAT.polynomial_set import mis
from FIAT.reference_element import TensorProductCell
from FIAT.reference_element import Hypercube, TensorProductCell
from FIAT.orientation_utils import make_entity_permutations_tensorproduct

import gem
from gem.utils import cached_property

from finat.finiteelementbase import FiniteElementBase
from finat.point_set import PointSingleton, PointSet, TensorPointSet
from finat.point_set import FacetPointSet, PointSingleton, PointSet, TensorPointSet


class TensorProductElement(FiniteElementBase):
Expand Down Expand Up @@ -139,6 +139,19 @@ def basis_evaluation(self, order, ps, entity=None, coordinate_mapping=None):
# factorised.
return self._stack_tabulations(order, ps, entity,
coordinate_mapping=coordinate_mapping)
if isinstance(ps, FacetPointSet):
# Tabulate on each facet and select the table with the facet index.
# Each table remains a product of normal and tangential factors.
# Coefficient evaluation contracts these factors one at a time.
facets = ps.entities
if isinstance(ps.cell, Hypercube):
facets = [ps.cell.unflattening_map[facet] for facet in facets]
tables = [self.basis_evaluation(order, ps.ps, facet) for facet in facets]
f = ps.indices[0]
indices = (*self.get_indices(), *self.get_value_indices())
return {alpha: gem.ComponentTensor(
gem.ListTensor([table[alpha][indices] for table in tables])[f], indices)
for alpha in tables[0]}

entities = self._factor_entity(entity)
entity_dim, _ = zip(*entities)
Expand Down Expand Up @@ -323,6 +336,16 @@ def factor_point_set(product_cell, product_dim, point_set):
for ps, dim in zip(point_set.factors, point_dims))
return point_set.factors

# A vertex holds a single point.
vertex = PointSingleton(numpy.zeros((0,)))
if isinstance(point_set, TensorPointSet) and \
len(point_set.factors) == sum(dim > 0 for dim in point_dims):
# Give the factors to the subelements not on a vertex.
factors = iter(point_set.factors)
result = [next(factors) if dim else vertex for dim in point_dims]
assert all(ps.dimension == dim for ps, dim in zip(result, point_dims))
return result

# Split the point coordinates along the point dimensions
# required by the subelements.
assert point_set.dimension == sum(point_dims)
Expand All @@ -333,6 +356,9 @@ def factor_point_set(product_cell, product_dim, point_set):
# Use the same point index for the new point sets.
result = []
for s in slices:
if s.start == s.stop:
result.append(vertex)
continue
ps = PointSet(point_set.points[:, s])
ps.indices = point_set.indices
result.append(ps)
Expand Down
6 changes: 5 additions & 1 deletion gem/flop_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,11 @@ def flops_zero(expr, temporaries):
@flops.register(gem.LogicalAnd)
@flops.register(gem.LogicalOr)
@flops.register(gem.ListTensor)
@flops.register(gem.FloorDiv)
@flops.register(gem.Remainder)
def flops_zeroplus(expr, temporaries):
# These nodes contribute 0 floating point operations, but their children may not.
# FloorDiv and Remainder are integer arithmetic on indices.
return 0 + sum(expression_flops(child, temporaries)
for child in expr.children)

Expand Down Expand Up @@ -168,7 +171,8 @@ def flops_solve(expr, temporaries):

@flops.register(gem.ComponentTensor)
def flops_componenttensor(expr, temporaries):
raise ValueError("Not expecting ComponentTensor")
child, = expr.children
return numpy.prod(expr.shape, dtype=int) * expression_flops(child, temporaries)


def expression_flops(expression, temporaries, top=False):
Expand Down
7 changes: 3 additions & 4 deletions gem/gem.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def __getitem__(self, indices):
return Indexed(self, indices)

def __neg__(self):
return componentwise(Product, minus, self)
return componentwise(Product, as_gem(-1, dtype=self.dtype), self)

def __add__(self, other):
return componentwise(Sum, self, as_gem(other, dtype=self.dtype))
Expand Down Expand Up @@ -309,12 +309,12 @@ def __init__(self, array, dtype=None):
def is_equal(self, other):
if type(self) is not type(other):
return False
if self.shape != other.shape:
if self.shape != other.shape or self.dtype != other.dtype:
return False
return numpy.array_equal(self.array, other.array)

def get_hash(self):
return hash((type(self), self.shape, tuple(self.array.flat)))
return hash((type(self), self.shape, self.dtype, tuple(self.array.flat)))

@property
def value(self):
Expand Down Expand Up @@ -1287,7 +1287,6 @@ def view(expression, *slices):

# Static one object for quicker constant folding
one = Literal(1)
minus = Literal(-1, dtype=int)


# Syntax sugar
Expand Down
2 changes: 1 addition & 1 deletion gem/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def _evaluate_indexed(e, self):
idx.append(slice(None))
elif isinstance(i, gem.VariableIndex):
# Variable index, evaluate inner expression
result, = self(i.expression)
result = self(i.expression)
assert not result.tshape
idx.append(result[()])
else:
Expand Down
21 changes: 20 additions & 1 deletion gem/optimise.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,12 @@ def _select_expression_uncached(expressions, index, cache):

types = set(map(type, expressions))
if types <= {Indexed, Zero}:
multiindex, = set(e.multiindex for e in expressions if isinstance(e, Indexed))
multiindices = set(e.multiindex for e in expressions if isinstance(e, Indexed))
if len(multiindices) > 1:
# Each expression is indexed by a different multiindex.
# Select the indexed expressions, not the tensors they index.
return Indexed(ListTensor(expressions), (index,))
multiindex, = multiindices
# Shape only determined by free indices
shape = tuple(i.extent for i in multiindex if isinstance(i, Index))

Expand Down Expand Up @@ -340,6 +345,20 @@ def substitute(expression, from_, to_):
else:
return Indexed(ComponentTensor(expression, (from_,)), (to_,))

# Replace each literal vector that has a single unit entry k and is
# indexed by a summation index i with the equivalent Delta(i, k).
# The loop below then eliminates i.
factors = list(factors)
for k, factor in enumerate(factors):
if not isinstance(factor, Indexed) or len(factor.multiindex) != 1:
continue
index, = factor.multiindex
table, = factor.children
if index in sum_indices and isinstance(table, Literal):
entries = numpy.flatnonzero(table.array)
if len(entries) == 1 and table.array[entries[0]] == 1:
factors[k] = Delta(index, int(entries[0]), dtype=factor.dtype)

delta_queue = [(f, index)
for f in factors if isinstance(f, Delta)
for index in (f.i, f.j) if index in sum_indices]
Expand Down
11 changes: 9 additions & 2 deletions gem/refactorise.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from sys import intern

from gem.node import Memoizer, MemoizerArg, traversal
from gem.gem import (Node, Conditional, IndexSum, Zero, Product, Sum,
from gem.gem import (Node, Conditional, Delta, IndexSum, Zero, Product, Sum,
Indexed, ListTensor, one, MathFunction)
from gem.optimise import (delta_elimination, filtered_replace_indices,
remove_componenttensors, sum_factorise,
Expand Down Expand Up @@ -266,7 +266,14 @@ def _collect_monomials_mathfunction(expression, self):
child_ms, = map(self, expression.children)
result = MonomialSum()
for k, v in child_ms.monomials.items():
result.monomials[k] = MathFunction(name, v)
# Move the Delta factors outside the math function.
# A Delta is real, so conj, real and imag do not change it.
# Outside the math function, delta elimination can remove it.
_, factors = traverse_product(v, stop_at=lambda e: not isinstance(e, Product))
deltas = [f for f in factors if isinstance(f, Delta)]
if deltas:
v = Product(*(f for f in factors if not isinstance(f, Delta)))
result.monomials[k] = Product(*deltas, MathFunction(name, v))
result.ordering = child_ms.ordering.copy()
return result
else:
Expand Down
8 changes: 5 additions & 3 deletions test/finat/test_dual_basis.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,17 +112,19 @@ def test_mixed_enriched_element_dual_evaluation():
check_nodal(mixed)


@pytest.mark.parametrize("repeated", (False, True))
def test_quadrature_element_on_union_of_points(repeated: bool):
@pytest.mark.parametrize("layout", ("distinct", "repeated", "single"))
def test_quadrature_element_on_union_of_points(layout: str):
# Firedrake interpolates through a quadrature space on the points of the
# target's dual basis, which for a direct sum is a union. That element
# has to evaluate on each point set of the union, just as the sum does.
cell = ufc_simplex(2)
enriched = restricted_lagrange_sum(cell)

_, ps = enriched.dual_basis
if repeated:
if layout == "repeated":
ps = UnionPointSet([ps, PointSet(ps.point_sets[0].points.copy())])
elif layout == "single":
ps = UnionPointSet(ps.point_sets[:1])
# The weights are not used, this quadrature scheme is not for integration.
rule = QuadratureRule(ps, numpy.full(len(ps.points), numpy.nan), ref_el=cell)
element = QuadratureElement(cell, rule)
Expand Down
Loading
Loading