Algorithm Search⌘K

Algorithmadvanced

Dalal's revision operator

Also called Hamming distance revision.

Revises by the models of the new formula that are at minimum Hamming distance from some model of the old beliefs.

Time
Θ(n·2^n) worstΘ(2^n) best
Space
Θ(2^n) extra
Where
n = the number of atoms
Properties
deterministic
Origin
Mukesh Dalal, 1988

Dalal's operator is the best known concrete belief revision operator for a finite propositional language. To revise a belief base KK by a formula pp, it keeps the models of pp that change as few atoms as possible in some model of KK. The number of changed atoms is the Hamming distance between two worlds. Mukesh Dalal defined it in 1988, and Katsuno and Mendelzon (1991) showed that it fits their characterization of the AGM postulates: it satisfies R1 to R6. On sets of models it is a breadth-first search over the cube {0,1}n\{0,1\}^n that starts from all models of KK at once. On formulas the same question is complete for PNP[O(log⁡n)]\mathrm{P}^{\mathrm{NP}[O(\log n)]} (Eiter and Gottlob 1992, Theorem 6.9).

In plain words

A world is one way of making each atom true or false. Your beliefs allow some worlds. New information allows some worlds too, and you must now believe it. If some world is allowed by both, keep exactly those worlds. If not, look for the allowed worlds of the new information that are nearest to your old worlds, where the distance between two worlds is the number of atoms on which they disagree. Keep only the nearest ones. So you give up as few separate facts as you can, and you count each atom as one fact.

The search goes outwards in rings. Ring 0 is your old worlds. Ring 1 is every world that you get by changing one atom, ring 2 by changing two, and so on. Stop at the first ring that contains a world of the new information.

The problem

Fix nn atoms x0,…,xn−1x_0, \ldots, x_{n-1}. A world is a vector w∈{0,1}nw \in \{0,1\}^n, and h(u,v)h(u, v) is the number of positions where uu and vv differ. The input is nn, the set K=Mod(ψ)K = \mathrm{Mod}(\psi) of the models of the base and the set P=Mod(μ)P = \mathrm{Mod}(\mu) of the models of the new formula. For nonempty KK let dist(w,K)=min⁡u∈Kh(w,u)\mathrm{dist}(w, K) = \min_{u \in K} h(w, u). The output is

Mod(ψ∘Dμ)={w∈P:dist(w,K)=d∗},d∗=min⁡w∈Pdist(w,K),\mathrm{Mod}(\psi \circ_D \mu) = \{w \in P : \mathrm{dist}(w, K) = d^*\}, \qquad d^* = \min_{w \in P} \mathrm{dist}(w, K),

with ψ∘Dμ≡μ\psi \circ_D \mu \equiv \mu when ψ\psi is unsatisfiable, and the empty set when μ\mu is unsatisfiable. Dalal states it through an operator GG on formulas: Mod(G(ψ))\mathrm{Mod}(G(\psi)) is the set of the worlds that differ from some model of ψ\psi in at most one atom, and ψ∘Dμ\psi \circ_D \mu is Gk(ψ)∧μG^k(\psi) \wedge \mu for the least kk that makes this satisfiable (Dalal 1988, p. 476). The two forms agree because Mod(Gk(ψ))={w:dist(w,K)≤k}\mathrm{Mod}(G^k(\psi)) = \{w : \mathrm{dist}(w, K) \le k\}.

The algorithm

SS is the set of the worlds reached so far and LL is the current ring. Worlds are stored as integers, with bit ii for atom xix_i.

  1. DALAL(K, P, n)
  2. 1if P = ∅ then return ∅
  3. 2if K = ∅ then return P ▷ no model to be near
  4. 3L ← K; S ← K; d ← 0
  5. 4while L ∩ P = ∅ do
  6. 5N ← ∅
  7. 6for each w in L do
  8. 7for i ← 0 to n-1 do
  9. 8v ← w xor 2^i ▷ change atom i
  10. 9if v ∉ S then add v to S and to N
  11. 10L ← N; d ← d + 1
  12. 11return L ∩ P (and d)

This is multi-source BFS on the hypercube graph, in which two worlds are adjacent when they differ in one atom. Ring dd is Mod(Gd(ψ))\mathrm{Mod}(G^d(\psi)) minus Mod(Gd−1(ψ))\mathrm{Mod}(G^{d-1}(\psi)). The loop stops at d=d∗d = d^*, so it never builds the rings beyond the answer.

Example

This is Example 3.3 of Eiter and Gottlob (1992). The atoms are a,b,c,da, b, c, d, and a world is written as the bit string abcdabcd. The base is ψ=a∧b∧c\psi = a \wedge b \wedge c and the new formula is

