Skip to content

Joins

A rule body \(r_1(\bar x_1), \dots, r_m(\bar x_m)\) is a conjunctive query over \(n\) variables. body_query reads it off a Rule: each premise is an atom whose attributes are the variables of its pattern, and relations makes each atom's relation from the items of its form that match the pattern, keyed by the values of those variables. Matching flattens nested constructor patterns and literals; it determines the item from its tuple, since the item's arguments are the pattern evaluated there. A premise with a sum of two variables, such as \(u(i + k)\), is refused: its matches are not a relation of its items alone.

Two questions are asked of a body, and they have different algorithms.

question algorithm cost status
every instance (a forest, requested evidence) generic_join \(O(N + m\,n\,\mathrm{AGM})\) worst-case optimal in data complexity (GENERIC_JOIN_WORK)
sum of products, grouped by the conclusion eliminate \(O(N + n\,m\,W + F)\) for the chosen order conditional on the exponential time hypothesis (ELIMINATION_WORK)
the same, for weights that keep their order enumerate_aggregate that of generic_join the products need every instance in premise order

Listing instances

For weights \(x_e \ge 0\) on the atoms with \(\sum_{e \ni v} x_e \ge 1\) for every variable \(v\) (a fractional edge cover), the join has at most \(\mathrm{AGM} = \prod_e N_e^{x_e}\) tuples, and for every query and sizes there are relations attaining it up to a constant factor (Atserias, Grohe and Marx 2013). agm_bound solves the linear program that minimizes \(\sum_e x_e \log N_e\), rounds its solution to rationals and repairs any variable left uncovered, so the recorded AGMBound is an exact cover and its bound holds whether or not it is the least. For the triangle at equal sizes it is \(x = (\tfrac12, \tfrac12, \tfrac12)\) and \(N^{3/2}\).

Generic Join (Ngo, Re and Rudra 2014) binds the variables in a fixed order. With the variables before \(v\) bound to \(t\), the values of \(v\) are the intersection, over the atoms containing \(v\), of the values their tries allow below \(t\); it iterates the smallest set and probes the others in expected constant time.

Theorem. Generic Join lists each instance once, and iterates at most \(n\,\mathrm{AGM}\) values and makes at most \(m\,n\,\mathrm{AGM}\) probes.

Proof. A binding is extended at depth \(d\) exactly when its first \(d\) variables agree with a tuple of every atom on the variables they share, so each complete binding is an instance and each instance is reached by one path, the values of its variables in order. Let \(v\) be the variable at depth \(d\) and \(E_v\) the atoms containing it. For a prefix \(t\) of the first \(d - 1\) variables, the values iterated are \(\min_{e \in E_v} |R_e[t]|\), where \(R_e[t]\) is the set of values of \(v\) in the tuples of \(R_e\) that agree with \(t\). Since \(\sum_{e \in E_v} x_e \ge 1\), \(\min_e |R_e[t]| \le \prod_{e \in E_v} |R_e[t]|^{x_e}\), and summing over the prefixes that survive, Hölder's inequality bounds the total by the AGM bound of the first \(d\) variables under the restricted cover, which is at most \(\mathrm{AGM}\) because restriction and projection do not grow a relation (Ngo, Re and Rudra 2014, the analysis of Generic Join; Ngo, Porat, Re and Rudra 2018, theorem 5.1). Over \(n\) depths this gives \(n\,\mathrm{AGM}\) values, each probed in at most \(m - 1\) other sets. QED

The bound holds under the conditions stated in the claim: the rule is fixed and the relations grow (data complexity); attributes are flat after matching; hashing costs expected constant time; and the side condition, evaluated on each complete binding, filters the output and is outside the bound. Generic Join is worst-case optimal, not instance optimal: on some inputs another algorithm does less (Ngo, Porat, Re and Rudra 2018, section 7). The indexed chart of a plan joins one premise at a time, and on the triangle with a hub value or a skewed triangle that does \(\Theta(N^2)\) work against the \(N^{3/2}\) bound, which the checks measure.

Aggregates by elimination

For a commutative semiring the aggregate of a body, grouped by the conclusion's variables \(F\), is \(\bigoplus_{\bar y} w \otimes \bigotimes_e \phi_e\), the sum over the other variables \(\bar y\) of the products of the premise weights. Eliminating \(y\) joins the factors that contain it and sums it away:

\[ \bigoplus_{y} \bigotimes_{e} \phi_e = \Big(\bigotimes_{e \not\ni y} \phi_e\Big) \otimes \bigoplus_{y} \bigotimes_{e \ni y} \phi_e . \]

Theorem. If \(\oplus\) is associative and commutative, \(\otimes\) is associative and commutative with unit, and \(\otimes\) distributes over \(\oplus\), every order of eliminating the variables of \(\bar y\) gives the aggregate.

Proof. The display is distributivity applied to the factors free of \(y\), after commuting them to the front; the result is a function of the remaining variables. Repeating it for each variable of the order, and joining the remaining factors over \(F\), gives the sum over \(\bar y\) of the products. Since \(\oplus\) is associative and commutative, summing the variables in one order or another, or all at once, gives the same value. QED

