Skip to content

Indexed charts

An IndexedChart holds the items of a RulePresentation and finds, when an item arrives, the rule instances it completes. A rule whose patterns are relations of their own variables (generic_joinable: no pattern is a sum of two variables) is joined by Generic Join from each trigger; any other rule, or every rule of a chart made with join="keyed", looks its premises up one at a time.

Generic Join from a trigger

For a rule and a trigger, the premise an arriving item fills, or the conclusion for the backward pass, join_order puts the trigger's variables first and the others in the order they first occur. Each other premise has a trie of the items of its form that match its pattern, keyed by its variables in that order and kept up to date as items arrive. Matching the trigger binds its variables; each other premise's trie is entered along the bound prefix of its variables; the remaining variables are bound one at a time, each to the values in the intersection of the tries that contain it, iterating the smallest and probing the others. A complete binding determines every premise's item, since the item's arguments are its pattern evaluated at the binding.

Lemma (each instance once). Admit items one at a time, and let each admitted item \(x\) trigger every premise position \(t\) whose form it has, enumerating the instances in which \(x\) fills \(t\), every premise is admitted, and no premise before \(t\) is \(x\). Then each instance is enumerated exactly once.

Proof. An instance is a rule with premise items \(p_1, \dots, p_n\); its binding determines the items, and the items determine the binding, since every variable of the rule occurs in a premise. Generic Join from \(t\) with \(x\) fixed at \(t\) reaches each binding of the other variables consistent with the admitted items once, by the values of its variables in order, so it yields each choice of other premise items once. Let \(x\) be the last of \(p_1, \dots, p_n\) to be admitted and \(t\) the least position with \(p_t = x\). Before \(x\) is admitted some premise is not, so the instance is not enumerated. When \(x\) is admitted, the join from \(t\) yields it, and the leaf test passes since no premise before \(t\) is \(x\); the join from a later position \(u\) with \(p_u = x\) yields it and the test rejects it, since \(p_t = x\) comes before \(u\). Items admitted later do not complete it. QED

Theorem (cost). Over a run, the lookups and candidates of one rule with \(m\) premises and \(n\) variables are \(O(m N + m^2 n\, \mathrm{AGM})\), where \(\mathrm{AGM}\) is the bound of a fractional edge cover of the body over the final relations and \(N\) the most items of a premise's form.

Proof. Fix a trigger position \(t\) and an arriving item \(x\). Its join binds the variables of \(t\) to \(x\)'s values and then runs the levels of Generic Join over the other premises, each relation a subset of its final one. Every set it intersects at a level is a subset of the set that Generic Join over the whole body, in the same order and on the final relations, intersects below the same prefix; and the prefixes it reaches are among those. So its work is at most that of the whole join below the prefix of \(x\)'s values, plus \(O(m)\) to enter the tries. Distinct items at \(t\) have distinct prefixes, so summing over them gives at most the whole join's work, \(O(m n\, \mathrm{AGM})\) (Joins), plus \(O(m N)\). Summing over the \(m\) positions gives the bound. QED

The plan records, in PlanRecord.joins, each rule's algorithm, the weight \(\rho^*\) of a least fractional edge cover of its body, and this bound with \(\mathrm{AGM} \le N^{\rho^*}\) (rule_joins). On the triangle with a hub value and the skewed triangle, the chart stays within the bound, and a chart that looks premises up one at a time does \(\Theta(N^2)\), which the same bound rejects; on chains, diamonds and skip graphs, whose step rule has \(\rho^* = 1\), the work is linear in the edges.

Keyed lookups

join_plans fixes, for every rule and trigger, the order in which the other premises are looked up and the positions each lookup is keyed on: next the premise with the most arguments whose variables are already bound. It handles any pattern that matching binds in premise order, including a sum whose other summand is already bound, and its instances are enumerated once by the same lemma, with the test applied as each premise is chosen. ChartWork counts the lookups, candidates, instances, side conditions and index entries of either method.