μ=(¬a∧d)∨(a∧¬b∧¬c∧¬d).\mu = (\neg a \wedge d) \vee (a \wedge \neg b \wedge \neg c \wedge \neg d).

So K={1110,1111}K = \{1110, 1111\} and P={0001,0011,0101,0111,1000}P = \{0001, 0011, 0101, 0111, 1000\}. K∩PK \cap P is empty, so the old beliefs and μ\mu conflict.

ring dd new worlds in the ring meets PP
0 1110, 1111 no
1 0110, 1010, 1100, 0111, 1011, 1101 0111

Line L8 tries 2⋅4=82 \cdot 4 = 8 changes of one atom. Two of them lead back into KK, and six give the new worlds of ring 1. The run stops with d=1d = 1 and the result {0111}\{0111\}, that is ψ∘Dμ≡¬a∧b∧c∧d\psi \circ_D \mu \equiv \neg a \wedge b \wedge c \wedge d. The distances of all five models of μ\mu confirm it:

model of μ\mu 0001 0011 0101 0111 1000
dist(w,K)\mathrm{dist}(w, K) 3 2 2 1 2

The world 10001000 shows what a count does. It differs from 11101110 in bb and cc, two atoms, while 01110111 differs from 11111111 only in aa. Satoh's operator compares the sets of changed atoms by inclusion instead of by size, and {a}\{a\} and {b,c}\{b, c\} are not comparable, so it keeps both worlds (Eiter and Gottlob 1992, Example 3.3).

A smaller case from Dalal (1988): revising a∧¬ba \wedge \neg b by bb gives a∧ba \wedge b. The fact aa survives because the change to bb alone is enough.

Correctness

At the test of line L4, LL is exactly the set of the worlds at distance dd from KK, and SS is the set at distance at most dd. The induction step uses one fact of the hypercube: a world at distance j≥1j \ge 1 has a neighbour at distance j−1j - 1, and neighbours differ in distance by at most 1. So line L9 adds exactly the worlds at distance d+1d + 1. The loop runs while no world of PP is in the ring, which means d<d∗d < d^*, and it stops at d=d∗d = d^* with L∩PL \cap P equal to the required set. Since all distances are at most nn, it stops after at most nn rounds. The full proof is in the correctness proof.

Proof: The layer method returns the models of p at minimum Hamming distance from the models of Kfull

We use the pseudocode of the page. The input is a number n≥0n \ge 0 of atoms, the set KK of the models of the belief base and the set PP of the models of the new information pp. Both are sets of worlds, and a world is a vector in {0,1}n\{0,1\}^n. Write h(u,v)h(u, v) for the Hamming distance between two worlds, the number of atoms on which they differ. For a nonempty set KK, write

dist(w,K)=min⁡u∈Kh(w,u).\mathrm{dist}(w, K) = \min_{u \in K} h(w, u).

Dalal's revision is K∘P={w∈P:dist(w,K)=d∗}K \circ P = \{w \in P : \mathrm{dist}(w, K) = d^*\} with d∗=min⁡w∈Pdist(w,K)d^* = \min_{w \in P} \mathrm{dist}(w, K) when KK and PP are nonempty, K∘P=PK \circ P = P when KK is empty, and K∘P=∅K \circ P = \emptyset when PP is empty (Dalal 1988, with the empty base as in Eiter and Gottlob 1992).

Two worlds are neighbours when their distance is 1. Line L8 makes the neighbour of ww that differs from ww in atom ii.

Lemma 1 (one step). Let KK be nonempty. If uu and vv are neighbours, then ∣dist(u,K)−dist(v,K)∣≤1|\mathrm{dist}(u, K) - \mathrm{dist}(v, K)| \le 1. If dist(v,K)=j≥1\mathrm{dist}(v, K) = j \ge 1, then vv has a neighbour uu with dist(u,K)=j−1\mathrm{dist}(u, K) = j - 1.

Proof. The Hamming distance is a metric, so h(u,x)≤h(u,v)+h(v,x)=1+h(v,x)h(u, x) \le h(u, v) + h(v, x) = 1 + h(v, x) for each x∈Kx \in K. Take the minimum over xx to get dist(u,K)≤1+dist(v,K)\mathrm{dist}(u, K) \le 1 + \mathrm{dist}(v, K), and swap uu and vv. For the second claim, take x∈Kx \in K with h(v,x)=j≥1h(v, x) = j \ge 1, and let uu be vv with one of the atoms where vv and xx differ changed. Then h(u,x)=j−1h(u, x) = j - 1, so dist(u,K)≤j−1\mathrm{dist}(u, K) \le j - 1, and the first claim gives dist(u,K)≥j−1\mathrm{dist}(u, K) \ge j - 1. □\square