There is one aggregate, the sum, over the variables not in the conclusion; so every order of them is semantically equivalent, the condition that FAQ needs for mixed aggregates (Abo Khamis, Ngo and Rudra 2016) holds trivially, and no product aggregate arises. The laws used are ELIMINATION_LAWS; each must be proved or decided by the algebra's own claims, so a MatrixSemiring, whose product does not commute, is refused, and its aggregate is taken by enumerate_aggregate, which multiplies in premise order and needs only ENUMERATION_LAWS.

A side condition reads some variables. When the first of them is eliminated, the factors covering all of them are joined into one bag, and the condition filters the bag before the variable is summed out; this is the elimination of the product of the factors with the condition's indicator, which is a factor over those variables. A condition on conclusion variables only filters the output.

Each EliminationStep records its bag and a fractional cover of the bag by the body's atoms. The bag's join has at most that cover's bound of tuples, since it lies in the projection of the body's join; the largest is \(W\) of the claim. The Elimination records the order, the induced width (the largest bag less one) and the fractional width (the largest cover weight). The order is chosen by elimination_order, smallest bag first; finding an order of least width is NP-hard (Arnborg, Corneil and Proskurowski 1987), so the widths are of the chosen order and are not claimed least. Under the exponential time hypothesis, for classes of bounded arity no algorithm beats treewidth by more than a logarithmic factor in the exponent (Marx 2010), which is why the claim's status is conditional.

On the star \(r_1(x, y_1), r_2(x, y_2), r_3(x, y_3)\) with one value of \(x\) of degree \(N\), there are \(N^3\) instances; elimination removes each \(y_i\) in a bag \(\{x, y_i\}\) and does linear work.

References

  • Abo Khamis, M., Ngo, H. Q., and Rudra, A. (2016). FAQ: questions asked frequently. PODS, 13-28. doi:10.1145/2902251.2902280
  • Arnborg, S., Corneil, D. G., and Proskurowski, A. (1987). Complexity of finding embeddings in a k-tree. SIAM Journal on Algebraic Discrete Methods 8(2), 277-284. doi:10.1137/0608024
  • Atserias, A., Grohe, M., and Marx, D. (2013). Size bounds and query plans for relational joins. SIAM Journal on Computing 42(4), 1737-1767. doi:10.1137/110859440
  • Marx, D. (2010). Can you beat treewidth? Theory of Computing 6, 85-112. doi:10.4086/toc.2010.v006a005
  • Ngo, H. Q., Porat, E., Re, C., and Rudra, A. (2018). Worst-case optimal join algorithms. Journal of the ACM 65(3), 1-40. doi:10.1145/3180143
  • Ngo, H. Q., Re, C., and Rudra, A. (2014). Skew strikes back: new developments in the theory of join algorithms. SIGMOD Record 42(4), 5-16. doi:10.1145/2590989.2590991

joins

Joins of rule bodies: worst-case optimal for full output, elimination for aggregates.

A rule body is a conjunctive query. Each premise is an atom whose attributes are the variables of its pattern; an item of the premise's form that matches the pattern is a tuple of the atom's relation, so a nested constructor pattern is flattened into the variables of its slots. The side condition is a filter on the variables it reads.

generic_join lists every instance of the body, one variable at a time: the values of a variable are the intersection, over the atoms that contain it, of the values their tuples allow given the variables already bound, found by iterating the smallest and probing the others. Its work is at most the number of atoms and variables times the AGM bound of the query (Ngo, Porat, Re and Rudra 2018, with the Generic Join of Ngo, Re and Rudra 2014), and agm_bound computes that bound for a fractional edge cover. The bound is tight in the worst case over inputs of the same sizes (Atserias, Grohe and Marx 2013), so no algorithm listing the output is better in data complexity; it is not instance optimal.

eliminate computes the sum, grouped by the conclusion's variables, of the products of the premise weights, without listing the body's instances: each variable that is summed out is removed by joining only the factors that contain it and summing it away (InsideOut, Abo Khamis, Ngo and Rudra 2016). Reordering products and sums this way needs a commutative product that distributes over a commutative sum, so it is refused for weights that keep their order. The order of elimination is chosen by a greedy rule and recorded with its widths; it is not claimed to be optimal, which is NP-hard to find.

References

Ngo, H. Q., Porat, E., Re, C., and Rudra, A. (2018). Worst-case optimal join algorithms. Journal of the ACM 65(3), 1-40. doi:10.1145/3180143

Ngo, H. Q., Re, C., and Rudra, A. (2014). Skew strikes back: new developments in the theory of join algorithms. SIGMOD Record 42(4), 5-16. doi:10.1145/2590989.2590991

Atserias, A., Grohe, M., and Marx, D. (2013). Size bounds and query plans for relational joins. SIAM Journal on Computing 42(4), 1737-1767. doi:10.1137/110859440

Abo Khamis, M., Ngo, H. Q., and Rudra, A. (2016). FAQ: questions asked frequently. PODS, 13-28. doi:10.1145/2902251.2902280

ELIMINATION_LAWS module-attribute

The laws elimination reorders by: a commutative semiring on one domain.

