Skip to content

FInAT: hash elements by value - #304

Merged
pbrubeck merged 4 commits into
mainfrom
pbrubeck/hashable-finat
Nov 26, 2026
Merged

pbrubeck merged 4 commits into
mainfrom
pbrubeck/hashable-finat

Conversation

@pbrubeck

@pbrubeck pbrubeck commented Oct 22, 2026 •

Copy link
Copy Markdown

Fixes #275.

Summary

FInAT elements compared and hashed by identity. Two constructions of the same element were different cache keys, so Firedrake keys its caches on entity_dofs_key/entity_permutations_key instead. Those keys cannot tell apart elements that share their DoF layout but not their basis, e.g. DG2 equispaced and spectral, which gives wrong multigrid transfers.

FiniteElementBase now records the constructor arguments, and equality and hashing come from them:

FiniteElementBase.__new__(cls, *args, **kwargs)
  self._init_args = (args, kwargs)

_hash_key
  bind args to the signature of type(self).__init__, apply its defaults
  return (type(self), frozen arguments)     # lists -> tuples, dicts -> frozensets, arrays -> bytes

__eq__   = same type and same _hash_key
__hash__ = hash(_hash_key)
__getnewargs_ex__ = _init_args              # keeps pickle and copy working

Elements that wrap other elements (TensorProductElement, EnrichedElement, TensorFiniteElement, ...) hash recursively. FIAT cells and quadrature rules already hash by value. EnrichedElement.__new__ now passes its arguments to the base __new__.

Evidence

New tests in test/finat/test_hash.py:

Lagrange(T, 2)                     == Lagrange(T, 2)              # was False
Lagrange(T, 2)                     == Lagrange(T, degree=2)       # was False
Hermite(T)                         == Hermite(T, degree=3)        # was False
DG(T, 2, "equispaced")             != DG(T, 2, "spectral")        # same entity_dofs
pickle.loads(pickle.dumps(e))      == e
  • Before: 8 failed, 5 passed in test/finat/test_hash.py
    After: 13 passed
  • Full suite (without test/FIAT/regression, which needs a download): 2618 passed.
  • TSFC tests (firedrake/tests/tsfc) against this branch: 374 passed.
  • A Firedrake regression subset (multigrid, assemble, interpolate, bcs, matrix, facet elements, quadrature, zany, restricted spaces) against this branch: 957 passed, 0 failed at 1 and 2 ranks.
  • All 2110 elements built by create_element from the UFL element list hash. Of those, 702 pairs that compare equal come from different UFL spellings (aliases, default variants), and every pair tabulates identically.

Merge Danger

Door: two-way

Blast Radius: medium

Every FInAT element now compares by value, so caches keyed on elements can merge entries that were separate before. Two elements compare equal only when they have the same type and the same constructor arguments. A default hidden behind **kwargs (e.g. FIAT's variant default in Lagrange) is not normalised, which costs a cache miss, never a false match. The hash depends on PYTHONHASHSEED, like the identity hash did, so it is not yet suitable for disk caches.


AI assistance: this PR was written with Claude Code (Claude Opus 5.5).

🤖 Generated with Claude Code

@pbrubeck pbrubeck added the LLM used An LLM was used in the production of this PR label Oct 22, 2026
FInAT elements compared and hashed by identity, so two constructions of
the same element were different cache keys, and Firedrake had to key its
caches on entity_dofs_key/entity_permutations_key instead, which cannot
tell apart elements that share their DoF layout but not their basis.

Record the constructor arguments in FiniteElementBase.__new__ and
derive __eq__ and __hash__ from the type and those arguments, matched
to the parameters of __init__. Elements that wrap other elements hash
recursively, and FIAT cells and quadrature rules already hash by value.

Fixes #275.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@connorjward connorjward left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be a nicer approach to make everything into a frozen dataclass, which is effectively the same thing as this but much more explicit. But this does work.

This also has the issue that mutating the element will not update the hash key. For example:

import FIAT
from finat import *


triangle = FIAT.ufc_cell("triangle")

cg = Lagrange(triangle, 1)
cg_copy = Lagrange(triangle, 1)
dg = DiscontinuousLagrange(triangle, 1)

cg._element = dg._element

assert cg != cg_copy  # fails

This is admittedly contrived, so this might not be a concern.

Comment thread finat/finiteelementbase.py Resolved
Comment thread test/finat/test_hash.py Resolved
Co-authored-by: Connor Ward <c.ward20@imperial.ac.uk>
@pbrubeck

Copy link
Copy Markdown
Author

cg._element = dg._element

assert cg != cg_copy # fails


This is admittedly contrived, so this might not be a concern.

We don't ever mutate an element, so we don't need to worry about this.

@pbrubeck

Copy link
Copy Markdown
Author

make everything into a frozen dataclass

I guess you mean make every element a frozen dataclass. It seems a much more invasive change and I don't think I want to do it in this PR.

AI assistance: OpenAI Codex.

@connorjward connorjward left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy with your explanations. Thanks!

@rckirby rckirby left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems fine to me as well, happy to live with the caveats discussed.

@pbrubeck
pbrubeck merged commit eeb041e into main Nov 26, 2026
9 checks passed
@pbrubeck
pbrubeck deleted the pbrubeck/hashable-finat branch November 26, 2026 13:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

LLM used An LLM was used in the production of this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FInAT elements are not hashable

3 participants