Lemma 2 (layers). Let KK and PP be nonempty. Each time the test of line L4 runs, with the current value dd,

(I1) L={w:dist(w,K)=d}L = \{w : \mathrm{dist}(w, K) = d\}, and

(I2) S={w:dist(w,K)≤d}S = \{w : \mathrm{dist}(w, K) \le d\}.

Proof. By induction on the number of times the test has run. The first time, line L3 has set L=S=KL = S = K and d=0d = 0, and dist(w,K)=0\mathrm{dist}(w, K) = 0 holds exactly for w∈Kw \in K.

Suppose the claims hold for dd and the body of the loop runs. Lines L5 to L9 put vv in NN exactly when vv is a neighbour of some w∈Lw \in L and v∉Sv \notin S at that moment. Since SS only grows by the worlds that are put in NN, a world is put in NN at most once, and at the end

N={v:v∉Sold and v has a neighbour in L}.N = \{v : v \notin S_{\text{old}} \text{ and } v \text{ has a neighbour in } L\}.

Let v∈Nv \in N. Then dist(v,K)>d\mathrm{dist}(v, K) > d by (I2), and dist(v,K)≤d+1\mathrm{dist}(v, K) \le d + 1 by Lemma 1, because a neighbour has distance dd by (I1). So dist(v,K)=d+1\mathrm{dist}(v, K) = d + 1. Conversely let dist(v,K)=d+1\mathrm{dist}(v, K) = d + 1. Then v∉Soldv \notin S_{\text{old}} by (I2), and by Lemma 1 vv has a neighbour at distance dd, which is in LL by (I1). So v∈Nv \in N. This shows N={w:dist(w,K)=d+1}N = \{w : \mathrm{dist}(w, K) = d + 1\}, and Snew=Sold∪N={w:dist(w,K)≤d+1}S_{\text{new}} = S_{\text{old}} \cup N = \{w : \mathrm{dist}(w, K) \le d + 1\}. Line L10 sets L←NL \leftarrow N and d←d+1d \leftarrow d + 1, so (I1) and (I2) hold for the new value of dd. □\square

Lemma 3 (termination). Let KK and PP be nonempty. The loop of lines L4 to L10 runs exactly d∗d^* times, and d∗≤nd^* \le n.

Proof. Each distance is at most nn, so d∗≤nd^* \le n. By (I1), L∩P={w∈P:dist(w,K)=d}L \cap P = \{w \in P : \mathrm{dist}(w, K) = d\} at the test of line L4. For d<d∗d < d^* this set is empty, by the definition of d∗d^*, so the loop body runs. For d=d∗d = d^* the set holds a world of PP with the least distance, so the test fails and the loop stops. □\square

Theorem. DALAL(K,P,n)(K, P, n) stops and returns K∘PK \circ P. When KK and PP are nonempty, the returned distance is d∗d^*.

Proof. If PP is empty, line L1 returns ∅\emptyset. If KK is empty, line L2 returns PP. Otherwise, by Lemma 3 the loop stops with d=d∗d = d^*, and by (I1) line L11 returns L∩P={w∈P:dist(w,K)=d∗}L \cap P = \{w \in P : \mathrm{dist}(w, K) = d^*\}, which is K∘PK \circ P. □\square

Cost. By (I2) and the test of line L9, each world enters SS at most once, and each world of LL was put in SS when it entered LL. So the layers are disjoint, the loop of line L6 meets each world at most once, and lines L7 to L9 run at most n⋅∣S∣≤n⋅2nn \cdot |S| \le n \cdot 2^n times in total. On the word RAM, with KK, PP and SS stored as bit arrays of 2n2^n bits, each run of lines L8 and L9 takes O(1)O(1) time, and the test of line L4 can be done when the members of NN are added. So the time is O(n⋅2n)O(n \cdot 2^n), plus O(2n)O(2^n) to set up the arrays. The bound is reached: for K={0n}K = \{0^n\} and P={1n}P = \{1^n\} we have d∗=nd^* = n, every world enters SS, and lines L7 to L9 run exactly n⋅2nn \cdot 2^n times.

The empty base. The case of line L2 is a convention, not a consequence of the distance: with no model of KK, no world of PP is closer than another, and Eiter and Gottlob (1992) take Mod(ψ∘μ)=Mod(μ)\mathrm{Mod}(\psi \circ \mu) = \mathrm{Mod}(\mu) when ψ\psi is unsatisfiable. This choice is the flat preorder in which all worlds are equal, so the operator satisfies R1 to R6 also when KK is inconsistent.

