Algorithm Search⌘K

Algorithmadvanced

Answer set grounding

Also called ASP grounder, intelligent grounding.

Replaces variables of a safe ASP program by constants, producing only ground rules whose bodies can be true, by semi-naive evaluation.

Time
O(r · m^2 · c^k · d^2) worst
Space
O(m · r · c^k + d) extra
Where
c = the number of constants; d = the number of atoms in the domain; k = the largest number of variables in a rule; m = the largest number of positive body atoms in a rule; r = the number of rules
Properties
deterministic
Origin
Martin Gebser, Torsten Schaub, Sven Thiele, 2007

An answer set solver works on ground programs, but answer set programs are written with variables. A grounder replaces the variables by constants. The full instantiation, which tries every constant for every variable, is correct but much too large, so real grounders produce only the rule instances whose positive body can be true. They find these instances by semi-naive evaluation, as in Datalog, and then simplify the result with the atoms that are certainly true or certainly false. The output has the same stable models as the full instantiation, but it can still be exponential in the size of a rule.

In plain words

A rule with variables is a pattern for many rules, one for each way of filling in the variables with names from the program. Writing out every one of them is wasteful: most would talk about things that can never be true. The grounder works forward instead. It starts from the plain facts and asks which filled-in rules could fire, ignoring the "not" conditions for now. Each rule that could fire adds its conclusion to a growing list of possible facts. Then it repeats with the new facts only, so no filled-in rule is produced twice. When nothing new appears, it cleans up: conditions that are surely true are dropped, and rules that are surely blocked are deleted. The solver gets the small program that is left.

The problem

The input is a finite normal program PP with variables and constants but no function symbols. Its rules have the form h←b1,…,bm,not c1,…,not cnh \leftarrow b_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_n, where the head and the body literals are atoms such as edge(X,Y)\mathit{edge}(X, Y). The Herbrand universe is the set CC of constants of PP. A rule is safe if each variable in it occurs in some positive body atom bib_i. The full instantiation GG is the set of all ground instances of the rules over CC, and the stable models of PP are by definition those of GG (Gelfond and Lifschitz 1988). The output is a ground program with the same stable models as GG. Grounding is the first step before any propositional solver, such as the smodels search or conflict-driven solving.

The algorithm

  1. GROUND(P)
  2. 1if some rule of P is not safe then fail
  3. 2O ← ∅; Δ ← the heads of the rules with no positive body atom; emit these rules
  4. 3while Δ ≠ ∅ do
  5. 4N ← ∅
  6. 5for each rule r = h ← b1, …, bm, not c1, …, not cn with m ≥ 1, and each j = 1, …, m do
  7. 6for each substitution θ with biθ ∈ O for i < j, bjθ ∈ Δ, and biθ ∈ O ∪ Δ for i > j do
  8. 7emit rθ; N ← N ∪ {hθ}
  9. 8O ← O ∪ Δ; Δ ← N ∖ O
  10. 9D ← O; F ← the least model of the emitted rules that have no negative literal
  11. 10for each emitted rule h ← pos, not neg do
  12. 11if neg contains an atom of F then delete the rule ▷ it is blocked in every stable model
  13. 12else replace it by h ← (pos ∖ F), not (neg ∩ D) ▷ an atom outside D is never true
  14. 13return the remaining rules, without duplicates

Lines L2 to L8 evaluate the positive part G+G^+ of the program, with the negative literals ignored. The final OO is the domain DD, the least model of G+G^+, which contains every atom of every stable model. At line L6, jj is the first position of an atom that is new in the last round: the earlier positions take only older atoms. So each pair of a rule and a substitution is found in exactly one round and at one position. Real grounders compute the join at line L6 with indexes on the bound arguments, as in a hash join; the Python code scans the atoms of each predicate.

Example

The program describes reachability from a start node, and a guess of a colour for each reached node:

edge(a, b).   edge(b, c).   start(a).
reach(X) ← start(X).
reach(Y) ← reach(X), edge(X, Y).
red(X)   ← reach(X), not green(X).
green(X) ← reach(X), not red(X).

The constants are aa, bb and cc, so the full instantiation has 3+3+9+3+3=213 + 3 + 9 + 3 + 3 = 21 rules.