indexed

An indexed chart of a rule presentation, with bindings pushed into lookups.

Items of each judgment form are indexed on the argument positions a premise finds bound when it is matched: when a rule fires on one item, the variables that item binds turn the other premises' patterns into lookup keys, and only the items with those arguments are visited. The indexes are built on first use and kept up to date as items arrive, so a lookup costs its key and its answers, not a scan of the family.

A join plan fixes, for each rule and each premise that triggers it, the order in which the other premises are looked up and the positions each lookup is keyed on: next comes the premise with the most bound positions, ties in premise order.

TrieNode

TrieNode = Trie[Ground, Item]

A level of a premise's trie; its leaves are items. A premise without variables keeps its item under the key ().

JoinStep didactic-model

JoinStep(*, premise: int, keyed: tuple[int, ...] = ())

Bases: ValueModel

One lookup of a join plan.

PARAMETER DESCRIPTION
premise

The premise looked up.

TYPE: int

keyed

The argument positions whose values are known before the lookup and form its key.

TYPE: tuple of int DEFAULT: ()

RuleJoinPlan didactic-model

RuleJoinPlan(*, rule: ConstructorId = field(opaque=True, extras=OPAQUE_BY_VALUE), trigger: int, steps: tuple[JoinStep, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

The order of lookups when one premise of a rule triggers it.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: ConstructorId DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

trigger

The premise matched against the new item, or -1 when the conclusion is matched first, as in a backward pass.

TYPE: int

steps

The other premises, in lookup order.

TYPE: tuple of JoinStep DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

ChartWork didactic-model

ChartWork(*, lookups: int = 0, candidates: int = 0, instances: int = 0, conditions: int = 0, index_entries: int = 0)

Bases: ValueModel

Counters of the work of a chart.

PARAMETER DESCRIPTION
lookups

Index lookups.

TYPE: int DEFAULT: 0

candidates

Items returned by lookups and matched against a pattern.

TYPE: int DEFAULT: 0

instances

Rule instances enumerated.

TYPE: int DEFAULT: 0

conditions

Side conditions evaluated.

TYPE: int DEFAULT: 0

index_entries

Entries added to indexes.

TYPE: int DEFAULT: 0

report

report(phase: Phase) -> WorkReport

The counters as a work report.

PARAMETER DESCRIPTION
phase

The phase they counted.

TYPE: Phase

RETURNS DESCRIPTION
WorkReport

Lookups as hash operations and candidates as key comparisons, the two measured.

Source code in src/quivers/stochastic/indexed.py
def report(self, phase: Phase) -> WorkReport:
    """The counters as a work report.

    Parameters
    ----------
    phase : Phase
        The phase they counted.

    Returns
    -------
    WorkReport
        Lookups as hash operations and candidates as key
        comparisons, the two measured.
    """
    return WorkReport(
        phase=phase,
        hash_operations=self.lookups,
        key_comparisons=self.candidates,
        measured=measuring({WorkField.HASH_OPERATIONS, WorkField.KEY_COMPARISONS}),
    )

IndexedChart

IndexedChart(presentation: RulePresentation, *, join: Literal['generic', 'keyed'] = 'generic')

Items of a presentation indexed on the argument positions lookups use.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

join

How a rule's other premises are found from a trigger. "generic" runs Generic Join over tries of the premises in the trigger's variable order, for every rule that generic_joinable admits, and looks premises up one at a time for the others; "keyed" looks premises up one at a time for every rule.

TYPE: ('generic', 'keyed') DEFAULT: "generic"

Source code in src/quivers/stochastic/indexed.py
def __init__(
    self,
    presentation: RulePresentation,
    *,
    join: Literal["generic", "keyed"] = "generic",
) -> None:
    self.presentation = presentation
    self.join = join
    self._tries: dict[
        tuple[ConstructorId, int, int], tuple[tuple[str, ...], TrieNode]
    ] = {}
    self._tries_by_family: dict[FamilyId, list[tuple[ConstructorId, int, int]]] = {}
    self._orders: dict[tuple[ConstructorId, int], tuple[str, ...]] = {}
    self.items = ItemTable()
    self._members: dict[FamilyId, list[Item]] = {}
    self._indexes: dict[
        tuple[FamilyId, tuple[int, ...]], dict[tuple[Ground, ...], list[Item]]
    ] = {}
    self.plans = join_plans(presentation)
    self.work = {
        "lookups": 0,
        "candidates": 0,
        "instances": 0,
        "conditions": 0,
        "index_entries": 0,
    }

counters

counters() -> ChartWork

The work so far.

RETURNS DESCRIPTION
ChartWork

The counters.

Source code in src/quivers/stochastic/indexed.py
def counters(self) -> ChartWork:
    """The work so far.

    Returns
    -------
    ChartWork
        The counters.
    """
    return ChartWork(**self.work)

add

add(item: Item) -> None

Index an item under every index of its family.

PARAMETER DESCRIPTION
item

The item, added once.

TYPE: Item

Source code in src/quivers/stochastic/indexed.py
def add(self, item: Item) -> None:
    """Index an item under every index of its family.

    Parameters
    ----------
    item : Item
        The item, added once.
    """
    self._members.setdefault(item.family, []).append(item)
    for key in self._tries_by_family.get(item.family, ()):
        variables, root = self._tries[key]
        self._insert(key, variables, root, item)
    for (family, positions), index in self._indexes.items():
        if family == item.family:
            key = tuple(item.arguments[p] for p in positions)
            index.setdefault(key, []).append(item)
            self.work["index_entries"] += 1

lookup

lookup(family: FamilyId, positions: tuple[int, ...], key: tuple[Ground, ...]) -> list[Item]

The items of a family with given values at given positions.

PARAMETER DESCRIPTION
family

The judgment form.

TYPE: FamilyId

positions

The argument positions.

TYPE: tuple of int

key

Their values.

TYPE: tuple of Ground

RETURNS DESCRIPTION
list of Item

The items, in the order they were added.

Source code in src/quivers/stochastic/indexed.py
def lookup(
    self, family: FamilyId, positions: tuple[int, ...], key: tuple[Ground, ...]
) -> list[Item]:
    """The items of a family with given values at given positions.

    Parameters
    ----------
    family : FamilyId
        The judgment form.
    positions : tuple of int
        The argument positions.
    key : tuple of Ground
        Their values.

    Returns
    -------
    list of Item
        The items, in the order they were added.
    """
    self.work["lookups"] += 1
    if not positions:
        return self._members.get(family, [])
    index = self._indexes.get((family, positions))
    if index is None:
        index = {}
        for item in self._members.get(family, []):
            index.setdefault(
                tuple(item.arguments[p] for p in positions), []
            ).append(item)
            self.work["index_entries"] += 1
        self._indexes[(family, positions)] = index
    return index.get(key, [])

holds

holds(rule: Rule, binding: Binding) -> bool

Evaluate a rule's side condition, counting the evaluation.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

binding

Its variables.

TYPE: Binding

RETURNS DESCRIPTION
bool

Whether the condition holds; true without one.

RAISES DESCRIPTION
MatchError

If the condition reads a variable the binding lacks.

Source code in src/quivers/stochastic/indexed.py
def holds(self, rule: Rule, binding: Binding) -> bool:
    """Evaluate a rule's side condition, counting the evaluation.

    Parameters
    ----------
    rule : Rule
        The rule.
    binding : Binding
        Its variables.

    Returns
    -------
    bool
        Whether the condition holds; true without one.

    Raises
    ------
    MatchError
        If the condition reads a variable the binding lacks.
    """
    if rule.side_condition is not None:
        self.work["conditions"] += 1
    return side_condition_holds(self.presentation, rule, binding)

instances

instances(rule: Rule, trigger: int, item: Item, admitted: Callable[[Item], bool]) -> Iterator[tuple[Binding, tuple[Item, ...]]]

The instances of a rule that item completes.

item fills premise trigger and no earlier premise; every other premise is an admitted item. So when items are admitted one at a time and each new item triggers every position it fits, each instance is produced once, by the last of its premises to be admitted, at the first position that item fills.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

trigger

The premise item fills.

TYPE: int

item

The newly admitted item.

TYPE: Item

admitted

Whether an item is admitted; item itself must be.

TYPE: Callable[[Item], bool]

YIELDS DESCRIPTION
tuple of Binding and tuple of Item

The binding and the premise items, in premise order.

Source code in src/quivers/stochastic/indexed.py
def instances(
    self,
    rule: Rule,
    trigger: int,
    item: Item,
    admitted: Callable[[Item], bool],
) -> Iterator[tuple[Binding, tuple[Item, ...]]]:
    """The instances of a rule that ``item`` completes.

    ``item`` fills premise ``trigger`` and no earlier premise; every
    other premise is an admitted item. So when items are admitted one
    at a time and each new item triggers every position it fits, each
    instance is produced once, by the last of its premises to be
    admitted, at the first position that item fills.

    Parameters
    ----------
    rule : Rule
        The rule.
    trigger : int
        The premise ``item`` fills.
    item : Item
        The newly admitted item.
    admitted : Callable[[Item], bool]
        Whether an item is admitted; ``item`` itself must be.

    Yields
    ------
    tuple of Binding and tuple of Item
        The binding and the premise items, in premise order.
    """
    premise = rule.premises[trigger]
    binding: Binding = {}
    for pattern, value in zip(
        premise.judgment.arguments, item.arguments, strict=True
    ):
        if not match_index(pattern, value, binding):
            return
    if self.method(rule) == "generic":
        yield from self._generic(rule, trigger, item, binding, admitted)
        return
    plan = self.plans[(rule.id, trigger)]
    chosen: dict[int, Item] = {trigger: item}
    yield from self._extend(
        rule, plan.steps, 0, binding, chosen, trigger, item, admitted
    )

incoming

incoming(rule: Rule, item: Item, admitted: Callable[[Item], bool]) -> Iterator[tuple[Binding, tuple[Item, ...]]]

The instances of a rule that conclude item from admitted premises.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

item

The conclusion.

TYPE: Item

admitted

Whether a premise item is admitted.

TYPE: Callable[[Item], bool]

YIELDS DESCRIPTION
tuple of Binding and tuple of Item

The binding and the premise items.

Source code in src/quivers/stochastic/indexed.py
def incoming(
    self, rule: Rule, item: Item, admitted: Callable[[Item], bool]
) -> Iterator[tuple[Binding, tuple[Item, ...]]]:
    """The instances of a rule that conclude ``item`` from admitted premises.

    Parameters
    ----------
    rule : Rule
        The rule.
    item : Item
        The conclusion.
    admitted : Callable[[Item], bool]
        Whether a premise item is admitted.

    Yields
    ------
    tuple of Binding and tuple of Item
        The binding and the premise items.
    """
    if rule.conclusion.family != item.family:
        return
    binding: Binding = {}
    for pattern, value in zip(
        rule.conclusion.arguments, item.arguments, strict=True
    ):
        if not match_index(pattern, value, binding):
            return
    if self.method(rule) == "generic":
        yield from self._generic(rule, -1, item, binding, admitted)
        return
    plan = self.plans[(rule.id, -1)]
    yield from self._extend(rule, plan.steps, 0, binding, {}, -1, item, admitted)

method

method(rule: Rule) -> Literal['generic', 'keyed']

How this chart joins a rule's premises.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

RETURNS DESCRIPTION
{'generic', 'keyed'}

"generic" when the chart runs Generic Join and the rule admits it.

Source code in src/quivers/stochastic/indexed.py
def method(self, rule: Rule) -> Literal["generic", "keyed"]:
    """How this chart joins a rule's premises.

    Parameters
    ----------
    rule : Rule
        The rule.

    Returns
    -------
    {"generic", "keyed"}
        ``"generic"`` when the chart runs Generic Join and the rule
        admits it.
    """
    if self.join == "generic" and generic_joinable(rule):
        return "generic"
    return "keyed"

index_variables

index_variables(term: IndexTerm) -> set[str]

The variable names of an index term.

PARAMETER DESCRIPTION
term

The term.

TYPE: IndexTerm

RETURNS DESCRIPTION
set of str

Its variables.

Source code in src/quivers/stochastic/indexed.py
def index_variables(term: IndexTerm) -> set[str]:
    """The variable names of an index term.

    Parameters
    ----------
    term : IndexTerm
        The term.

    Returns
    -------
    set of str
        Its variables.
    """
    if isinstance(term, IndexVariable):
        return {term.name}
    if isinstance(term, IndexConstructor):
        found: set[str] = set()
        for item in term.arguments:
            found |= index_variables(item)
        return found
    if isinstance(term, IndexSum):
        return {item.name for item in term.terms}
    return set()

flat_pattern

flat_pattern(term: IndexTerm) -> bool

Whether matching a term alone binds all its variables.

PARAMETER DESCRIPTION
term

The term.

TYPE: IndexTerm

RETURNS DESCRIPTION
bool

False when a sum, here or nested, has two variables.

Source code in src/quivers/stochastic/indexed.py
def flat_pattern(term: IndexTerm) -> bool:
    """Whether matching a term alone binds all its variables.

    Parameters
    ----------
    term : IndexTerm
        The term.

    Returns
    -------
    bool
        False when a sum, here or nested, has two variables.
    """
    if isinstance(term, IndexSum):
        return len({item.name for item in term.terms}) <= 1
    if isinstance(term, IndexConstructor):
        return all(flat_pattern(argument) for argument in term.arguments)
    return True

generic_joinable

generic_joinable(rule: Rule) -> bool

Whether every premise, and the conclusion, is a relation of its own variables.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

RETURNS DESCRIPTION
bool

True when no pattern of the rule has a sum of two variables and no premise has hypotheses.

Source code in src/quivers/stochastic/indexed.py
def generic_joinable(rule: Rule) -> bool:
    """Whether every premise, and the conclusion, is a relation of its own variables.

    Parameters
    ----------
    rule : Rule
        The rule.

    Returns
    -------
    bool
        True when no pattern of the rule has a sum of two variables and
        no premise has hypotheses.
    """
    judgments = [premise.judgment for premise in rule.premises] + [rule.conclusion]
    return all(not premise.hypotheses for premise in rule.premises) and all(
        flat_pattern(argument)
        for judgment in judgments
        for argument in judgment.arguments
    )

join_order

join_order(rule: Rule, trigger: int) -> tuple[str, ...]

The variable order of a rule's join from one trigger.

The variables the trigger binds come first, in the order they occur in its pattern (the conclusion's for trigger -1), then the others in the order they first occur in the premises.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

trigger

The triggering premise, or -1 for the conclusion.

TYPE: int

RETURNS DESCRIPTION
tuple of str

The order.

Source code in src/quivers/stochastic/indexed.py
def join_order(rule: Rule, trigger: int) -> tuple[str, ...]:
    """The variable order of a rule's join from one trigger.

    The variables the trigger binds come first, in the order they occur
    in its pattern (the conclusion's for trigger ``-1``), then the others
    in the order they first occur in the premises.

    Parameters
    ----------
    rule : Rule
        The rule.
    trigger : int
        The triggering premise, or ``-1`` for the conclusion.

    Returns
    -------
    tuple of str
        The order.
    """
    source = (
        rule.conclusion.arguments
        if trigger < 0
        else rule.premises[trigger].judgment.arguments
    )
    order = _ordered_variables(source)
    for premise in rule.premises:
        for name in _ordered_variables(premise.judgment.arguments):
            if name not in order:
                order.append(name)
    return tuple(order)

index_variables_of

index_variables_of(arguments: Sequence[IndexTerm]) -> set[str]

The variables of a pattern.

PARAMETER DESCRIPTION
arguments

The pattern's arguments.

TYPE: Sequence of IndexTerm

RETURNS DESCRIPTION
set of str

Its variables.

Source code in src/quivers/stochastic/indexed.py
def index_variables_of(arguments: Sequence[IndexTerm]) -> set[str]:
    """The variables of a pattern.

    Parameters
    ----------
    arguments : Sequence of IndexTerm
        The pattern's arguments.

    Returns
    -------
    set of str
        Its variables.
    """
    found: set[str] = set()
    for argument in arguments:
        found |= index_variables(argument)
    return found

join_plans

join_plans(presentation: RulePresentation) -> dict[tuple[ConstructorId, int], RuleJoinPlan]

The join plan of every rule for every trigger, and from its conclusion.

PARAMETER DESCRIPTION
presentation

The presentation.

TYPE: RulePresentation

RETURNS DESCRIPTION
dict of tuple of ConstructorId and int to RuleJoinPlan

Plans by rule and trigger; trigger -1 starts from the conclusion's variables.

Source code in src/quivers/stochastic/indexed.py
def join_plans(
    presentation: RulePresentation,
) -> dict[tuple[ConstructorId, int], RuleJoinPlan]:
    """The join plan of every rule for every trigger, and from its conclusion.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation.

    Returns
    -------
    dict of tuple of ConstructorId and int to RuleJoinPlan
        Plans by rule and trigger; trigger ``-1`` starts from the
        conclusion's variables.
    """
    plans: dict[tuple[ConstructorId, int], RuleJoinPlan] = {}
    for rule in presentation.rules:
        positions = range(len(rule.premises))
        for trigger in positions:
            bound: set[str] = set()
            for argument in rule.premises[trigger].judgment.arguments:
                bound |= index_variables(argument)
            others = [index for index in positions if index != trigger]
            plans[(rule.id, trigger)] = _plan(rule, bound, others, trigger)
        conclusion: set[str] = set()
        for argument in rule.conclusion.arguments:
            conclusion |= index_variables(argument)
        plans[(rule.id, -1)] = _plan(rule, conclusion, list(positions), -1)
    return plans

side_condition_holds

side_condition_holds(presentation: RulePresentation, rule: Rule, binding: Binding) -> bool

Evaluate a rule's side condition with the QIEC evaluator.

PARAMETER DESCRIPTION
presentation

The presentation, which holds the condition's computation.

TYPE: RulePresentation

rule

The rule.

TYPE: Rule

binding

Its variables.

TYPE: Binding

RETURNS DESCRIPTION
bool

Whether the condition holds; true without one.

RAISES DESCRIPTION
MatchError

If the condition reads a variable the binding lacks.

Source code in src/quivers/stochastic/indexed.py
def side_condition_holds(
    presentation: RulePresentation, rule: Rule, binding: Binding
) -> bool:
    """Evaluate a rule's side condition with the QIEC evaluator.

    Parameters
    ----------
    presentation : RulePresentation
        The presentation, which holds the condition's computation.
    rule : Rule
        The rule.
    binding : Binding
        Its variables.

    Returns
    -------
    bool
        Whether the condition holds; true without one.

    Raises
    ------
    MatchError
        If the condition reads a variable the binding lacks.
    """
    condition = rule.side_condition
    if condition is None:
        return True
    computation = presentation.conditions_by_id[condition.computation]
    environment = {}
    for name, parameter in zip(
        condition.arguments, computation.parameters, strict=True
    ):
        if name not in binding:
            raise MatchError(f"the side condition of {rule.name!r} reads {name!r}")
        environment[parameter] = _matched_value(
            computation, rule, name, parameter, binding[name]
        )
    return bool(Evaluator().evaluate(computation.body, environment))