Complexity

Each world enters SS once, so lines L7 to L9 run at most n⋅∣S∣≤n⋅2nn \cdot |S| \le n \cdot 2^n times. With KK, PP and SS as bit arrays of 2n2^n bits on the word RAM, each step is O(1)O(1), so the time is Θ(n⋅2n)\Theta(n \cdot 2^n) in the worst case and Θ(2n)\Theta(2^n) in the best case, where the bit arrays are set up and K∩PK \cap P is already nonempty. The worst case is reached when K={0n}K = \{0^n\} and P={1n}P = \{1^n\}: then d∗=nd^* = n and every world is visited. The extra space is 2n2^n bits for SS. The Python version uses hash sets, so its cost is O(∣K∣+∣P∣+n⋅∣S∣)O(|K| + |P| + n \cdot |S|) expected time, which is small when the answer is near KK.

The brute-force method computes dist(w,K)\mathrm{dist}(w, K) for each w∈Pw \in P in O(∣K∣⋅∣P∣)O(|K| \cdot |P|) distance computations, each a population count of u⊕wu \oplus w. It wins when KK and PP are small and d∗d^* is large, and the ring method wins when KK is large or d∗d^* is small.

When ψ\psi and μ\mu are formulas, the model sets can have 2n2^n members, and the right measure is the cost of the decision problem "does ψ∘Dμ\psi \circ_D \mu entail qq". It is PNP[O(log⁡n)]\mathrm{P}^{\mathrm{NP}[O(\log n)]}-complete, and hard already when ψ\psi is a conjunction of atoms (Eiter and Gottlob 1992, Theorem 6.9). The upper bound is a binary search on k∈{0,…,n}k \in \{0, \ldots, n\}. Each step asks one SAT question: is there a model of μ\mu within distance kk of a model of ψ\psi? Then one more question decides whether some model of μ∧¬q\mu \wedge \neg q is at distance d∗d^*. Hardness stays when ψ\psi, μ\mu and qq are Horn (Theorem 7.4, which uses a base of literals). If the size of μ\mu is bounded by a constant, a constant number of NP calls suffices (Theorem 8.1), and with Horn formulas as well the problem is solvable in time O(∣ψ∣⋅∣q∣)O(|\psi| \cdot |q|) (Theorem 8.3). These classes sit in the polynomial hierarchy below Σ2P\Sigma_2^P. Most other model-based operators, including Satoh's and the possible models approach of Winslett, are Π2P\Pi_2^P-complete (Theorem 6.4).

Properties

  • It satisfies R1 to R6. The ranks dist(⋅,K)\mathrm{dist}(\cdot, K) form a total preorder on worlds in which the models of KK are exactly the worlds of rank 0. This is a faithful assignment, so by the Katsuno and Mendelzon theorem the operator satisfies R1 to R6, and so the AGM postulates K1 to K8 for belief sets over a finite language.
  • It is a system of spheres. Sphere kk is Mod(Gk(ψ))\mathrm{Mod}(G^k(\psi)). These sets are nested, the smallest is Mod(ψ)\mathrm{Mod}(\psi), and the largest is every world, as in Grove's model.
  • It depends only on the models. Equivalent bases and equivalent new formulas give the same result, so the syntax does not matter (R4).
  • It depends on the choice of atoms. Rename the language and the distance changes. Take ψ=a∧b\psi = a \wedge b and μ=¬(a∧b)\mu = \neg(a \wedge b): the result is (a∧¬b)∨(¬a∧b)(a \wedge \neg b) \vee (\neg a \wedge b). Now use the atoms x=ax = a and y=a⊕by = a \oplus b, which describe the same worlds. Then ψ\psi is x∧¬yx \wedge \neg y, the worlds ¬a∧¬b\neg a \wedge \neg b and a∧¬ba \wedge \neg b are at distance 1, and the result is ¬b\neg b.
  • It is a revision, not an update. It takes the models of μ\mu nearest to the whole set KK. An update takes the nearest models of μ\mu for each model of KK separately.