round emitted instances new atoms Δ\Delta
0 the three facts edge(a,b)\mathit{edge}(a, b), edge(b,c)\mathit{edge}(b, c), start(a)\mathit{start}(a)
1 reach(a)←start(a)\mathit{reach}(a) \leftarrow \mathit{start}(a) reach(a)\mathit{reach}(a)
2 reach(b)←reach(a),edge(a,b)\mathit{reach}(b) \leftarrow \mathit{reach}(a), \mathit{edge}(a, b), and the two colour rules for aa reach(b)\mathit{reach}(b), red(a)\mathit{red}(a), green(a)\mathit{green}(a)
3 reach(c)←reach(b),edge(b,c)\mathit{reach}(c) \leftarrow \mathit{reach}(b), \mathit{edge}(b, c), and the two colour rules for bb reach(c)\mathit{reach}(c), red(b)\mathit{red}(b), green(b)\mathit{green}(b)
4 the two colour rules for cc red(c)\mathit{red}(c), green(c)\mathit{green}(c)
5 none none: stop

The run emits 12 instances in 5 rounds. The definite rules give F={edge(a,b),edge(b,c),start(a),reach(a),reach(b),reach(c)}F = \{\mathit{edge}(a, b), \mathit{edge}(b, c), \mathit{start}(a), \mathit{reach}(a), \mathit{reach}(b), \mathit{reach}(c)\}. Line L12 removes the reach\mathit{reach} atoms from the bodies, so the output is the six facts of FF and six rules such as red(c)←not green(c)\mathit{red}(c) \leftarrow \mathit{not}\ \mathit{green}(c). It has 23=82^3 = 8 stable models, one for each colouring of the three nodes, the same as the 21 rules of the full instantiation.

The output can be exponential in the size of the input. The rule p(X1,…,Xk)←d(X1),…,d(Xk)p(X_1, \ldots, X_k) \leftarrow d(X_1), \ldots, d(X_k) with the facts d(a)d(a) and d(b)d(b) has 2k2^k instances, and each of them derives a different atom, so none can be left out:

kk 1 2 3 4 5 6 7 8
ground rules 4 6 10 18 34 66 130 258

Correctness

The correctness proof has the details. First, semi-naive evaluation gives the domain DD and exactly the instances whose positive body lies in DD, each once: each atom has one round in which it is new, and an instance is found in the round after the last of its body atoms became new, at the first position that holds such an atom. Second, the other instances do not matter. Every rule of a reduct GMG^M is a rule of G+G^+, so the least model of GMG^M lies in DD, and a rule with a body atom outside DD never fires. Third, simplification keeps the stable models. Every stable model contains the least model FF of the definite instances and lies in DD. For such a set MM, a rule with not c\mathit{not}\ c, c∈Fc \in F, is deleted by the reduct anyway, a literal not c\mathit{not}\ c with c∉Dc \notin D is true, and a body atom in FF is true, so the reducts have the same least model.

Proof: The grounder keeps the stable models of the full instantiationfull

Let PP be a finite normal program with variables and constants but no function symbols. A rule is h←b1,…,bm,not c1,…,not ckh \leftarrow b_1, \ldots, b_m, \mathit{not}\ c_1, \ldots, \mathit{not}\ c_k, where the bib_i form pos(r)\mathrm{pos}(r) and the cic_i form neg(r)\mathrm{neg}(r). The rule is safe if each variable of hh and of the cic_i occurs in some bib_i. Let CC be the set of constants of PP (the Herbrand universe). An instance of rr is the ground rule rθr\theta for a substitution θ\theta of its variables by constants of CC. The full instantiation GG is the set of all instances of all rules. Its stable models are by definition the stable models of PP (Gelfond and Lifschitz 1988).

For a ground program QQ, Q+Q^+ is the definite program of the rules h←pos(r)h \leftarrow \mathrm{pos}(r), QMQ^M is the Gelfond-Lifschitz reduct and lm\mathrm{lm} is the least model.

Step 1: semi-naive evaluation computes the domain and its instances

Let D=lm(G+)D = \mathrm{lm}(G^+), the domain, and let II be the set of instances rθ∈Gr\theta \in G with pos(rθ)⊆D\mathrm{pos}(r\theta) \subseteq D.