Sums are regrouped and reordered, products are regrouped and reordered, a sum is moved inside the product of the factors that do not contain its letter, an absent term is the zero and annihilates its product, a sum over several axes is taken one axis at a time, and a product of no factors is the unit.

ENUMERATION_LAWS module-attribute

ENUMERATION_LAWS: tuple[Law, ...] = (PLUS_ASSOCIATIVE, PLUS_COMMUTATIVE, TIMES_ASSOCIATIVE)

The laws a sum of products in premise order uses.

GENERIC_JOIN_WORK module-attribute

GENERIC_JOIN_WORK = ComplexityClaim(query='every instance of one rule body', parameters=(ComplexityParameter(name='N', meaning="tuples of the atoms' relations"), ComplexityParameter(name='AGM', meaning='the bound of a fractional edge cover of the body'), ComplexityParameter(name='n', meaning='variables of the body'), ComplexityParameter(name='m', meaning='atoms of the body')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='N + m n AGM', status=ProvedOptimal(lower_bound='AGM in the worst case over relations of the same sizes', model=ALGEBRA_OPERATIONS, sources=(_AGM, _NPRR, _GENERIC))), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='N + n', status=ProvedOptimal(lower_bound='N', model=ALGEBRA_OPERATIONS, sources=(_READ,)))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='the query is read off the rule in its size'), PhaseInapplicable(phase=Phase.DIFFERENTIATION, reason='instances are listed, not weighed'), PhaseInapplicable(phase=Phase.REFIT, reason='instances depend on the items only, not on weights')), conditions=('data complexity: the rule is fixed and the relations grow', 'a natural join over flat attributes; a nested constructor pattern is flattened by matching, and a sum of two variables is refused', 'the side condition filters the output and is outside the bound', 'expected constant-time hashing', 'worst-case optimal, not instance optimal'))

The cost of listing a rule body's instances by Generic Join.

ELIMINATION_WORK module-attribute

ELIMINATION_WORK = ComplexityClaim(query='sum of products of one rule body, grouped by its conclusion', parameters=(ComplexityParameter(name='N', meaning="tuples of the atoms' relations"), ComplexityParameter(name='W', meaning="the largest bound of a bag's cover over the chosen order"), ComplexityParameter(name='F', meaning='conclusions'), ComplexityParameter(name='n', meaning='variables of the body'), ComplexityParameter(name='m', meaning='atoms of the body')), model=ALGEBRA_OPERATIONS, bounds=(ComplexityBound(phase=Phase.EXECUTION, resource='time', expression='N + n m W + F', status=Conditional(hypothesis='the exponential time hypothesis: for classes of bounded arity no algorithm beats treewidth by more than a logarithmic factor in the exponent', sources=(_FAQ, _MARX))), ComplexityBound(phase=Phase.EXECUTION, resource='space', expression='N + W + F', status=Conditional(hypothesis='as for time', sources=(_FAQ,))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='time', expression='N + n m W + F', status=Conditional(hypothesis='as for execution', sources=(_FAQ,))), ComplexityBound(phase=Phase.DIFFERENTIATION, resource='space', expression='N + n m W + F', status=Conditional(hypothesis='the autograd tape holds every product and sum', sources=(_FAQ,)))), inapplicable=(PhaseInapplicable(phase=Phase.CONSTRUCTION, reason='the order is chosen from the rule in its size'), PhaseInapplicable(phase=Phase.REFIT, reason='a refit is one more elimination at the new weights')), conditions=('a commutative semiring on one domain sharing zero and one: the laws of ELIMINATION_LAWS, each proved or decided', 'not for weights that keep their order, effects, or algebras that are not semirings; those are summed by enumeration in premise order', 'the order is greedy and its widths are recorded; an order of least width is NP-hard to find and is not claimed', 'the side condition joins the factors covering its variables into one bag'))

The cost of aggregating a rule body by variable elimination.

JoinRefusal

Bases: str, Enum

Why a join is refused.

JoinRefused

JoinRefused(code: JoinRefusal, reason: str)

Bases: ValueError

A join is refused, with the reason.

PARAMETER DESCRIPTION
code

The kind of reason.

TYPE: JoinRefusal

reason

The reason.

TYPE: str

Source code in src/quivers/stochastic/joins.py
def __init__(self, code: JoinRefusal, reason: str) -> None:
    super().__init__(f"{code.value}: {reason}")
    self.code = code
    self.reason = reason

Atom didactic-model

Atom(*, premise: int, family: FamilyId = field(opaque=True, extras=OPAQUE_BY_VALUE), arguments: tuple[IndexTerm, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), variables: tuple[str, ...] = ())

Bases: ValueModel

One premise as a relation over its pattern's variables.

PARAMETER DESCRIPTION
premise

The premise's position.

TYPE: int

family

Its form.

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

arguments

Its pattern.

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

variables

The pattern's variables, in the query's order.

TYPE: tuple of str DEFAULT: ()

BodyQuery didactic-model

BodyQuery(*, rule: Rule = field(opaque=True, extras=OPAQUE_BY_VALUE), atoms: tuple[Atom, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), variables: tuple[str, ...] = (), free: tuple[str, ...] = (), filtered: tuple[str, ...] = ())

