def replay(self, target: Iterable[Sequence[int]]) -> SignedTreeExpansion:
"""Express one actual spanning-tree moment in the NBC family exactly."""
supplied = tuple(
_normalize_edge(edge, self.degree, name="target") for edge in target
)
tree = frozenset(supplied)
if len(supplied) != len(tree):
raise ValueError("target edges must not contain duplicates.")
if not tree <= frozenset(self.edge_order):
raise ValueError("target must use only actual occurrence edges.")
_prepare_tree(tree, self.degree)
ranks = {edge: rank for rank, edge in enumerate(self.edge_order)}
arrow_signs = {
edge: 1 if arrow == edge else -1
for edge, arrow in zip(
self.edge_order,
self.reference_arrows,
strict=True,
)
}
def tree_key(value: OccurrenceTree) -> tuple[int, ...]:
return tuple(sorted(ranks[edge] for edge in value))
rewrites: dict[
OccurrenceTree,
tuple[tuple[OccurrenceTree, int], ...],
] = {}
pending = [tree]
while pending:
value = pending.pop()
if value in rewrites:
continue
reduction: tuple[OccurrenceEdge, tuple[OccurrenceEdge, ...]] | None = None
for higher in reversed(self.edge_order):
if higher in value:
continue
path = _tree_path(value, *higher, self.degree)
if all(ranks[edge] < ranks[higher] for edge in path):
reduction = higher, path
break
if reduction is None:
rewrites[value] = ()
continue
higher, path = reduction
unicyclic = value | {higher}
deltas = {}
for relation_tree, coefficient in _signed_unicyclic_relation(
unicyclic,
self.degree,
):
omitted = next(iter(unicyclic - relation_tree))
deltas[omitted] = coefficient * arrow_signs[omitted]
children = tuple(
(
frozenset((value - {removed}) | {higher}),
-deltas[higher] * deltas[removed],
)
for removed in path
)
rewrites[value] = children
pending.extend(child for child, _ in children)
expansions: dict[OccurrenceTree, SignedTreeExpansion] = {}
for value in sorted(
rewrites,
key=lambda item: sum(ranks[edge] for edge in item),
reverse=True,
):
children = rewrites[value]
if not children:
expansions[value] = ((value, 1),)
continue
totals: dict[OccurrenceTree, int] = {}
for child, local_coefficient in children:
for terminal, coefficient in expansions[child]:
totals[terminal] = (
totals.get(terminal, 0) + local_coefficient * coefficient
)
expansions[value] = tuple(
(terminal, coefficient)
for terminal, coefficient in sorted(
totals.items(), key=lambda item: tree_key(item[0])
)
if coefficient
)
return expansions[tree]