The code emits each rule with an empty positive body (by safety it is ground), sets Δ0\Delta_0 to the heads of these rules and O0=∅O_0 = \emptyset. In round t≥1t \geq 1, for each rule rr with positive body b1,…,bmb_1, \ldots, b_m and each position jj, it finds the substitutions θ\theta with biθ∈Ot−1b_i\theta \in O_{t-1} for i<ji < j, bjθ∈Δt−1b_j\theta \in \Delta_{t-1}, and biθ∈Ot−1∪Δt−1b_i\theta \in O_{t-1} \cup \Delta_{t-1} for i>ji > j. It emits rθr\theta. Then Ot=Ot−1∪Δt−1O_t = O_{t-1} \cup \Delta_{t-1}, and Δt\Delta_t is the set of new heads minus OtO_t. It stops when Δt=∅\Delta_t = \emptyset and returns OtO_t.

Lemma 1. The sets Δ0,Δ1,…\Delta_0, \Delta_1, \ldots are pairwise disjoint, and their union is DD. The emitted instances are exactly II, and each pair (rule, substitution) with rθ∈Ir\theta \in I is emitted exactly once.

Proof. For an atom aa in some Δt\Delta_t, call tt its entry round e(a)e(a). Each Δt\Delta_t is disjoint from OtO_t, which contains all earlier Δ\Delta's, so each atom has at most one entry round. Every emitted head is a head of a rule of G+G^+ whose body is in DD (by induction on tt), so the union is a subset of DD, and since DD is finite the loop stops. Conversely, let rθr\theta be an instance whose positive body atoms all have entry rounds, and let qq be the largest of them and jj the first position with e(bjθ)=qe(b_j\theta) = q. In round q+1q + 1, bjθ∈Δqb_j\theta \in \Delta_q, the atoms before jj have entry rounds below qq and are in OqO_q, and the atoms after jj are in Oq∪ΔqO_q \cup \Delta_q. So rθr\theta is emitted in round q+1q + 1 at position jj. It is emitted at no other round t+1t + 1 and position j′j': that would need e(bj′θ)=te(b_{j'}\theta) = t and all other entry rounds at most tt, so t=qt = q, and all entry rounds before j′j' below qq, so j′=jj' = j. The rules with an empty positive body are emitted once, before the loop, and never in it, because the loop runs over the positions of the positive body. The head of each emitted instance enters some Δ\Delta unless it is already in OO. So the set of atoms with an entry round is closed under G+G^+, and it contains the least model DD. With the first part, it is equal to DD, and the emitted instances are exactly those with positive body in DD, that is II. Because the rule is safe, all its variables occur in pos(r)\mathrm{pos}(r), so θ\theta is determined by pos(rθ)\mathrm{pos}(r\theta) and two different substitutions give two different instances. □\square

Step 2: instances outside the domain do not matter

Lemma 2. GG and II have the same stable models.

Proof. Let MM be any set of atoms. Each rule of GMG^M is a rule of G+G^+, so lm(GM)⊆D\mathrm{lm}(G^M) \subseteq D. A rule of GMG^M that comes from an instance outside II has a positive body atom outside DD, so it never fires in the computation of lm(GM)\mathrm{lm}(G^M). Hence lm(GM)=lm(IM)\mathrm{lm}(G^M) = \mathrm{lm}(I^M), since IM⊆GMI^M \subseteq G^M contains every rule that fires. So M=lm(GM)M = \mathrm{lm}(G^M) if and only if M=lm(IM)M = \mathrm{lm}(I^M). □\square

Step 3: simplification

Let FF be the least model of the instances in II with no negative literal. The simplified program SS is built from II as follows: delete each instance with some not c\mathit{not}\ c, c∈Fc \in F; in the others, delete each literal not c\mathit{not}\ c with c∉Dc \notin D and each positive body atom in FF; remove duplicate rules.

Lemma 3. Every stable model MM of II, and every stable model MM of SS, satisfies F⊆M⊆DF \subseteq M \subseteq D.

Proof. For II: the rules with no negative literal are unchanged in IMI^M, so F⊆lm(IM)=MF \subseteq \mathrm{lm}(I^M) = M, and M=lm(IM)⊆lm(I+)⊆DM = \mathrm{lm}(I^M) \subseteq \mathrm{lm}(I^+) \subseteq D. For SS: each head of SS is a head of II and lies in DD. The rules of II with no negative literal stay in SS with the atoms of FF removed from their bodies. Each atom of FF is derived from such rules whose bodies lie in FF, so in SS these rules are facts, and F⊆lm(SM)=MF \subseteq \mathrm{lm}(S^M) = M. □\square

Lemma 4. II and SS have the same stable models.

Proof. By Lemma 3 it is enough to compare the reducts for an MM with F⊆M⊆DF \subseteq M \subseteq D. Take an instance rr of II. If neg(r)\mathrm{neg}(r) meets FF, it meets MM, so IMI^M deletes rr, and SS does not contain it. Otherwise SS contains r′=(h,pos(r)∖F,neg(r)∩D)r' = (h, \mathrm{pos}(r) \setminus F, \mathrm{neg}(r) \cap D). Since M⊆DM \subseteq D, neg(r)∩M=∅\mathrm{neg}(r) \cap M = \emptyset exactly when (neg(r)∩D)∩M=∅(\mathrm{neg}(r) \cap D) \cap M = \emptyset. So IMI^M keeps h←pos(r)h \leftarrow \mathrm{pos}(r) exactly when SMS^M keeps h←pos(r)∖Fh \leftarrow \mathrm{pos}(r) \setminus F. For a set X⊇FX \supseteq F, the two bodies are true in XX together, so the two definite programs have the same immediate consequences on sets that contain FF. Both least models contain FF (Lemma 3), and each least model is the least fixpoint, so each one is a fixpoint of the other operator. Hence the two least models are equal. Duplicates do not change a reduct or a least model. □\square

Theorem. If every rule of PP is safe, then ground(P) has the same stable models as the full instantiation of PP over its constants.

Proof. By Lemma 1 the code computes DD and II, and simplify computes SS. Lemmas 2 and 4 give the claim. □\square

Size and time

A rule with kk variables has ∣C∣k|C|^k instances. The family p(X1,…,Xk)←d(X1),…,d(Xk)p(X_1, \ldots, X_k) \leftarrow d(X_1), \ldots, d(X_k) with the facts d(a)d(a) and d(b)d(b) has DD with 2k+22^k + 2 atoms, and every instance is in II and in SS as a fact. So the ground program has 2k+22^k + 2 rules for a non-ground program of size O(k)O(k), and no grounder that writes out the ground program can be faster than Ω(2k)\Omega(2^k) on this family.

Let rr be the number of rules, mm the largest number of positive body atoms of a rule, c=∣C∣c = |C|, kk the largest number of variables in a rule, and d=∣D∣d = |D|. There are at most r⋅ckr \cdot c^k instances. In one round, for each rule and each position jj, the join visits at most m⋅ckm \cdot c^k partial substitutions, and each visit scans the at most dd atoms of one predicate. There are at most d+1d + 1 rounds. So the code takes O(r⋅m2⋅ck⋅d2)O(r \cdot m^2 \cdot c^k \cdot d^2) time. Real grounders index the atoms on their bound arguments and order the body so that the join is cheaper, but the bound Ω(ck)\Omega(c^k) for the output remains.

What the tests check

The tests generate 300 random safe programs over the constants aa and bb, with the predicates p/1p/1, q/1q/1, r/2r/2 and s/0s/0, so at most 9 ground atoms. They check that the domain and the instances from semi-naive evaluation equal those computed from the least model of the positive part of the full instantiation, and that the count of emitted instances equals the number of (rule, substitution) pairs with positive body in the domain. On 200 more programs they check that the output of ground has the same stable models as the full instantiation, by brute force with the reduct. They also check that an unsafe rule raises an error, and that the exponential family above gives 2k+22^k + 2 rules for k=1,…,8k = 1, \ldots, 8.

Complexity

A rule with kk variables over cc constants has ckc^k instances, so a program with rr rules has at most r⋅ckr \cdot c^k instances, and the example family shows that the output can need 2k2^k rules for a program of size O(k)O(k). No grounder can avoid this, because the output itself is that large. For the Python code, each round, rule and position jj visits at most m⋅ckm \cdot c^k partial substitutions, each visit scans at most dd atoms, and there are at most d+1d + 1 rounds, which gives O(r⋅m2⋅ck⋅d2)O(r \cdot m^2 \cdot c^k \cdot d^2) time. The space is the stored instances plus the domain. For a fixed program, kk is a constant and grounding takes time polynomial in the number of facts. Deciding whether a normal program with variables has a stable model is NP-complete when the program is fixed and the facts are the input, and NEXPTIME-complete when the program is part of the input (Dantsin, Eiter, Gottlob and Voronkov 2001).

Properties

  • Exact on the positive part. The domain is the least model of the positive part of the program, so no atom of a stable model is missed.
  • Each instance once. Semi-naive evaluation finds each pair of a rule and a substitution exactly once.
  • Stratified programs are solved. For a program without negation, the output is the least model as a list of facts, so the solver has nothing left to do. Grounders that also evaluate stratified negation solve stratified programs completely.
  • Safety is necessary. An unsafe rule such as p(X)←not q(X)p(X) \leftarrow \mathit{not}\ q(X) has an instance for each constant, and its meaning depends on which constants exist. Grounders reject it.

Variants and improvements

  • Component order. Real grounders split the program along the strongly connected components of its predicate dependency graph and ground the components bottom-up. Atoms of finished lower components are then known exactly, so more literals can be decided.
  • Stratified negation. If cc is in a lower component and is not derived, then not c\mathit{not}\ c is true and can be dropped as soon as that component is done; if cc is a fact, the rule can be deleted.
  • Join order and indexes. Choosing the order of the body atoms and indexing atoms by their bound arguments change the cost of line L6 a great deal, though not the output.
  • Function symbols and arithmetic. With function symbols the Herbrand universe is infinite; grounders accept such programs only under conditions that make the domain finite, and they evaluate arithmetic during grounding.
  • Goal-directed grounding. Methods in the spirit of magic sets ground only the part of the program that a query needs.

When to use it

Every answer set system grounds first. Write the program so that the grounding is small: keep the number of variables per rule low, add domain predicates that restrict the variables, and avoid rules that join many large predicates. When the ground program is too large in practice, the problem usually lies in such a rule, not in the solver.

Pitfalls

  • Grounding bottleneck. The output grows as ckc^k. A rule with four variables over 1000 constants already has 101210^{12} instances, which no system can write out.
  • Unsafe rules. A variable that occurs only in the head, or only under not\mathit{not}, has no positive atom to bind it. Add a domain predicate to the body.
  • The domain is an overestimate. An atom in DD is not necessarily true in a stable model, because DD ignores the negative literals. Only atoms of FF are certain.
  • Simplification is semantic, not syntactic. Dropping not c\mathit{not}\ c is correct only for cc outside the domain. Dropping it because no rule for cc was emitted yet, in the middle of the evaluation, is wrong.
  • Duplicates. Two rules of the program can have the same instance. This is harmless, but the counts of instances and of output rules then differ.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

answer_set_grounding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/answer-set-grounding/. The authors are listed in prov/JQHNQC.jsonl.
"""A grounder for safe normal programs with variables, by semi-naive evaluation.

An atom is a tuple (predicate, t1, ..., tk) of strings. A term that starts
with an upper-case letter is a variable; every other term is a constant. There
are no function symbols. A rule is (head, pos, neg) with pos and neg tuples of
atoms. A rule is safe when every variable of the head and of neg occurs in pos.

ground(program) returns a ground program in the format of lp.py, whose atoms
are the ground tuples. It has the same stable models as the instantiation of
the program over all constants (the Herbrand universe).

1. Semi-naive evaluation of the positive parts of the rules computes the
   domain D, an overestimate of the atoms that some stable model can contain,
   and emits each rule instance whose positive body lies in D exactly once.
2. Simplification removes what the domain and the definite part decide:
   a rule with not c, where c is derived by the definite rules alone, is
   deleted; a literal not c with c outside D is true and is deleted; a
   positive body atom derived by the definite rules alone is deleted.
"""

import lp


def is_var(term):
    return term[:1].isupper()


def variables(atoms):
    return {t for atom in atoms for t in atom[1:] if is_var(t)}


def check_safe(rule):
    head, pos, neg = rule
    unsafe = variables((head,) + tuple(neg)) - variables(pos)
    if unsafe:
        raise ValueError(f"unsafe variables {sorted(unsafe)} in rule {rule}")


def match(pattern, fact, theta):
    """Extend the substitution theta so that pattern becomes fact, or return None."""
    if pattern[0] != fact[0] or len(pattern) != len(fact):
        return None
    out = dict(theta)
    for p, f in zip(pattern[1:], fact[1:]):
        if is_var(p):
            if out.setdefault(p, f) != f:
                return None
        elif p != f:
            return None
    return out


def subst(atom, theta):
    return (atom[0],) + tuple(theta.get(t, t) for t in atom[1:])


def index(atoms):
    """Atoms grouped by (predicate, arity)."""
    out = {}
    for a in atoms:
        out.setdefault((a[0], len(a)), []).append(a)
    return out


def joins(pos, sources, theta=None, i=0):
    """All substitutions that map pos[i] into sources[i] for every i."""
    if theta is None:
        theta = {}
    if i == len(pos):
        yield theta
        return
    for fact in sources[i].get((pos[i][0], len(pos[i])), ()):
        nxt = match(pos[i], fact, theta)
        if nxt is not None:
            yield from joins(pos, sources, nxt, i + 1)


def instantiate(program, stats=None):
    """Semi-naive evaluation. Return the domain and the list of rule instances with positive body in the domain."""
    for rule in program:
        check_safe(rule)  # @line L1
    instances = []
    seen = set()

    def emit(rule, theta):
        head, pos, neg = rule
        inst = (subst(head, theta), tuple(subst(b, theta) for b in pos), tuple(subst(c, theta) for c in neg))
        if stats is not None:
            stats["emitted"] = stats.get("emitted", 0) + 1
        if inst not in seen:
            seen.add(inst)
            instances.append(inst)
        return inst[0]

    old = set()
    delta = set()
    for rule in program:
        if not rule[1]:
            delta.add(emit(rule, {}))  # @line L2
    rounds = 0
    while delta:  # @line L3
        rounds += 1
        new_atoms = set()  # @line L4
        old_ix, delta_ix, all_ix = index(old), index(delta), index(old | delta)
        for rule in program:
            pos = rule[1]
            for j in range(len(pos)):  # @line L5
                # The first atom from the last round is at position j: earlier ones are old, later ones any.
                sources = [old_ix] * j + [delta_ix] + [all_ix] * (len(pos) - j - 1)
                for theta in joins(pos, sources):  # @line L6
                    new_atoms.add(emit(rule, theta))  # @line L7
        old |= delta
        delta = new_atoms - old  # @line L8
    if stats is not None:
        stats["rounds"] = rounds
    return old, instances


def simplify(domain, instances):
    """Remove what the domain and the definite instances decide. Duplicates are removed; the order is kept."""
    certain = lp.least_model([(h, pos, ()) for h, pos, neg in instances if not neg])  # @line L9
    out = []
    seen = set()
    for h, pos, neg in instances:  # @line L10
        if any(c in certain for c in neg):  # @line L11
            continue
        rule = (h, tuple(b for b in pos if b not in certain), tuple(c for c in neg if c in domain))  # @line L12
        if rule not in seen:
            seen.add(rule)
            out.append(rule)
    return out  # @line L13


def ground(program, stats=None):
    """The simplified ground program."""
    domain, instances = instantiate(program, stats)
    return simplify(domain, instances)
lp.py 79 lines
# SPDX-License-Identifier: MIT
# Shared helper of the logic program pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Ground normal logic programs, for the logic program pages.

A program is a list of rules (head, pos, neg). The head is an atom, and pos and
neg are tuples of atoms: the rule is head <- pos[0], ..., not neg[0], ....
An atom is any hashable value that can be sorted with the other atoms, for
example a small int or a short string. A rule with pos and neg empty is a fact.
A program with every neg empty is definite.

The functions are the plain definitions, written for clarity and checked by
the tests of each page. The brute force enumerator accepts at most MAX_ATOMS
atoms. The algorithms of the pages live in their own files, not here.
"""

from itertools import combinations

MAX_ATOMS = 12


def atoms(program):
    """The sorted list of the atoms that occur in the program."""
    out = set()
    for head, pos, neg in program:
        out.add(head)
        out.update(pos)
        out.update(neg)
    return sorted(out)


def tp(program, interp):
    """The immediate consequence operator: the heads of the rules whose body is true in the set interp."""
    return frozenset(h for h, pos, neg in program if all(b in interp for b in pos) and not any(c in interp for c in neg))


def least_model(program):
    """The least model of a definite program, as the limit of tp from the empty set."""
    if any(neg for _, _, neg in program):
        raise ValueError("least_model needs a definite program")
    model = frozenset()
    while True:
        nxt = tp(program, model)
        if nxt == model:
            return model
        model = nxt


def reduct(program, m):
    """The Gelfond-Lifschitz reduct of the program by the set m."""
    return [(h, tuple(pos), ()) for h, pos, neg in program if not any(c in m for c in neg)]


def is_stable(program, m):
    """True when m is the least model of the reduct of the program by m."""
    return least_model(reduct(program, m)) == frozenset(m)


def stable_models(program):
    """All stable models, by brute force over every subset of the atoms, sorted by size and then by content."""
    universe = atoms(program)
    if len(universe) > MAX_ATOMS:
        raise ValueError(f"the brute force accepts at most {MAX_ATOMS} atoms")
    found = []
    for k in range(len(universe) + 1):
        for subset in combinations(universe, k):
            if is_stable(program, frozenset(subset)):
                found.append(frozenset(subset))
    return found


def random_program(rng, n_atoms, n_rules, max_pos=2, max_neg=2):
    """A random ground normal program over the atoms 0 .. n_atoms - 1, drawn with the random.Random rng."""
    program = []
    for _ in range(n_rules):
        head = rng.randrange(n_atoms)
        pos = tuple(rng.sample(range(n_atoms), rng.randint(0, min(max_pos, n_atoms))))
        neg = tuple(rng.sample(range(n_atoms), rng.randint(0, min(max_neg, n_atoms))))
        program.append((head, pos, neg))
    return program
test_answer_set_grounding.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/answer-set-grounding/. The authors are listed in prov/JQHNQC.jsonl.

import random
import unittest
from itertools import product

import lp
from answer_set_grounding import ground, instantiate, is_var, subst

ARITY = {"p": 1, "q": 1, "r": 2, "s": 0}
CONSTANTS = ("a", "b")
VARS = ("X", "Y")


def constants_of(program):
    out = set()
    for h, pos, neg in program:
        for atom in (h,) + tuple(pos) + tuple(neg):
            out.update(t for t in atom[1:] if not is_var(t))
    return sorted(out) or ["a"]


def rule_vars(rule):
    h, pos, neg = rule
    return sorted({t for atom in (h,) + tuple(pos) + tuple(neg) for t in atom[1:] if is_var(t)})


def full_instantiation(program, consts=None):
    """Every rule under every substitution of its variables by constants of the program."""
    if consts is None:
        consts = constants_of(program)
    out = set()
    for rule in program:
        vs = rule_vars(rule)
        for values in product(consts, repeat=len(vs)):
            theta = dict(zip(vs, values))
            h, pos, neg = rule
            out.add((subst(h, theta), tuple(subst(b, theta) for b in pos), tuple(subst(c, theta) for c in neg)))
    return sorted(out)


def naive_instances(program):
    """The instances whose positive body lies in the least model of the positive parts, by plain iteration."""
    full = full_instantiation(program)
    domain = lp.least_model([(h, pos, ()) for h, pos, neg in full])
    return domain, {r for r in full if all(b in domain for b in r[1])}


def random_atom(rng, allow_vars):
    pred = rng.choice(sorted(ARITY))
    terms = [rng.choice(VARS + CONSTANTS) if allow_vars else rng.choice(CONSTANTS) for _ in range(ARITY[pred])]
    return (pred,) + tuple(terms)


def random_program(rng):
    program = []
    for _ in range(rng.randint(1, 4)):
        program.append((random_atom(rng, False), (), ()))
    for _ in range(rng.randint(1, 5)):
        pos = tuple(random_atom(rng, True) for _ in range(rng.randint(1, 2)))
        safe = {t for atom in pos for t in atom[1:] if is_var(t)}
        fix = lambda atom: (atom[0],) + tuple(t if not is_var(t) or t in safe else rng.choice(CONSTANTS) for t in atom[1:])
        head = fix(random_atom(rng, True))
        neg = tuple(fix(random_atom(rng, True)) for _ in range(rng.randint(0, 1)))
        program.append((head, pos, neg))
    return program


class TestGrounding(unittest.TestCase):
    def test_example(self):
        # Reachability with a choice between two colours of each reached node.
        program = [
            (("edge", "a", "b"), (), ()),
            (("edge", "b", "c"), (), ()),
            (("start", "a"), (), ()),
            (("reach", "X"), (("start", "X"),), ()),
            (("reach", "Y"), (("reach", "X"), ("edge", "X", "Y")), ()),
            (("red", "X"), (("reach", "X"),), (("green", "X"),)),
            (("green", "X"), (("reach", "X"),), (("red", "X"),)),
        ]
        g = ground(program)
        self.assertEqual(len(g), 12)
        self.assertIn((("red", "c"), (), (("green", "c"),)), g)
        self.assertEqual(len(lp.stable_models(g)), 8)

    def test_semi_naive_finds_each_instance_once(self):
        rng = random.Random(4483)
        for _ in range(300):
            program = random_program(rng)
            stats = {}
            domain, instances = instantiate(program, stats)
            n_domain, n_instances = naive_instances(program)
            self.assertEqual(domain, set(n_domain))
            self.assertEqual(set(instances), n_instances)
            # Each (rule, substitution) pair is produced in exactly one round and one position.
            consts = constants_of(program)
            pairs = sum(1 for r in program for i in full_instantiation([r], consts) if all(b in domain for b in i[1]))
            self.assertEqual(stats["emitted"], pairs)

    def test_same_stable_models_as_full_instantiation(self):
        rng = random.Random(266)
        for _ in range(200):
            program = random_program(rng)
            full = full_instantiation(program)
            self.assertLessEqual(len(lp.atoms(full)), 9)
            expected = lp.stable_models(full)
            got = lp.stable_models(ground(program))
            self.assertEqual(got, expected, program)

    def test_unsafe_rule_is_rejected(self):
        with self.assertRaises(ValueError):
            ground([(("p", "X"), (), (("q", "X"),))])

    def test_exponential_family(self):
        # p(X1, ..., Xk) <- d(X1), ..., d(Xk) with d(a), d(b) has 2^k ground instances,
        # and every one of them is a different fact in the output.
        for k in range(1, 9):
            vs = tuple(f"X{i}" for i in range(1, k + 1))
            program = [(("d", "a"), (), ()), (("d", "b"), (), ()), (("p",) + vs, tuple(("d", v) for v in vs), ())]
            g = ground(program)
            self.assertEqual(len(g), 2 + 2 ** k)
            self.assertEqual(len(lp.least_model(g)), 2 + 2 ** k)


if __name__ == "__main__":
    unittest.main()

History

Gelfond and Lifschitz (1988) defined stable models of programs with variables through the ground instances. The lparse grounder of the smodels system and the grounder of DLV (Leone et al. 2006) introduced domain restrictions and intelligent grounding, which produce only the relevant instances. Gebser, Schaub and Thiele (2007) presented the gringo grounder, which accepts a larger class of programs. Its later versions are part of the clingo system, and like the method on this page they evaluate the positive part of the program bottom-up, in the manner of Datalog engines.

References

  1. Martin Gebser, Torsten Schaub and Sven Thiele, GrinGo: a new grounder for answer set programming, in Logic Programming and Nonmonotonic Reasoning (LPNMR 2007), Lecture Notes in Computer Science, Springer, 266 to 271 (2007), the gringo grounder and the class of programs it accepts
  2. Martin Gebser, Roland Kaminski, Benjamin Kaufmann and Torsten Schaub, Answer Set Solving in Practice, Morgan and Claypool (2012), Chapter 4, Grounding (safety, the instantiation of rules and the simplification of the ground program)
  3. Nicola Leone, Gerald Pfeifer, Wolfgang Faber, Thomas Eiter, Georg Gottlob, Simona Perri and Francesco Scarcello, The DLV system for knowledge representation and reasoning, ACM Transactions on Computational Logic 7(3) (2006), the intelligent grounding module of DLV
  4. Michael Gelfond and Vladimir Lifschitz, The stable model semantics for logic programming, in Robert A. Kowalski and Kenneth A. Bowen (eds.), Logic Programming: Proceedings of the Fifth International Conference and Symposium, MIT Press, 1070 to 1080 (1988), stable models of a program with variables defined through its ground instances
  5. Evgeny Dantsin, Thomas Eiter, Georg Gottlob and Andrei Voronkov, Complexity and expressive power of logic programming, ACM Computing Surveys 33(3), 374 to 425 (2001), the data complexity and program complexity of normal programs under the stable model semantics

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example