Bases: ValueModel

A rule body as a conjunctive query.

PARAMETER DESCRIPTION
rule

The rule.

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

atoms

One per premise.

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

variables

Every variable of the premises, in order of first occurrence.

TYPE: tuple of str DEFAULT: ()

free

The variables of the conclusion, which an aggregate groups by.

TYPE: tuple of str DEFAULT: ()

filtered

The variables the side condition reads.

TYPE: tuple of str DEFAULT: ()

Relation didactic-model

Relation(*, atom: Atom = field(opaque=True, extras=OPAQUE_BY_VALUE), tuples: dict[tuple[Ground, ...], Item] = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The tuples of one atom: each item matching it, by its variables' values.

Matching determines an item from its tuple, since the item's arguments are the pattern evaluated at the tuple.

PARAMETER DESCRIPTION
atom

The atom.

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

tuples

Each tuple, over the atom's variables in order, and its item.

TYPE: dict of tuple of Ground to Item DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

AGMBound didactic-model

AGMBound(*, variables: tuple[str, ...] = (), sizes: tuple[int, ...] = (), cover: tuple[Rational, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

A fractional edge cover and the size bound it gives.

For relations of sizes N_e and weights x_e >= 0 that cover every variable (the weights of the atoms containing it sum to one or more), the join has at most prod_e N_e^{x_e} tuples (Atserias, Grohe and Marx 2013). The cover is exact rationals checked to cover; it comes from a linear program minimizing the bound, and the bound holds whether or not it is the minimum.

PARAMETER DESCRIPTION
variables

The variables covered.

TYPE: tuple of str DEFAULT: ()

sizes

The relation sizes.

TYPE: tuple of int DEFAULT: ()

cover

The weight of each relation.

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

value property

value: float

The bound prod_e N_e^{x_e}, zero when a covering relation is empty.

RETURNS DESCRIPTION
float

The bound.

rho property

rho: Fraction

The cover's total weight, the bound's exponent when every size is N.

RETURNS DESCRIPTION
Fraction

sum_e x_e.

JoinWork didactic-model

JoinWork(*, iterated: int = 0, probes: int = 0, tuples: int = 0, outputs: int = 0, conditions: int = 0, products: int = 0, sums: int = 0)

Bases: ValueModel

Counters of a join.

PARAMETER DESCRIPTION
iterated

Values iterated from the smallest set of each intersection.

TYPE: int DEFAULT: 0

probes

Membership tests in the other sets.

TYPE: int DEFAULT: 0

tuples

Partial and complete bindings extended.

TYPE: int DEFAULT: 0

outputs

Complete bindings produced.

TYPE: int DEFAULT: 0

conditions

Side conditions evaluated.

TYPE: int DEFAULT: 0

products

Products of the algebra computed.

TYPE: int DEFAULT: 0

sums

Sums of the algebra computed.

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

Values iterated and probes as key comparisons, the algebra's sums and products, each measured; a join divides nothing.

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

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

    Returns
    -------
    WorkReport
        Values iterated and probes as key comparisons, the algebra's
        sums and products, each measured; a join divides nothing.
    """
    return WorkReport(
        phase=phase,
        key_comparisons=self.iterated + self.probes,
        scalar_sums=self.sums,
        scalar_products=self.products,
        measured=measuring(
            {
                WorkField.KEY_COMPARISONS,
                WorkField.SCALAR_SUMS,
                WorkField.SCALAR_PRODUCTS,
                WorkField.SCALAR_DIVISIONS,
            }
        ),
    )

JoinCounter

JoinCounter()

Bases: TrieCounter

Mutable counters of a join, read out as a JoinWork.

Source code in src/quivers/stochastic/joins.py
def __init__(self) -> None:
    super().__init__()
    self.outputs = 0
    self.conditions = 0
    self.products = 0
    self.sums = 0

report

report() -> JoinWork

The counts so far.

RETURNS DESCRIPTION
JoinWork

The counters.

Source code in src/quivers/stochastic/joins.py
def report(self) -> JoinWork:
    """The counts so far.

    Returns
    -------
    JoinWork
        The counters.
    """
    return JoinWork(
        iterated=self.iterated,
        probes=self.probes,
        tuples=self.tuples,
        outputs=self.outputs,
        conditions=self.conditions,
        products=self.products,
        sums=self.sums,
    )

EliminationStep didactic-model

EliminationStep(*, variable: str, bag: tuple[str, ...] = (), cover: AGMBound = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: QiecModel

One variable summed out.

PARAMETER DESCRIPTION
variable

The variable.

TYPE: str

bag

The variables of the factors joined to remove it.

TYPE: tuple of str DEFAULT: ()

cover

A fractional cover of the bag by the body's atoms.

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

Elimination didactic-model

Elimination(*, values: dict[Item, Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), algorithm: Literal['variable elimination', 'enumeration in premise order'], order: tuple[str, ...] = (), steps: tuple[EliminationStep, ...] = field(default=(), opaque=True, extras=OPAQUE_BY_VALUE), width: int = 0, fractional_width: Rational = field(default=Rational(numerator=0), opaque=True, extras=OPAQUE_BY_VALUE), work: JoinWork = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

The aggregate of a rule body, and how it was computed.

PARAMETER DESCRIPTION
values

The sum, for each conclusion, of the rule weight times the product of the premise weights over the body's instances.

TYPE: dict of Item to torch.Tensor DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

algorithm

"variable elimination" or "enumeration in premise order".

TYPE: str

order

The variables summed out, in order.

TYPE: tuple of str DEFAULT: ()

steps

Each step, with its bag and cover.

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

width

The largest bag less one, the induced width of the order.

TYPE: int DEFAULT: 0

fractional_width

The largest cover weight of a bag.

TYPE: Rational DEFAULT: field(default=Rational(numerator=0), opaque=True, extras=OPAQUE_BY_VALUE)

work

The counters.

TYPE: JoinCounter DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

body_query

body_query(rule: Rule) -> BodyQuery

The conjunctive query of a rule body.

PARAMETER DESCRIPTION
rule

The rule.

TYPE: Rule

RETURNS DESCRIPTION
BodyQuery

Its query.

RAISES DESCRIPTION
JoinRefused

If a premise has a sum of two variables, whose matches are not a relation of the premise's items alone; or a premise has hypotheses.

Source code in src/quivers/stochastic/joins.py
def body_query(rule: Rule) -> BodyQuery:
    """The conjunctive query of a rule body.

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

    Returns
    -------
    BodyQuery
        Its query.

    Raises
    ------
    JoinRefused
        If a premise has a sum of two variables, whose matches are not
        a relation of the premise's items alone; or a premise has
        hypotheses.
    """
    order: list[str] = []
    atoms: list[Atom] = []
    for position, premise in enumerate(rule.premises):
        if premise.hypotheses:
            raise JoinRefused(
                JoinRefusal.NOT_FLAT,
                f"premise {position} of {rule.name} has hypotheses",
            )
        names: list[str] = []
        for argument in premise.judgment.arguments:
            if not flat_pattern(argument):
                raise JoinRefused(
                    JoinRefusal.NOT_FLAT,
                    f"premise {position} of {rule.name} has a sum of two variables",
                )
            for name in sorted(index_variables(argument)):
                if name not in names:
                    names.append(name)
                if name not in order:
                    order.append(name)
        atoms.append(
            Atom(
                premise=position,
                family=premise.judgment.family,
                arguments=premise.judgment.arguments,
                variables=tuple(names),
            )
        )
    free: list[str] = []
    for argument in rule.conclusion.arguments:
        for name in sorted(index_variables(argument)):
            if name not in free:
                free.append(name)
    condition = rule.side_condition
    return BodyQuery(
        rule=rule,
        atoms=tuple(atoms),
        variables=tuple(order),
        free=tuple(free),
        filtered=() if condition is None else tuple(condition.arguments),
    )

relations

relations(query: BodyQuery, items: Iterable[Item]) -> tuple[Relation, ...]

The relation of every atom over a set of items.

PARAMETER DESCRIPTION
query

The query.

TYPE: BodyQuery

items

The items; repeats count once.

TYPE: Iterable of Item

RETURNS DESCRIPTION
tuple of Relation

One per atom.

Source code in src/quivers/stochastic/joins.py
def relations(query: BodyQuery, items: Iterable[Item]) -> tuple[Relation, ...]:
    """The relation of every atom over a set of items.

    Parameters
    ----------
    query : BodyQuery
        The query.
    items : Iterable of Item
        The items; repeats count once.

    Returns
    -------
    tuple of Relation
        One per atom.
    """
    by_family: dict[FamilyId, list[Item]] = {}
    for item in dict.fromkeys(items):
        by_family.setdefault(item.family, []).append(item)
    found: list[Relation] = []
    for atom in query.atoms:
        tuples: dict[tuple[Ground, ...], Item] = {}
        for item in by_family.get(atom.family, []):
            binding: Binding = {}
            if all(
                match_index(pattern, value, binding)
                for pattern, value in zip(atom.arguments, item.arguments, strict=True)
            ):
                tuples[tuple(binding[name] for name in atom.variables)] = item
        found.append(Relation(atom=atom, tuples=tuples))
    return tuple(found)

agm_bound

agm_bound(variables: Sequence[str], edges: Sequence[Sequence[str]], sizes: Sequence[int]) -> AGMBound

A fractional edge cover of variables by relations, and its bound.

PARAMETER DESCRIPTION
variables

The variables to cover.

TYPE: Sequence of str

edges

The variables of each relation.

TYPE: Sequence of Sequence of str

sizes

The size of each relation.

TYPE: Sequence of int

RETURNS DESCRIPTION
AGMBound

A cover; with every size at least two, of least bound up to the rounding of the program's solution, which is then repaired to cover exactly.

RAISES DESCRIPTION
JoinRefused

If a variable is in no relation.

Source code in src/quivers/stochastic/joins.py
def agm_bound(
    variables: Sequence[str],
    edges: Sequence[Sequence[str]],
    sizes: Sequence[int],
) -> AGMBound:
    """A fractional edge cover of variables by relations, and its bound.

    Parameters
    ----------
    variables : Sequence of str
        The variables to cover.
    edges : Sequence of Sequence of str
        The variables of each relation.
    sizes : Sequence of int
        The size of each relation.

    Returns
    -------
    AGMBound
        A cover; with every size at least two, of least bound up to the
        rounding of the program's solution, which is then repaired to
        cover exactly.

    Raises
    ------
    JoinRefused
        If a variable is in no relation.
    """
    names = list(variables)
    for name in names:
        if not any(name in edge for edge in edges):
            raise JoinRefused(JoinRefusal.NOT_FLAT, f"{name!r} is in no relation")
    if not names:
        return AGMBound(
            variables=(),
            sizes=tuple(sizes),
            cover=tuple(Rational.of(0) for _ in sizes),
        )

    import numpy
    from scipy.optimize import linprog

    costs = numpy.array([math.log(max(size, 2)) for size in sizes])
    matrix = numpy.array(
        [[-1.0 if name in edge else 0.0 for edge in edges] for name in names]
    )
    solution = linprog(
        costs,
        A_ub=matrix,
        b_ub=-numpy.ones(len(names)),
        bounds=[(0, None)] * len(edges),
        method="highs",
    )
    weights = [
        Fraction(max(float(value), 0.0)).limit_denominator(1024) for value in solution.x
    ]
    for name in names:
        covered = sum(
            (
                weight
                for weight, edge in zip(weights, edges, strict=True)
                if name in edge
            ),
            Fraction(0),
        )
        if covered < 1:
            index = min(
                (i for i, edge in enumerate(edges) if name in edge),
                key=lambda i: sizes[i],
            )
            weights[index] += 1 - covered
    return AGMBound(
        variables=tuple(names),
        sizes=tuple(sizes),
        cover=tuple(Rational.of(weight) for weight in weights),
    )

generic_join

generic_join(query: BodyQuery, tables: Sequence[Relation], presentation: RulePresentation, *, order: Sequence[str] | None = None, work: JoinCounter | None = None) -> Iterator[tuple[Binding, tuple[Item, ...]]]

Every instance of a rule body over the relations, by Generic Join.

Variables are bound one at a time in order; each takes the values in the intersection, over the atoms containing it, of the values their tries allow below the variables already bound. The side condition filters each complete binding.

PARAMETER DESCRIPTION
query

The query.

TYPE: BodyQuery

tables

One relation per atom, in atom order.

TYPE: Sequence of Relation

presentation

The presentation, for the side condition.

TYPE: RulePresentation

order

The order of the variables; the query's by default.

TYPE: Sequence of str or None DEFAULT: None

work

Counters to add to.

TYPE: JoinCounter or None DEFAULT: None

YIELDS DESCRIPTION
tuple of Binding and tuple of Item

Each instance's binding and its premise items in premise order.

RAISES DESCRIPTION
JoinRefused

If order is not an order of the query's variables.

Source code in src/quivers/stochastic/joins.py
def generic_join(
    query: BodyQuery,
    tables: Sequence[Relation],
    presentation: RulePresentation,
    *,
    order: Sequence[str] | None = None,
    work: JoinCounter | None = None,
) -> Iterator[tuple[Binding, tuple[Item, ...]]]:
    """Every instance of a rule body over the relations, by Generic Join.

    Variables are bound one at a time in ``order``; each takes the
    values in the intersection, over the atoms containing it, of the
    values their tries allow below the variables already bound. The side
    condition filters each complete binding.

    Parameters
    ----------
    query : BodyQuery
        The query.
    tables : Sequence of Relation
        One relation per atom, in atom order.
    presentation : RulePresentation
        The presentation, for the side condition.
    order : Sequence of str or None
        The order of the variables; the query's by default.
    work : JoinCounter or None
        Counters to add to.

    Yields
    ------
    tuple of Binding and tuple of Item
        Each instance's binding and its premise items in premise order.

    Raises
    ------
    JoinRefused
        If ``order`` is not an order of the query's variables.
    """
    chosen = tuple(query.variables if order is None else order)
    if sorted(chosen) != sorted(query.variables):
        raise JoinRefused(JoinRefusal.ORDER, f"{chosen} orders other variables")
    counters = JoinCounter() if work is None else work
    position = {name: index for index, name in enumerate(chosen)}
    tries = [_trie(table, position) for table in tables]
    if any(not variables and isinstance(node, dict) for variables, node in tries):
        return
    containing = [
        [index for index, (variables, _) in enumerate(tries) if name in variables]
        for name in chosen
    ]
    yield from _descend(
        query, presentation, chosen, containing, [node for _, node in tries], counters
    )

elimination_order

elimination_order(query: BodyQuery) -> tuple[str, ...]

A greedy order of the variables to sum out: fewest neighbours first.

The order is quivers.core.elimination.elimination_order over the atoms' variables and the side condition's, by the number of variables of each bag, ties in the query's order. Finding an order of least width is NP-hard, so this order's widths are recorded, not claimed least.

PARAMETER DESCRIPTION
query

The query.

TYPE: BodyQuery

RETURNS DESCRIPTION
tuple of str

The variables not in the conclusion, in elimination order.

Source code in src/quivers/stochastic/joins.py
def elimination_order(query: BodyQuery) -> tuple[str, ...]:
    """A greedy order of the variables to sum out: fewest neighbours first.

    The order is `quivers.core.elimination.elimination_order` over the
    atoms' variables and the side condition's, by the number of
    variables of each bag, ties in the query's order. Finding an order
    of least width is NP-hard, so this order's widths are recorded, not
    claimed least.

    Parameters
    ----------
    query : BodyQuery
        The query.

    Returns
    -------
    tuple of str
        The variables not in the conclusion, in elimination order.
    """
    edges = [set(atom.variables) for atom in query.atoms]
    if query.filtered:
        edges.append(set(query.filtered))
    return greedy_order(query.variables, edges, set(query.free))

eliminate

eliminate(query: BodyQuery, tables: Sequence[Relation], presentation: RulePresentation, algebra: OrderPreservingSemiring, weights: Mapping[Item, Tensor], *, like: Tensor, rule_weight: Tensor | None = None, order: Sequence[str] | None = None) -> Elimination

The aggregate of a rule body by eliminating its summed variables.

Each step joins the factors containing the variable (and, while the side condition is pending, the factors covering its variables, so that it filters the bag), sums the variable out, and replaces those factors by the result. What is left, over the conclusion's variables, is joined and multiplied by the rule weight.

PARAMETER DESCRIPTION
query

The query.

TYPE: BodyQuery

tables

One relation per atom.

TYPE: Sequence of Relation

presentation

The presentation, for the side condition.

TYPE: RulePresentation

algebra

The algebra.

TYPE: OrderPreservingSemiring

weights

The weight of each premise item; a missing one is the unit.

TYPE: Mapping of Item to torch.Tensor

like

The dtype and device of the unit.

TYPE: Tensor

rule_weight

The rule's weight; the unit by default.

TYPE: Tensor or None DEFAULT: None

order

The variables to sum out, in order; elimination_order by default.

TYPE: Sequence of str or None DEFAULT: None

RETURNS DESCRIPTION
Elimination

The weight of each conclusion, the order, and its widths.

RAISES DESCRIPTION
JoinRefused

If the algebra does not establish ELIMINATION_LAWS, or order is not an order of the summed variables.

Source code in src/quivers/stochastic/joins.py
def eliminate(
    query: BodyQuery,
    tables: Sequence[Relation],
    presentation: RulePresentation,
    algebra: OrderPreservingSemiring,
    weights: Mapping[Item, torch.Tensor],
    *,
    like: torch.Tensor,
    rule_weight: torch.Tensor | None = None,
    order: Sequence[str] | None = None,
) -> Elimination:
    """The aggregate of a rule body by eliminating its summed variables.

    Each step joins the factors containing the variable (and, while the
    side condition is pending, the factors covering its variables, so
    that it filters the bag), sums the variable out, and replaces those
    factors by the result. What is left, over the conclusion's
    variables, is joined and multiplied by the rule weight.

    Parameters
    ----------
    query : BodyQuery
        The query.
    tables : Sequence of Relation
        One relation per atom.
    presentation : RulePresentation
        The presentation, for the side condition.
    algebra : OrderPreservingSemiring
        The algebra.
    weights : Mapping of Item to torch.Tensor
        The weight of each premise item; a missing one is the unit.
    like : torch.Tensor
        The dtype and device of the unit.
    rule_weight : torch.Tensor or None
        The rule's weight; the unit by default.
    order : Sequence of str or None
        The variables to sum out, in order; `elimination_order` by
        default.

    Returns
    -------
    Elimination
        The weight of each conclusion, the order, and its widths.

    Raises
    ------
    JoinRefused
        If the algebra does not establish `ELIMINATION_LAWS`, or
        ``order`` is not an order of the summed variables.
    """
    _require_laws(algebra, ELIMINATION_LAWS)
    summed = [name for name in query.variables if name not in query.free]
    chosen = elimination_order(query) if order is None else tuple(order)
    if sorted(chosen) != sorted(summed):
        raise JoinRefused(JoinRefusal.ORDER, f"{chosen} does not order {summed}")
    work = JoinCounter()
    factors = [
        _Factor(
            variables=table.atom.variables,
            table={
                values: weights.get(item, _unit(algebra, like))
                for values, item in table.tuples.items()
            },
        )
        for table in tables
    ]
    sizes = [len(table.tuples) for table in tables]
    pending = query.rule.side_condition is not None
    steps: list[EliminationStep] = []
    for name in chosen:
        joined = [factor for factor in factors if name in factor.variables]
        filtering = pending and name in query.filtered
        needed = set().union(*(factor.variables for factor in joined))
        if filtering:
            needed |= set(query.filtered)
            for factor in factors:
                if factor not in joined and set(factor.variables) & (
                    needed - set().union(*(f.variables for f in joined))
                ):
                    joined.append(factor)
                    needed |= set(factor.variables)
        bag = tuple(variable for variable in query.variables if variable in needed)
        rest = tuple(variable for variable in bag if variable != name)
        table: dict[tuple[Ground, ...], torch.Tensor] = {}
        for binding, product in _join_factors(joined, bag, algebra, work):
            if filtering:
                work.conditions += 1
                if not side_condition_holds(presentation, query.rule, binding):
                    continue
            _add(algebra, table, tuple(binding[v] for v in rest), product, work)
        factors = [factor for factor in factors if factor not in joined]
        factors.append(_Factor(variables=rest, table=table))
        if filtering:
            pending = False
        edges = [tuple(v for v in atom.variables if v in bag) for atom in query.atoms]
        steps.append(
            EliminationStep(variable=name, bag=bag, cover=agm_bound(bag, edges, sizes))
        )
    output: dict[tuple[Ground, ...], torch.Tensor] = {}
    weight = _unit(algebra, like) if rule_weight is None else rule_weight
    for binding, product in _join_factors(factors, query.free, algebra, work):
        if pending:
            work.conditions += 1
            if not side_condition_holds(presentation, query.rule, binding):
                continue
        work.products += 1
        work.outputs += 1
        _add(
            algebra,
            output,
            tuple(binding[v] for v in query.free),
            algebra.tensor_op(weight, product),
            work,
        )
    return Elimination(
        values=_conclusions(query, output, algebra, work),
        algorithm="variable elimination",
        order=chosen,
        steps=tuple(steps),
        width=max((len(step.bag) - 1 for step in steps), default=0),
        fractional_width=Rational.of(
            max((step.cover.rho for step in steps), default=Fraction(0))
        ),
        work=work.report(),
    )

enumerate_aggregate

enumerate_aggregate(query: BodyQuery, tables: Sequence[Relation], presentation: RulePresentation, algebra: OrderPreservingSemiring, weights: Mapping[Item, Tensor], *, like: Tensor, rule_weight: Tensor | None = None, order: Sequence[str] | None = None) -> Elimination

The aggregate of a rule body by listing its instances.

Each instance's product is taken in premise order, then the rule weight, as a derivation's factors are read, so the product need not commute; the cost is that of generic_join, the number of instances at worst.

PARAMETER DESCRIPTION
query

The query.

TYPE: BodyQuery

tables

One relation per atom.

TYPE: Sequence of Relation

presentation

The presentation, for the side condition.

TYPE: RulePresentation

algebra

The algebra.

TYPE: OrderPreservingSemiring

weights

The weight of each premise item; a missing one is the unit.

TYPE: Mapping of Item to torch.Tensor

like

The dtype and device of the unit.

TYPE: Tensor

rule_weight

The rule's weight; the unit by default.

TYPE: Tensor or None DEFAULT: None

order

The join's variable order.

TYPE: Sequence of str or None DEFAULT: None

RETURNS DESCRIPTION
Elimination

The weight of each conclusion.

RAISES DESCRIPTION
JoinRefused

If the algebra does not establish ENUMERATION_LAWS.

Source code in src/quivers/stochastic/joins.py
def enumerate_aggregate(
    query: BodyQuery,
    tables: Sequence[Relation],
    presentation: RulePresentation,
    algebra: OrderPreservingSemiring,
    weights: Mapping[Item, torch.Tensor],
    *,
    like: torch.Tensor,
    rule_weight: torch.Tensor | None = None,
    order: Sequence[str] | None = None,
) -> Elimination:
    """The aggregate of a rule body by listing its instances.

    Each instance's product is taken in premise order, then the rule
    weight, as a derivation's factors are read, so the product need not
    commute; the cost is that of
    `generic_join`, the number of instances at worst.

    Parameters
    ----------
    query : BodyQuery
        The query.
    tables : Sequence of Relation
        One relation per atom.
    presentation : RulePresentation
        The presentation, for the side condition.
    algebra : OrderPreservingSemiring
        The algebra.
    weights : Mapping of Item to torch.Tensor
        The weight of each premise item; a missing one is the unit.
    like : torch.Tensor
        The dtype and device of the unit.
    rule_weight : torch.Tensor or None
        The rule's weight; the unit by default.
    order : Sequence of str or None
        The join's variable order.

    Returns
    -------
    Elimination
        The weight of each conclusion.

    Raises
    ------
    JoinRefused
        If the algebra does not establish `ENUMERATION_LAWS`.
    """
    _require_laws(algebra, ENUMERATION_LAWS)
    work = JoinCounter()
    weight = _unit(algebra, like) if rule_weight is None else rule_weight
    output: dict[tuple[Ground, ...], torch.Tensor] = {}
    for binding, premises in generic_join(
        query, tables, presentation, order=order, work=work
    ):
        total = weights.get(premises[0], _unit(algebra, like)) if premises else weight
        for item in premises[1:]:
            work.products += 1
            total = algebra.tensor_op(total, weights.get(item, _unit(algebra, like)))
        if premises:
            work.products += 1
            total = algebra.tensor_op(total, weight)
        _add(algebra, output, tuple(binding[v] for v in query.free), total, work)
    return Elimination(
        values=_conclusions(query, output, algebra, work),
        algorithm="enumeration in premise order",
        order=tuple(query.variables if order is None else order),
        work=work.report(),
    )