Variants and improvements

  • Weighted distance. Give each atom a positive weight and add the weights of the changed atoms. The ring method becomes Dijkstra's algorithm on the cube, or a bucket queue for small integer weights. The postulates still hold, since the ranks are still a total preorder with the models of KK alone at rank 0.
  • Satoh's operator. Compare the sets of changed atoms by inclusion. This gives a partial preorder, and the operator satisfies R1 to R5 but fails R6 (Eiter and Gottlob 1992, Section 3).
  • Model-wise distance. Winslett's possible models approach and Forbus's operator use the same kind of distance, but for each model of KK separately. They are update operators.
  • Merging. Summing the Hamming distances to several bases gives a distance-based operator for belief merging.
  • With a SAT solver. For formulas, ask for a model of μ\mu and a copy of ψ\psi with at most kk disagreeing atoms, using a cardinality constraint, and search on kk. Or minimise the number of disagreements with a MaxSAT solver, where each "atom ii is the same in both copies" is a soft clause.

When to use it

Use it when the beliefs are a small propositional theory, the atoms are independent facts of the same weight, and the new information must be accepted. Examples are repairs of a configuration, of a database row, or of a sensor reading, where each atom is one value that can be wrong. With at most 20 or 25 atoms, the ring method on bit arrays is direct. With more atoms, work on formulas with a SAT or MaxSAT solver. If the facts have different weights, use the weighted variant. If the world has changed, rather than your knowledge of it, use an update operator. If several revisions follow one another, one total preorder per base is not enough, and the Darwiche and Pearl postulates apply.

Pitfalls

  • Distance from the set, not from each model. The minimum is over all pairs of a model of KK and a model of μ\mu. Taking the nearest models of μ\mu for each model of KK and their union gives an update operator, which fails R2.
  • Stopping one ring too late. Test the ring against PP before building the next one. Otherwise the result mixes two distances.
  • Inconsistent base. If KK has no model, there is no first ring. Return PP, as line L2 does.
  • Unsatisfiable new formula. The result is empty, and R3 does not apply.
  • Worlds outside the cube. An integer that is not below 2n2^n is not a world. The Python version rejects it with an error.
  • Treating the result as unique to the language. The operator answers for one fixed set of atoms. Adding defined atoms or recoding values changes the result, as shown in the properties.

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.

dalal_revision.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dalal-revision/. The authors are listed in prov/WXMFTE.jsonl.

"""Dalal's revision operator on finite propositional belief bases.

A world (an interpretation) over n atoms is an integer w with 0 <= w < 2**n:
bit i of w is 1 when atom i is true. A belief base is given by its set of
models, a set of worlds. The revision K o p keeps the models of p that are at
minimum Hamming distance from some model of K (Dalal 1988).

The method grows the set of worlds around the models of K one Hamming layer at
a time, which is Dalal's generalization operator G applied again and again:
layer 0 is Mod(K), and layer d + 1 holds the worlds that differ in one atom
from a world of layer d and are in no earlier layer. The first layer that
meets Mod(p) is at the minimum distance, and its common part with Mod(p) is
the result.
"""


def hamming(u, v):
    """The number of atoms on which the worlds u and v differ."""
    return bin(u ^ v).count("1")


def _check_worlds(worlds, n, name):
    out = frozenset(worlds)
    limit = 1 << n
    for w in out:
        if not isinstance(w, int) or w < 0 or w >= limit:
            raise ValueError(f"{name} holds {w!r}, which is not a world over {n} atoms")
    return out


def dalal_revision_with_stats(k_models, p_models, n):
    """Return (result, d, visited, flips).

    result is Mod(K o p) as a frozenset. d is the minimum Hamming distance
    between a model of K and a model of p, or None when K or p has no model.
    visited is the number of worlds put in some layer, and flips is the number
    of one-atom changes that the layer loop tried.
    """
    if n < 0:
        raise ValueError("n must be at least 0")
    k = _check_worlds(k_models, n, "k_models")
    p = _check_worlds(p_models, n, "p_models")
    if not p:
        return frozenset(), None, 0, 0  # @line L1
    if not k:
        # Mod(K) is empty: every model of p is kept (Eiter and Gottlob 1992).
        return p, None, 0, 0  # @line L2
    layer, seen, d = k, set(k), 0  # @line L3
    flips = 0
    while not (layer & p):  # @line L4
        nxt = set()  # @line L5
        for w in layer:  # @line L6
            for i in range(n):  # @line L7
                flips += 1
                v = w ^ (1 << i)  # @line L8
                if v not in seen:  # @line L9
                    seen.add(v)
                    nxt.add(v)
        # nxt is not empty here: p has a model outside seen, and the cube is connected.
        layer, d = frozenset(nxt), d + 1  # @line L10
    return frozenset(layer & p), d, len(seen), flips  # @line L11


def dalal_revision(k_models, p_models, n):
    """Mod(K o p): the models of p at minimum Hamming distance from Mod(K)."""
    return dalal_revision_with_stats(k_models, p_models, n)[0]


