From 7afe4761aa6622738722b08c50e8db212548301b Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Wed, 29 Jul 2026 09:16:28 +0100 Subject: [PATCH 01/12] Split dual basis Concatenate before contracting with the dual coefficient compile_expression_dual_evaluation contracts the dual evaluation against the dual coefficient with an IndexSum over the basis indices when the dual argument is a Cofunction. When the target element has a block-structured dual basis (e.g. a RestrictedElement, whose dual evaluation is a gem.Concatenate), this hid the concatenation index from the subsequent unconcatenate() call, which can only split along indices that are still free in the assignment. Resolve the concatenation of the dual basis before the basis indices are summed over, following the same pattern already used for coefficient evaluation in tsfc.fem. This makes matrix-free adjoint interpolation (MatMultTranspose of a two-form Interpolate) work for restricted elements. Co-Authored-By: Claude Opus 5 --- tsfc/driver.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/tsfc/driver.py b/tsfc/driver.py index 6ee929eced..04f880890f 100644 --- a/tsfc/driver.py +++ b/tsfc/driver.py @@ -347,12 +347,25 @@ def compile_expression_dual_evaluation(expression, ufl_element, *, coordinate_mapping = None evaluation, basis_indices = to_element.dual_evaluation(fn, coordinate_mapping) + # Index splitting cache, shared by every unconcatenate() call below so + # that a Concatenate index is always split the same way. + concatenate_cache = {} + # Compute the action against the dual argument if isinstance(dual_arg, ufl.Cofunction): gem_dual = builder.coefficient_map[dual_arg] if complex_mode: evaluation = gem.MathFunction('conj', evaluation) - evaluation = gem.IndexSum(evaluation * gem_dual[basis_indices], basis_indices) + # The basis indices are about to be contracted away, so any + # Concatenate node expressing the block structure of the dual basis + # must be split now: unconcatenate() can only split along indices + # that are still free in the assignment. This is the same pattern + # as coefficient evaluation in tsfc.fem. + dual_expr, = gem.optimise.remove_componenttensors([gem_dual[basis_indices]]) + summands = [gem.IndexSum(gem.Product(expr, var), var.index_ordering()) + for var, expr in unconcatenate([(dual_expr, evaluation)], + cache=concatenate_cache)] + evaluation = gem.optimise.make_sum(summands) basis_indices = () else: argument_multiindices[dual_arg.number()] = basis_indices @@ -376,7 +389,7 @@ def predicate(index): # TODO: one should apply some GEM optimisations as in assembly, # but we don't for now. evaluation, = impero_utils.preprocess_gem([evaluation]) - pairs = unconcatenate([(return_expr, evaluation)]) + pairs = unconcatenate([(return_expr, evaluation)], cache=concatenate_cache) impero_c = impero_utils.compile_gem(pairs, return_indices) index_names = {idx: f"p{i}" for (i, idx) in enumerate(basis_indices)} # Handle kernel interface requirements From 6072eeedef39646897315b28c395d8d1eeb16b43 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Wed, 29 Jul 2026 11:25:24 +0100 Subject: [PATCH 02/12] DROP BEFORE MERGE: build against firedrakeproject/fiat#268 EnrichedElement has no dual basis without it, so interpolating into the facet space of a hexahedron raises NotImplementedError, and gem cannot unconcatenate a dual basis whose blocks have already been contracted with a Cofunction. Co-Authored-By: Claude Opus 5 --- .github/actions/install/action.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/actions/install/action.yml b/.github/actions/install/action.yml index 54c1411d7f..11f3fc754a 100644 --- a/.github/actions/install/action.yml +++ b/.github/actions/install/action.yml @@ -163,6 +163,14 @@ runs: firedrake-clean pip list + - name: "DROP BEFORE MERGE: install FIAT from firedrakeproject/fiat#268" + shell: bash + run: | + . venv/bin/activate + pip install --verbose --no-build-isolation --no-deps --force-reinstall \ + git+https://github.com/firedrakeproject/fiat.git@pbrubeck/fix/dual-enriched + pip list | grep -i fiat + - name: Run firedrake-check shell: bash run: | From 7a92a6e0fdd674ea881b26c9486eacf309b605e3 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Wed, 29 Jul 2026 14:04:12 +0100 Subject: [PATCH 03/12] tsfc: contract each block after unconcatenating compile_expression_dual_evaluation carried a TODO to apply the GEM optimisations that assembly applies. Apply one of them: contract each assignment once unconcatenate has split the Concatenate nodes. This matters for H(div) and H(curl). Those elements are a sum of blocks, each mapping into one vector component, and with firedrakeproject/fiat#270 each block selects its component with a Delta. Before unconcatenation the blocks are branches of a Concatenate, so the Deltas never meet; afterwards each pair of blocks is its own assignment, the Deltas multiply, and delta elimination cancels every pair mapping to different components. Coarse to fine interpolation, kernel temporaries and wall clock: NCF 1->4 832K -> 68K 3.07x faster NCE 1->4 307K -> 110K 2.23x faster NCE 1->3 131K -> 61K 2.23x faster Form assembly does not go through this function and is unchanged. Co-Authored-By: Claude Opus 5 --- tsfc/driver.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tsfc/driver.py b/tsfc/driver.py index 04f880890f..aaceacb077 100644 --- a/tsfc/driver.py +++ b/tsfc/driver.py @@ -390,6 +390,12 @@ def predicate(index): # but we don't for now. evaluation, = impero_utils.preprocess_gem([evaluation]) pairs = unconcatenate([(return_expr, evaluation)], cache=concatenate_cache) + # Contract each block once the Concatenate nodes are gone. An H(div) or + # H(curl) element selects the component each block maps to with a Delta, + # and only here, with the blocks separated, do those Deltas meet pairwise + # and cancel the pairs that map to different components. + pairs = [(variable, gem.optimise.contraction(expression)) + for variable, expression in pairs] impero_c = impero_utils.compile_gem(pairs, return_indices) index_names = {idx: f"p{i}" for (i, idx) in enumerate(basis_indices)} # Handle kernel interface requirements From c6f5cc351d73a7e623aca11e1cba5d90c54e72af Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Tue, 4 Aug 2026 14:41:11 +0100 Subject: [PATCH 04/12] tsfc: propagate zeros through dual evaluation Apply to dual evaluation the zero handling assembly already does. Fold zero-valued Literals into symbolic Zero before anything else, so the algebraic identities built into gem (Product(_, Zero) -> Zero, and so on) can propagate them and the later steps can prune what they reach. Then drop any pair whose expression has collapsed to Zero once the blocks are contracted: a cross-component block that a Delta has just cancelled is a real zero contribution rather than one merely absent from the sum, and it must not reach codegen as a temporary. Emit a Zero temporary as a zero-filled read-only array when one does reach loopy, as gem.Zero carries no .array for the Constant branch to use. --- tsfc/driver.py | 13 ++++++++++--- tsfc/loopy.py | 5 ++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/tsfc/driver.py b/tsfc/driver.py index aaceacb077..37ba2f0241 100644 --- a/tsfc/driver.py +++ b/tsfc/driver.py @@ -14,6 +14,7 @@ import gem import gem.impero_utils as impero_utils +from gem.optimise import constant_fold_zero from gem.unconcatenate import unconcatenate import finat @@ -346,6 +347,10 @@ def compile_expression_dual_evaluation(expression, ufl_element, *, else: coordinate_mapping = None evaluation, basis_indices = to_element.dual_evaluation(fn, coordinate_mapping) + # As in assembly, fold zero-valued Literals into symbolic Zero first, so + # that the algebraic identities built into gem (Product(_, Zero) -> Zero, + # etc.) can propagate them and later steps can prune them. + evaluation, = constant_fold_zero([evaluation]) # Index splitting cache, shared by every unconcatenate() call below so # that a Concatenate index is always split the same way. @@ -386,8 +391,6 @@ def predicate(index): return_expr = gem.Indexed(gem.reshape(return_var, return_shape), return_indices) return_expr, = gem.optimise.remove_componenttensors([return_expr]) - # TODO: one should apply some GEM optimisations as in assembly, - # but we don't for now. evaluation, = impero_utils.preprocess_gem([evaluation]) pairs = unconcatenate([(return_expr, evaluation)], cache=concatenate_cache) # Contract each block once the Concatenate nodes are gone. An H(div) or @@ -396,7 +399,11 @@ def predicate(index): # and cancel the pairs that map to different components. pairs = [(variable, gem.optimise.contraction(expression)) for variable, expression in pairs] - impero_c = impero_utils.compile_gem(pairs, return_indices) + # As in assembly, drop any pair whose expression collapsed to Zero: a + # cross-component block that a Delta has just cancelled above is a real + # zero contribution, not merely absent from the sum, and it must not + # reach codegen as a temporary. + impero_c = impero_utils.compile_gem(pairs, return_indices, remove_zeros=True) index_names = {idx: f"p{i}" for (i, idx) in enumerate(basis_indices)} # Handle kernel interface requirements builder.register_requirements([evaluation]) diff --git a/tsfc/loopy.py b/tsfc/loopy.py index d4a31a36cb..459d2d243e 100644 --- a/tsfc/loopy.py +++ b/tsfc/loopy.py @@ -236,7 +236,10 @@ def generate(impero_c, args, scalar_type, kernel_name="loopy_kernel", index_name data = list(args) for i, (temp, dtype) in enumerate(assign_dtypes(impero_c.temporaries, scalar_type)): name = "t%d" % i - if isinstance(temp, gem.Constant): + if isinstance(temp, gem.Zero): + initializer = numpy.zeros(temp.shape, dtype=dtype) + data.append(lp.TemporaryVariable(name, shape=temp.shape, dtype=dtype, initializer=initializer, address_space=lp.AddressSpace.LOCAL, read_only=True)) + elif isinstance(temp, gem.Constant): data.append(lp.TemporaryVariable(name, shape=temp.shape, dtype=dtype, initializer=temp.array, address_space=lp.AddressSpace.LOCAL, read_only=True)) else: shape = tuple([i.extent for i in ctx.indices[temp]]) + temp.shape From 906dce536bf468b47a8b7f937e6d99eab7a5d2e8 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Tue, 4 Aug 2026 14:59:55 +0100 Subject: [PATCH 05/12] Test Boundary Quadrature on quadrilaterals Run the quadrature element tests on a quadrilateral mesh as well as a triangular one, and check that interpolation into a facet quadrature space reproduces the expression at the points and gives both cells sharing a facet the same values there. Scalar, vector and tensor valued spaces each take a different path through dual evaluation, so cover all three. Co-Authored-By: Claude Opus 5 --- tests/firedrake/regression/test_quadrature.py | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/tests/firedrake/regression/test_quadrature.py b/tests/firedrake/regression/test_quadrature.py index 225a4b244d..ed416e5c1c 100644 --- a/tests/firedrake/regression/test_quadrature.py +++ b/tests/firedrake/regression/test_quadrature.py @@ -3,9 +3,9 @@ import numpy as np -@pytest.fixture +@pytest.fixture(params=[False, True], ids=["triangle", "quadrilateral"]) def mesh(request): - return UnitSquareMesh(5, 5) + return UnitSquareMesh(5, 5, quadrilateral=request.param) def test_hand_specified_quadrature(mesh): @@ -52,3 +52,24 @@ def test_quadrature_element(mesh, family, mat_type, diagonal): a = inner(u, v) * dx assemble(a, mat_type=mat_type, diagonal=diagonal) + + +@pytest.mark.parametrize("space", [FunctionSpace, VectorFunctionSpace, TensorFunctionSpace]) +def test_boundary_quadrature_interpolation(mesh, space): + V = space(mesh, "Boundary Quadrature", 2) + x = SpatialCoordinate(mesh) + if V.value_shape == (): + expr = x[0]**2 + x[1] + elif len(V.value_shape) == 1: + expr = as_vector([x[0]**2, x[1]]) + else: + expr = as_tensor([[x[0]**2, x[1]], [x[0]*x[1], 1 + x[0]]]) + + f = Function(V).interpolate(expr) + + # The functionals are point evaluations, so interpolation is exact there + assert np.isclose(assemble(inner(f - expr, f - expr) * ds), 0) + assert np.isclose(assemble(inner(f('+') - expr('+'), f('+') - expr('+')) * dS), 0) + # The degrees of freedom on a facet are shared, so the cells on either + # side of one see the same values + assert np.isclose(assemble(inner(f('+') - f('-'), f('+') - f('-')) * dS), 0) From 55646a2451e0b02a5b34139c8e5108868685bf51 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Tue, 4 Aug 2026 15:00:48 +0100 Subject: [PATCH 06/12] DROP BEFORE MERGE: build against firedrakeproject/fiat#274 Point the existing FIAT install step at pbrubeck/tensor-facet-quadrature, which is pbrubeck/fix/dual-enriched plus the facet quadrature work. A Boundary Quadrature space on a quadrilateral cannot be interpolated into without it: the dual basis names the points of every facet at once, and a TensorProductElement cannot tabulate on those. Co-Authored-By: Claude Opus 5 --- .github/actions/install/action.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/actions/install/action.yml b/.github/actions/install/action.yml index 11f3fc754a..bf969297c3 100644 --- a/.github/actions/install/action.yml +++ b/.github/actions/install/action.yml @@ -163,12 +163,12 @@ runs: firedrake-clean pip list - - name: "DROP BEFORE MERGE: install FIAT from firedrakeproject/fiat#268" + - name: "DROP BEFORE MERGE: install FIAT from firedrakeproject/fiat#274" shell: bash run: | . venv/bin/activate pip install --verbose --no-build-isolation --no-deps --force-reinstall \ - git+https://github.com/firedrakeproject/fiat.git@pbrubeck/fix/dual-enriched + git+https://github.com/firedrakeproject/fiat.git@pbrubeck/tensor-facet-quadrature pip list | grep -i fiat - name: Run firedrake-check From a3f7f15db21b8e0a5723bcd9facbd67629e57bfb Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Tue, 4 Aug 2026 15:15:38 +0100 Subject: [PATCH 07/12] Apply suggestions from code review Co-authored-by: Pablo Brubeck --- tests/firedrake/regression/test_quadrature.py | 3 --- tsfc/driver.py | 7 ------- 2 files changed, 10 deletions(-) diff --git a/tests/firedrake/regression/test_quadrature.py b/tests/firedrake/regression/test_quadrature.py index ed416e5c1c..a63b1b171c 100644 --- a/tests/firedrake/regression/test_quadrature.py +++ b/tests/firedrake/regression/test_quadrature.py @@ -70,6 +70,3 @@ def test_boundary_quadrature_interpolation(mesh, space): # The functionals are point evaluations, so interpolation is exact there assert np.isclose(assemble(inner(f - expr, f - expr) * ds), 0) assert np.isclose(assemble(inner(f('+') - expr('+'), f('+') - expr('+')) * dS), 0) - # The degrees of freedom on a facet are shared, so the cells on either - # side of one see the same values - assert np.isclose(assemble(inner(f('+') - f('-'), f('+') - f('-')) * dS), 0) diff --git a/tsfc/driver.py b/tsfc/driver.py index 37ba2f0241..cb7ca671b1 100644 --- a/tsfc/driver.py +++ b/tsfc/driver.py @@ -347,9 +347,6 @@ def compile_expression_dual_evaluation(expression, ufl_element, *, else: coordinate_mapping = None evaluation, basis_indices = to_element.dual_evaluation(fn, coordinate_mapping) - # As in assembly, fold zero-valued Literals into symbolic Zero first, so - # that the algebraic identities built into gem (Product(_, Zero) -> Zero, - # etc.) can propagate them and later steps can prune them. evaluation, = constant_fold_zero([evaluation]) # Index splitting cache, shared by every unconcatenate() call below so @@ -399,10 +396,6 @@ def predicate(index): # and cancel the pairs that map to different components. pairs = [(variable, gem.optimise.contraction(expression)) for variable, expression in pairs] - # As in assembly, drop any pair whose expression collapsed to Zero: a - # cross-component block that a Delta has just cancelled above is a real - # zero contribution, not merely absent from the sum, and it must not - # reach codegen as a temporary. impero_c = impero_utils.compile_gem(pairs, return_indices, remove_zeros=True) index_names = {idx: f"p{i}" for (i, idx) in enumerate(basis_indices)} # Handle kernel interface requirements From b4efefea24d14912a525a4a6b16234333e838655 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Tue, 4 Aug 2026 15:16:32 +0100 Subject: [PATCH 08/12] Apply suggestion from @pbrubeck --- tsfc/loopy.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tsfc/loopy.py b/tsfc/loopy.py index 459d2d243e..d4a31a36cb 100644 --- a/tsfc/loopy.py +++ b/tsfc/loopy.py @@ -236,10 +236,7 @@ def generate(impero_c, args, scalar_type, kernel_name="loopy_kernel", index_name data = list(args) for i, (temp, dtype) in enumerate(assign_dtypes(impero_c.temporaries, scalar_type)): name = "t%d" % i - if isinstance(temp, gem.Zero): - initializer = numpy.zeros(temp.shape, dtype=dtype) - data.append(lp.TemporaryVariable(name, shape=temp.shape, dtype=dtype, initializer=initializer, address_space=lp.AddressSpace.LOCAL, read_only=True)) - elif isinstance(temp, gem.Constant): + if isinstance(temp, gem.Constant): data.append(lp.TemporaryVariable(name, shape=temp.shape, dtype=dtype, initializer=temp.array, address_space=lp.AddressSpace.LOCAL, read_only=True)) else: shape = tuple([i.extent for i in ctx.indices[temp]]) + temp.shape From 141db137de97f260221db59ef5899fd01dff9308 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Mon, 23 Nov 2026 09:59:49 +0000 Subject: [PATCH 09/12] Include base form operators in quadrature inference Use the operators in each integrand when choosing the quadrature rule. Test Boundary Quadrature interpolation in exterior and interior facet integrals. AI-assisted-by: OpenAI Codex --- tests/firedrake/regression/test_quadrature.py | 30 +++++++++++++++---- tsfc/kernel_interface/common.py | 3 +- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/tests/firedrake/regression/test_quadrature.py b/tests/firedrake/regression/test_quadrature.py index 41980de181..eede6c55a2 100644 --- a/tests/firedrake/regression/test_quadrature.py +++ b/tests/firedrake/regression/test_quadrature.py @@ -1,3 +1,5 @@ +from math import sqrt + from firedrake import * import pytest import numpy as np @@ -54,10 +56,10 @@ def test_quadrature_element(mesh, family, mat_type, diagonal): assemble(a, mat_type=mat_type, diagonal=diagonal) -@pytest.mark.parallel([1, 2]) -@pytest.mark.parametrize("space", [FunctionSpace, VectorFunctionSpace, TensorFunctionSpace]) -def test_boundary_quadrature_interpolation(mesh, space): - V = space(mesh, "Boundary Quadrature", 2) +@pytest.fixture(params=[FunctionSpace, VectorFunctionSpace, TensorFunctionSpace], + ids=lambda space: space.__name__) +def boundary_quadrature_data(mesh, request): + V = request.param(mesh, "Boundary Quadrature", 2) x = SpatialCoordinate(mesh) if V.value_shape == (): expr = x[0]**2 + x[1] @@ -65,9 +67,25 @@ def test_boundary_quadrature_interpolation(mesh, space): expr = as_vector([x[0]**2, x[1]]) else: expr = as_tensor([[x[0]**2, x[1]], [x[0]*x[1], 1 + x[0]]]) + return V, expr + +@pytest.mark.parallel([1, 2]) +def test_boundary_quadrature_interpolation(boundary_quadrature_data): + V, expr = boundary_quadrature_data f = Function(V).interpolate(expr) + error = f - expr # The functionals are point evaluations, so interpolation is exact there - assert np.isclose(assemble(inner(f - expr, f - expr) * ds), 0) - assert np.isclose(assemble(inner(f('+') - expr('+'), f('+') - expr('+')) * dS), 0) + assert sqrt(abs(assemble(inner(error, error) * ds))) < 1e-12 + trace = error('+') + assert sqrt(abs(assemble(inner(trace, trace) * dS))) < 1e-12 + + +@pytest.mark.parallel([1, 2]) +def test_boundary_quadrature_interpolation_in_form(boundary_quadrature_data): + V, expr = boundary_quadrature_data + error = interpolate(expr, V) - expr + assert sqrt(abs(assemble(inner(error, error) * ds))) < 1e-12 + trace = error('+') + assert sqrt(abs(assemble(inner(trace, trace) * dS))) < 1e-12 diff --git a/tsfc/kernel_interface/common.py b/tsfc/kernel_interface/common.py index 73be8237a8..4fcb9e30c4 100644 --- a/tsfc/kernel_interface/common.py +++ b/tsfc/kernel_interface/common.py @@ -5,7 +5,7 @@ from itertools import chain, product import copy -from ufl.algorithms.analysis import has_type +from ufl.algorithms.analysis import extract_base_form_operators, has_type from ufl.classes import Cofunction, GeometricQuantity, Interpolate from ufl.finiteelement import AbstractFiniteElement from ufl.utils.sequences import max_degree @@ -244,6 +244,7 @@ def compile_integrand(self, integrand, params, ctx): # Compile: ufl -> gem info = self.integral_data_info functions = [*info.arguments, self.coordinate(info.domain), *info.coefficients] + functions.extend(extract_base_form_operators(integrand)) set_quad_rule(params, info.domain.ufl_cell(), info.integral_type, functions) quad_rule = params["quadrature_rule"] config = self.fem_config() From bf93a71ce42e056c248903127f58e3ac7b9a9307 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Mon, 23 Nov 2026 16:32:23 +0000 Subject: [PATCH 10/12] Do not permute quadrature axes with a single point On a hexahedron the quadrature points of a facet integral are replaced by orientation-permuted runtime indices. With one point on an axis, a facet quadrature coefficient leaves Delta(q, 0) after its singleton sum is unrolled, and the permuted q stops it from folding, so a Delta reached code generation. The only permutation of a single point is the identity, so such an axis takes the fixed index 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BiE9EeMXhu6p14ShyaFE3o --- tests/tsfc/test_dual_evaluation.py | 18 +++++++++++++++++- tsfc/fem.py | 4 ++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/tsfc/test_dual_evaluation.py b/tests/tsfc/test_dual_evaluation.py index 204f135d24..0bd178782e 100644 --- a/tests/tsfc/test_dual_evaluation.py +++ b/tests/tsfc/test_dual_evaluation.py @@ -4,7 +4,7 @@ import ufl import finat.ufl from finat.element_factory import create_element -from tsfc import compile_expression_dual_evaluation +from tsfc import compile_expression_dual_evaluation, compile_form from tsfc.kernel_args import OutputKernelArg @@ -128,3 +128,19 @@ def test_dual_argument_is_sum_factorised(cell, restriction, dual): rate = math.log(flops[1] / flops[0]) / math.log(degrees[1] / degrees[0]) # Lower order terms move the measured rate to either side of dim + 1. assert rate < dim + 1.5 + + +@pytest.mark.parametrize("degree", [1, 2]) +@pytest.mark.parametrize("cell", [ufl.quadrilateral, ufl.hexahedron]) +def test_boundary_quadrature_in_facet_integral(cell, degree): + """Facet quadrature values enter a facet integral on a runtime facet. + + On a hexahedron the quadrature points of a facet integral are permuted by + the facet orientation, including the axes with a single point. + """ + mesh = ufl.Mesh(finat.ufl.VectorElement("Q", cell, 1)) + u = ufl.Coefficient(ufl.FunctionSpace(mesh, finat.ufl.FiniteElement("Q", cell, 2))) + V = ufl.FunctionSpace(mesh, finat.ufl.FiniteElement("Boundary Quadrature", cell, degree)) + for f in [ufl.Coefficient(V), ufl.Interpolate(u, V)]: + kernel, = compile_form(f * u * ufl.ds) + assert kernel.flop_count > 0 diff --git a/tsfc/fem.py b/tsfc/fem.py index 8bc05d378f..9f779c153d 100644 --- a/tsfc/fem.py +++ b/tsfc/fem.py @@ -975,6 +975,10 @@ def _make_quad_multiindex_permuted(domain, mt, ctx): for ref_axis in range(len(quad_multiindex)): io = cell.extract_intrinsic_orientation(o, ref_axis) io_perm_map = gem.Literal(quad_rule.intrinsic_orientation_permutation_map_tuple[ref_axis], dtype=gem.uint_type) + if io_perm_map.shape[-1] == 1: + # The only permutation of a single point is the identity. + quad_multiindex_permuted.append(0) + continue # Effectively swap axes if needed. ref_index = tuple((phys_index, gem.Indexed(eo_perm_map, (eo, ref_axis, phys_axis))) for phys_axis, phys_index in enumerate(quad_multiindex)) quad_index_permuted = gem.VariableIndex(gem.FlexiblyIndexed(io_perm_map, ((0, ((io, 1), )), (0, ref_index)))) From 9756f9713e0813a4bc30f99f12002c1472b06030 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Mon, 23 Nov 2026 16:32:23 +0000 Subject: [PATCH 11/12] Test flop count of integer index arithmetic Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BiE9EeMXhu6p14ShyaFE3o --- tests/tsfc/test_flop_count.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/tsfc/test_flop_count.py b/tests/tsfc/test_flop_count.py index 1925fbaf28..363b554923 100644 --- a/tests/tsfc/test_flop_count.py +++ b/tests/tsfc/test_flop_count.py @@ -11,7 +11,7 @@ def test_count_flops(expression): assert flops == expected -@pytest.fixture(params=("expr1", "expr2", "expr3", "expr4")) +@pytest.fixture(params=("expr1", "expr2", "expr3", "expr4", "expr5")) def expression(request): if request.param == "expr1": expr = gem.Sum(gem.Product(gem.Variable("a", ()), gem.Literal(2)), @@ -58,6 +58,20 @@ def expression(request): expr = compile_gem(assignments, (j, k)) # Cjk += \sum_i Aij * Bki expected = 2 * 10 * 8 * 15 + elif request.param == "expr5": + A = gem.Variable("A", (4,)) + B = gem.Variable("B", (4,)) + n = gem.Variable("n", (), dtype=gem.uint_type) + two = gem.Literal(2, dtype=gem.uint_type) + k = gem.VariableIndex(gem.Remainder(gem.FloorDiv(n, two), two)) + expr = gem.Product(gem.Indexed(A, (k,)), gem.Indexed(B, (k,))) + C = gem.Variable("C", (1,)) + i, = gem.indices(1) + expr, = preprocess_gem([expr]) + assignments = [(C[i], expr)] + expr = compile_gem(assignments, (i,)) + # C += A[k] * B[k], where k = n // 2 % 2 is integer arithmetic + expected = 1 + 1 else: raise ValueError("Unexpected expression") From 112eb363f898ecc8a531f5e9e50400f6627b58a0 Mon Sep 17 00:00:00 2001 From: Pablo Brubeck Date: Mon, 23 Nov 2026 23:12:20 +0000 Subject: [PATCH 12/12] Permute facet quadrature tables before the coefficient contraction Apply the facet orientation permutation to the basis tables instead of to the contracted result. The argument tables are already permuted in the same way. Interpolated values on Boundary Quadrature elements then need no separate treatment. AI assistance: OpenAI Codex. Co-Authored-By: Claude Opus 5.5 --- tsfc/fem.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/tsfc/fem.py b/tsfc/fem.py index 9f779c153d..f896a45676 100644 --- a/tsfc/fem.py +++ b/tsfc/fem.py @@ -912,6 +912,16 @@ def take_singleton(xs): per_derivative = {alpha: gem.select_expression(tables, f) for alpha, tables in per_derivative.items()} + if ctx.use_canonical_quadrature_point_ordering: + # Permute the tables from reference to physical quadrature point order + # before they are contracted with ``vec``. + # The facet orientation then does not change ``vec``. + quad_multiindex = ctx.quadrature_rule.point_set.indices + quad_multiindex_permuted = _make_quad_multiindex_permuted(domain, mt, ctx) + mapper = gem.node.MemoizerArg(gem.optimise.filtered_replace_indices) + per_derivative = {alpha: mapper(table, tuple(zip(quad_multiindex, quad_multiindex_permuted))) + for alpha, table in per_derivative.items()} + # Coefficient evaluation beta = ctx.index_cache.setdefault(ufl_element, element.get_indices()) zeta = element.get_value_indices() @@ -946,11 +956,6 @@ def take_singleton(xs): if isinstance(node, gem.Literal)): result = gem.optimise.aggressive_unroll(result) - if ctx.use_canonical_quadrature_point_ordering: - quad_multiindex = ctx.quadrature_rule.point_set.indices - quad_multiindex_permuted = _make_quad_multiindex_permuted(domain, mt, ctx) - mapper = gem.node.MemoizerArg(gem.optimise.filtered_replace_indices) - result = mapper(result, tuple(zip(quad_multiindex, quad_multiindex_permuted))) return result