def dalal_distance(k_models, p_models, n):
    """The minimum Hamming distance between Mod(K) and Mod(p), or None."""
    return dalal_revision_with_stats(k_models, p_models, n)[1]
test_dalal_revision.py 295 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dalal-revision/. The authors are listed in prov/WXMFTE.jsonl.

import itertools
import random

import pytest

from dalal_revision import dalal_distance, dalal_revision, dalal_revision_with_stats, hamming


def worlds(n):
    return range(1 << n)


def random_set(rng, n, prob):
    return frozenset(w for w in worlds(n) if rng.random() < prob)


def brute_force(k, p, n):
    """Models of p at minimum Hamming distance from some model of k, by all pairs."""
    k, p = frozenset(k), frozenset(p)
    if not p:
        return frozenset()
    if not k:
        return p
    dist = {w: min(hamming(w, v) for v in k) for w in p}
    best = min(dist.values())
    return frozenset(w for w in p if dist[w] == best)


def all_subsets(n):
    ws = list(worlds(n))
    for mask in range(1 << len(ws)):
        yield frozenset(w for j, w in enumerate(ws) if mask >> j & 1)


# The six KM postulates, with formulas given by their sets of models.
def km_violations(op, k, p, q, n):
    bad = []
    r = op(k, p, n)
    if not r <= p:
        bad.append("R1")
    if k & p and r != k & p:
        bad.append("R2")
    if p and not r:
        bad.append("R3")
    if op(list(k)[::-1], sorted(p, reverse=True), n) != r:
        bad.append("R4")
    rpq = op(k, p & q, n)
    if not (r & q) <= rpq:
        bad.append("R5")
    if r & q and not rpq <= r & q:
        bad.append("R6")
    return bad


# Atoms a, b, c, d are bits 0, 1, 2, 3. The example of the page is Example 3.3 of
# Eiter and Gottlob (1992): K = a and b and c, p = (not a and d) or (a and not b and not c and not d).
A, B, C, D = 1, 2, 4, 8


def page_example():
    n = 4
    k = frozenset(w for w in worlds(n) if w & A and w & B and w & C)
    p = frozenset(w for w in worlds(n) if (not w & A and w & D) or w == A)
    return k, p, n


def test_page_example():
    k, p, n = page_example()
    assert k == {A | B | C, A | B | C | D}
    assert p == {D, B | D, C | D, B | C | D, A}
    result, d, visited, flips = dalal_revision_with_stats(k, p, n)
    assert d == 1
    assert result == {B | C | D}
    # Layer 0 has 2 worlds, layer 1 adds 6 new worlds, after 2 * 4 flips.
    assert visited == 8 and flips == 8
    # Distances of the five models of p to Mod(K).
    assert {w: min(hamming(w, v) for v in k) for w in p} == {D: 3, B | D: 2, C | D: 2, B | C | D: 1, A: 2}


def test_dalal_small_example():
    # K = a and not b, p = b, over two atoms (Dalal 1988, Section 3): the result is a and b.
    assert dalal_revision({A}, {B, A | B}, 2) == {A | B}
    assert dalal_distance({A}, {B, A | B}, 2) == 1


@pytest.mark.parametrize("n", [0, 1, 2, 3, 4, 5])
def test_matches_brute_force(n):
    rng = random.Random(1000 + n)
    for _ in range(300):
        k = random_set(rng, n, rng.choice([0.05, 0.2, 0.5]))
        p = random_set(rng, n, rng.choice([0.05, 0.2, 0.5]))
        r = dalal_revision(k, p, n)
        assert r == brute_force(k, p, n)
        d = dalal_distance(k, p, n)
        if k and p:
            assert d == min(hamming(u, v) for u in k for v in p)
        else:
            assert d is None


def test_exhaustive_two_atoms():
    for k in all_subsets(2):
        for p in all_subsets(2):
            assert dalal_revision(k, p, 2) == brute_force(k, p, 2)


def test_empty_cases():
    assert dalal_revision(set(), {1, 2}, 2) == {1, 2}
    assert dalal_revision({1}, set(), 2) == set()
    assert dalal_revision(set(), set(), 3) == set()
    assert dalal_revision({0}, {0}, 0) == {0}


def test_bad_world_rejected():
    with pytest.raises(ValueError):
        dalal_revision({4}, {1}, 2)
    with pytest.raises(ValueError):
        dalal_revision({1}, {-1}, 2)


@pytest.mark.parametrize("n", [1, 2, 3, 4, 5])
def test_km_postulates_dalal(n):
    rng = random.Random(2000 + n)
    for _ in range(200):
        k = random_set(rng, n, rng.choice([0.0, 0.1, 0.3, 0.6]))
        p = random_set(rng, n, rng.choice([0.1, 0.3, 0.6]))
        q = random_set(rng, n, rng.choice([0.2, 0.5, 0.8]))
        assert km_violations(dalal_revision, k, p, q, n) == []


def test_km_postulates_dalal_exhaustive_two_atoms():
    subsets = list(all_subsets(2))
    for k in subsets:
        for p in subsets:
            for q in subsets:
                assert km_violations(dalal_revision, k, p, q, 2) == []


def test_cost_counts():
    rng = random.Random(7)
    for n in range(1, 6):
        for _ in range(100):
            k = random_set(rng, n, 0.1)
            p = random_set(rng, n, 0.1)
            _, d, visited, flips = dalal_revision_with_stats(k, p, n)
            assert visited <= 1 << n
            assert flips <= n * visited
            if d is not None:
                assert d <= n
    # Antipodal worlds: the layers cover the whole cube, d = n.
    _, d, visited, flips = dalal_revision_with_stats({0}, {31}, 5)
    assert (d, visited) == (5, 32)
    assert flips == 5 * (1 + 5 + 10 + 10 + 5)


# Faithful assignments of total preorders (Katsuno and Mendelzon 1991). A total
# preorder on worlds is given by a rank function: w <= v iff rank[w] <= rank[v].
def ranked_operator(rank_of):
    def op(k, p, n):
        k, p = frozenset(k), frozenset(p)
        if not p:
            return frozenset()
        rank = rank_of(k, n)
        best = min(rank[w] for w in p)
        return frozenset(w for w in p if rank[w] == best)

    return op


def faithful_random_ranks(seed):
    """A faithful assignment: rank 0 on Mod(K), a rank from 1 to 3 elsewhere.

    The ranks depend only on the set Mod(K), so equal bases get equal preorders.
    If Mod(K) is empty, the ranks are free.
    """

    def rank_of(k, n):
        key = sum(1 << w for w in k)
        rng = random.Random(seed * 1000003 + key * 7 + n)
        if not k:
            return {w: rng.randrange(3) for w in worlds(n)}
        return {w: 0 if w in k else 1 + rng.randrange(3) for w in worlds(n)}

    return rank_of


def dalal_ranks(k, n):
    if not k:
        return {w: 0 for w in worlds(n)}
    return {w: min(hamming(w, v) for v in k) for w in worlds(n)}


@pytest.mark.parametrize("seed", [1, 2, 3])
def test_faithful_total_preorders_satisfy_r1_to_r6(seed):
    op = ranked_operator(faithful_random_ranks(seed))
    rng = random.Random(3000 + seed)
    for _ in range(300):
        n = rng.randrange(1, 5)
        k = random_set(rng, n, rng.choice([0.0, 0.2, 0.5]))
        p = random_set(rng, n, rng.choice([0.2, 0.5]))
        q = random_set(rng, n, rng.choice([0.3, 0.6]))
        assert km_violations(op, k, p, q, n) == []


def test_dalal_is_the_hamming_ranking():
    op = ranked_operator(dalal_ranks)
    rng = random.Random(4000)
    for _ in range(300):
        n = rng.randrange(1, 6)
        k = random_set(rng, n, 0.2)
        p = random_set(rng, n, 0.3)
        assert op(k, p, n) == dalal_revision(k, p, n)


def test_unfaithful_assignment_breaks_r2():
    # The world 3 (a and b) is outside Mod(K) = {1} but gets rank 0, the same rank as the model of K.
    def rank_of(k, n):
        return {w: 0 if w in k or w == 3 else 1 for w in worlds(n)}

    op = ranked_operator(rank_of)
    k, p, q = frozenset({1}), frozenset({1, 3}), frozenset(worlds(2))
    assert op(k, p, 2) == {1, 3}
    assert "R2" in km_violations(op, k, p, q, 2)


def satoh_revision(k, p, n):
    """Keep the models of p whose difference to some model of K is minimal under set inclusion."""
    k, p = frozenset(k), frozenset(p)
    if not k or not p:
        return p
    diffs = {u ^ v for u in p for v in k}
    minimal = {x for x in diffs if not any(y != x and y & x == y for y in diffs)}
    return frozenset(u for u in p if any(u ^ v in minimal for v in k))


def test_random_search_finds_r6_failures_of_satoh_only():
    # Satoh's operator compares differences by set inclusion, which is not a total preorder.
    rng = random.Random(5)
    failures = 0
    for _ in range(3000):
        k = random_set(rng, 3, 0.25)
        p = random_set(rng, 3, 0.5)
        q = random_set(rng, 3, 0.5)
        bad = km_violations(satoh_revision, k, p, q, 3)
        assert all(x == "R6" for x in bad)
        if bad:
            failures += 1
            assert km_violations(dalal_revision, k, p, q, 3) == []
    assert failures > 0


def test_satoh_r6_counterexample_of_the_page():
    # K = not a and not b and not c, p = (a and not b and not c) or (not a and b),
    # q = (a and not b and not c) or (not a and b and c).
    k = frozenset({0})
    p = frozenset({A, B, B | C})
    q = frozenset({A, B | C})
    assert satoh_revision(k, p, 3) == {A, B}
    assert satoh_revision(k, p & q, 3) == {A, B | C}
    assert km_violations(satoh_revision, k, p, q, 3) == ["R6"]
    assert dalal_revision(k, p, 3) == {A, B}
    assert dalal_revision(k, p & q, 3) == {A}
    assert km_violations(dalal_revision, k, p, q, 3) == []


def preorder_from_operator(op, k, n):
    """KM's construction: w <= v iff w is in Mod(K o form(w, v))."""
    return {(w, v) for w in worlds(n) for v in worlds(n) if w in op(k, {w, v}, n)}


@pytest.mark.parametrize("n", [1, 2, 3])
def test_km_construction_recovers_operator(n):
    rng = random.Random(6000 + n)
    bases = list(all_subsets(n)) if n <= 2 else [random_set(rng, n, 0.3) for _ in range(12)]
    preds = list(all_subsets(n)) if n <= 2 else [random_set(rng, n, 0.5) for _ in range(60)]
    for k in bases:
        le = preorder_from_operator(dalal_revision, k, n)
        ws = list(worlds(n))
        for w, v in itertools.product(ws, ws):
            assert (w, v) in le or (v, w) in le  # total
        for w, v, u in itertools.product(ws, ws, ws):
            if (w, v) in le and (v, u) in le:
                assert (w, u) in le  # transitive
        for w in k:
            for v in ws:
                if v not in k:
                    assert (w, v) in le and (v, w) not in le  # faithful, condition 2
            for v in k:
                assert (w, v) in le  # faithful, condition 1
        for p in preds:
            mins = frozenset(w for w in p if all((w, v) in le for v in p))
            assert mins == dalal_revision(k, p, n)

History

Dalal presented the operator at AAAI-88, defined by the iterated operator GG. He also gave GG on formulas: for each atom, take ψ\psi with that atom set to true or to false, which forgets the atom (a construction from Weber 1987), and join the results for all atoms with "or". He gave six principles for revision, among them the persistence of prior knowledge, and checked his operator against the Gardenfors postulates. Katsuno and Mendelzon (1991) gave the semantic characterization of the AGM postulates by faithful assignments and showed that Dalal's operator is an instance. Eiter and Gottlob (1992) placed it in the polynomial hierarchy. Its entailment problem is in PNP[O(log⁡n)]\mathrm{P}^{\mathrm{NP}[O(\log n)]}, while for the other operators of their study the general problem is Π2P\Pi_2^P-hard.

References

  1. Mukesh Dalal, Investigations into a theory of knowledge base revision: preliminary report, Proceedings of the Seventh National Conference on Artificial Intelligence (AAAI-88), 475 to 479 (1988), p. 476 (the operator G on models and the definition of revision by the least k) and p. 477 (the syntactic form of G and the check of the Gardenfors postulates)
  2. Hirofumi Katsuno and Alberto O. Mendelzon, Propositional knowledge base revision and minimal change, Artificial Intelligence 52(3), 263 to 294 (1991), Section 3 (the postulates R1 to R6 and the representation by faithful assignments) and the discussion of Dalal's operator as an instance
  3. Thomas Eiter and Georg Gottlob, On the complexity of propositional knowledge base revision, updates, and counterfactuals, Artificial Intelligence 57(2-3), 227 to 270 (1992), Section 3 (Example 3.3, and which operators satisfy R1 to R6), Theorem 6.9 (the general case), Theorem 7.4 (the Horn case) and Theorems 8.1 and 8.3 (bounded new formula)
  4. Thomas Eiter and Georg Gottlob, On the complexity of propositional knowledge base revision, updates, and counterfactuals, Proceedings of the Eleventh ACM Symposium on Principles of Database Systems (PODS 1992), the extended abstract of the journal paper

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.best
  • 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