Module contents
Lesson 22 of 23Advanced 110 min

Reasoning under uncertainty in symbolic systems: from certainty factors to probabilistic logic

Real-world rules have exceptions and evidence is noisy. Study why MYCIN certainty factors failed, the contributions and failures of Dempster–Shafer, and how possible-world semantics joins logic and probability. The computational core covers model counting (#SAT), weighted model counting, knowledge compilation and probabilistic logic programming with ProbLog, directly reusing the module’s SAT machinery.

After this lesson you can

  • Explain why certainty factors are incoherent with probability.
  • Calculate belief, plausibility and Dempster combinations and recognize their failures.
  • Reduce discrete probabilistic inference to weighted model counting.
  • Implement a model counter with component decomposition and caching.
  • Model uncertain knowledge with ProbLog and reason about its distribution semantics.

Before you start

The problem: rules with exceptions and noisy evidence

Production-system rules are logical truths: if premises hold, the conclusion is true. Expert knowledge brought to those systems rarely is. The expert-systems lesson showed a MYCIN rule:

IF the organism’s stain is gram-negative, morphology is bacillus, and it is anaerobic, THEN suggestive evidence (0.6) indicates it is Bacteroides.

The 0.6 says two things. First, the rule has exceptions: some anaerobic gram-negative bacilli are not Bacteroides, and listing all as negated premises is impossible (the qualification problem in nonmonotonic reasoning, which handles exceptions qualitatively without weights). Second, evidence is noisy: staining can fail, cultures become contaminated. A security operations analyst faces the same world: “IP on a reputation list” or “out-of-hours login” suggests account compromise, but does not prove it, and sources err.

We need a number per rule and a way to combine numbers when rules share a conclusion or chain. The lesson’s tension follows: rule systems want modularity, each rule contributing independently so rules can be added, removed and explained individually; probability is global, evidence value depending on everything else known. Three historic answers occupy the first half:

  1. MYCIN certainty factors, modular and, as Heckerman showed, probabilistically coherent only under independence assumptions rarely met.
  2. Dempster–Shafer theory, separating belief from plausibility and representing ignorance, but with a combination rule that misleads when sources conflict.
  3. Possible-worlds semantics, placing a probability distribution over models of a logical theory and joining both traditions.

The second half is computational. With possible worlds, query probability sums exponentially many models: weighted model counting, #SAT. You will see how to count with the module’s SAT machinery (DPLL, propagation, components and caching), how its trace is a compiled circuit answering thousands of queries, and how ProbLog packages this into logic programming where a rule with exceptions is written directly.

Certainty factors

MYCIN associates each rule and conclusion with a number in [−1,1][-1, 1]. Shortliffe and Buchanan (1975) defined it from two measures, belief and disbelief evidence EE adds to hypothesis HH:

MB(H,E)=max⁡{P(H∣E),P(H)}−P(H)1−P(H),MD(H,E)=P(H)−min⁡{P(H∣E),P(H)}P(H),\mathrm{MB}(H, E) = \frac{\max\{P(H \given E), P(H)\} - P(H)}{1 - P(H)}, \qquad \mathrm{MD}(H, E) = \frac{P(H) - \min\{P(H \given E), P(H)\}}{P(H)},

The certainty factor is their difference. Since one is always zero, it can be written as one expression.

In practice experts gave rule numbers directly, not probabilities, and the system combined them using three fixed functions without returning to probabilities.

  • Parallel combination. Rules E1⇒HE_1 \Rightarrow H and E2⇒HE_2 \Rightarrow H, factors xx and yy, merge into one rule with factor
x⊕y={x+y−xysi x,y≥0,x+y+xysi x,y<0,x+y1−min⁡(∣x∣,∣y∣)si tienen signos opuestos.x \oplus y = \begin{cases} x + y - xy & \text{si } x, y \ge 0, \\ x + y + xy & \text{si } x, y < 0, \\ \dfrac{x + y}{1 - \min(\abs{x}, \abs{y})} & \text{si tienen signos opuestos.} \end{cases}
  • Sequential combination. If E′⇒EE' \Rightarrow E has factor CF(E,E′)\mathrm{CF}(E, E') and E⇒HE \Rightarrow H has CF(H,E)\mathrm{CF}(H, E), chain E′⇒HE' \Rightarrow H has CF(H,E′)=CF(H,E)⋅max⁡{0,CF(E,E′)}\mathrm{CF}(H, E') = \mathrm{CF}(H, E)\cdot\max\{0, \mathrm{CF}(E, E')\}.
  • Compound premises. Conjunction takes the minimum premise factor, disjunction the maximum.

These functions have useful properties. Parallel combination is commutative and associative (evidence arrival order does not matter), has neutral element 00 and absorbing elements ±1\pm 1 (except undefined 1⊕(−1)1 \oplus (-1): one item proves HH and another refutes it), and x⊕(−x)=0x \oplus (-x) = 0. They are modular: a rule factor is used identically regardless of other knowledge (locality), and an obtained conclusion is used without inspecting provenance (detachment). Modularity was the point: each rule could be elicited and explained separately.

Why certainty factors are incoherent

David Heckerman analyzed the scheme in Probabilistic Interpretations for MYCIN’s Certainty Factors, presented at the first Uncertainty in Artificial Intelligence conference (1985) and published in proceedings edited by Kanal and Lemmer (1986). He found two things.

The original definition contradicts the combination functions. If CF\mathrm{CF} is defined as above, parallel combination should follow from probability, but does not. Worse, as an update rule the original definition does not commute. Heckerman’s example starts with P(H)=0.4P(H) = 0.4 and two evidence items with factors +0.7+0.7 and −0.5-0.5. Positive first: 0.7=(P−0.4)/0.60.7 = (P - 0.4)/0.6 gives P=0.82P = 0.82; then negative −0.5=(P′−0.82)/0.82-0.5 = (P' - 0.82)/0.82 gives P′=0.41P' = 0.41. In reverse, negative gives 0.20.2 and positive 0.760.76. Final belief depends on arrival order, exactly what combination functions forbid. The cause is asymmetry: positive evidence is measured against distance from P(H)P(H) to 1, negative against distance from P(H)P(H) to 0.

Combination functions do have a probabilistic reading, but a restrictive one. Heckerman treated desired factor properties (above) as axioms and sought probabilistic quantities satisfying them. All are monotone transformations of the likelihood ratio

λ(H,E)=P(E∣H)P(E∣¬H),O(H∣E)=λ(H,E) O(H),\lambda(H, E) = \frac{P(E \given H)}{P(E \given \neg H)}, \qquad O(H \given E) = \lambda(H, E)\, O(H),

where O(H)=P(H)/(1−P(H))O(H) = P(H)/(1 - P(H)) are odds and equality is Bayes’ theorem in odds form. One transformation reproduces MYCIN’s parallel combination exactly.

Proof

The inverse is g−1(c)=1/(1−c)g\inv(c) = 1/(1 - c) if c≥0c \ge 0 and g−1(c)=1+cg\inv(c) = 1 + c if c<0c < 0, with branches joining continuously at c=0c = 0, λ=1\lambda = 1. Check three cases of ⊕\oplus.

If x,y≥0x, y \ge 0: 1−(x⊕y)=1−x−y+xy=(1−x)(1−y)1 - (x \oplus y) = 1 - x - y + xy = (1 - x)(1 - y), so g−1(x⊕y)=11−x⋅11−yg\inv(x \oplus y) = \frac{1}{1 - x}\cdot\frac{1}{1 - y}.

If x,y<0x, y < 0: 1+(x⊕y)=1+x+y+xy=(1+x)(1+y)1 + (x \oplus y) = 1 + x + y + xy = (1 + x)(1 + y).

If x>0>yx > 0 > y, product λ=(1+y)/(1−x)\lambda = (1 + y)/(1 - x) is at least 1 exactly when x+y≥0x + y \ge 0, i.e. when ∣y∣≤x\abs{y} \le x and the minimum is ∣y∣\abs{y}. Then g(λ)=1−1−x1+y=x+y1+y=x+y1−∣y∣g(\lambda) = 1 - \frac{1 - x}{1 + y} = \frac{x + y}{1 + y} = \frac{x + y}{1 - \abs{y}}. If x+y<0x + y < 0, the minimum is xx and g(λ)=λ−1=x+y1−xg(\lambda) = \lambda - 1 = \frac{x + y}{1 - x}. Both match the third branch of ⊕\oplus. Case x<0<yx < 0 < y swaps roles because both expressions are symmetric.

Finally Bayes’ theorem in odds form yields O(H∣E1E2)=λ(H,E1E2) O(H)O(H \given E_1 E_2) = \lambda(H, E_1 E_2)\,O(H) unconditionally, and conditional independence given HH and ¬H\neg H factorizes P(E1E2∣H)=P(E1∣H)P(E2∣H)P(E_1 E_2 \given H) = P(E_1 \given H)P(E_2 \given H) and likewise ¬H\neg H, giving λ(H,E1E2)=λ(H,E1)λ(H,E2)\lambda(H, E_1 E_2) = \lambda(H, E_1)\lambda(H, E_2).

∎

Heckerman goes further: the appendix shows the modularity axiom (factor EE independent of previous evidence) forces that conditional independence in any probabilistic interpretation, and propagation through a rule network is coherent only if the network is a tree. MYCIN’s sequential combination admits no probabilistic interpretation: it implicitly assumes CF(H,¬E)=0\mathrm{CF}(H, \neg E) = 0, i.e. absence of EE says nothing about HH. In his example “likes parties” (+0.8+0.8) and “likes solo hikes” (−0.5-0.5) inform “is extroverted”, which informs “does volunteer work” (+0.4+0.4). The probabilistic version needs one more number, the effect of not being extroverted on volunteering, fixed at −0.4-0.4. With only the second evidence MYCIN concludes change 0 in volunteering because maximum with 0 cuts the chain, while the probabilistic interpretation gives −0.2-0.2: lower extroversion probability does convey information.

[ ]MYCIN versus BayesBrowser
import numpy as np

def combinar(x, y):
    """Combinación paralela de MYCIN (dos reglas con la misma conclusión)."""
    if x >= 0 and y >= 0:
        return x + y - x * y
    if x < 0 and y < 0:
        return x + y + x * y
    return (x + y) / (1 - min(abs(x), abs(y)))

def cf_de_lambda(lam):
    """Interpretación de Heckerman que reproduce exactamente la regla de MYCIN."""
    return (lam - 1) / lam if lam >= 1 else lam - 1

def lambda_de_cf(cf):
    return 1 / (1 - cf) if cf >= 0 else 1 + cf

def posterior(prior, lam):
    o = lam * prior / (1 - prior)
    return o / (1 + o)

rng = np.random.default_rng(0)
trios = rng.uniform(-0.99, 0.99, size=(20000, 3))
e_prod = max(abs(lambda_de_cf(combinar(x, y)) / (lambda_de_cf(x) * lambda_de_cf(y)) - 1) for x, y, _ in trios)
e_asoc = max(abs(combinar(combinar(x, y), z) - combinar(x, combinar(y, z))) for x, y, z in trios)
print(f"máx error relativo de λ(x ⊕ y) = λ(x)·λ(y): {e_prod:.1e}")
print(f"máx |(x ⊕ y) ⊕ z − x ⊕ (y ⊕ z)|:           {e_asoc:.1e}")

def actualizar_original(p, cf):
    """Definición de Shortliffe y Buchanan despejada: de (prior, CF) a la posterior."""
    return p + cf * (1 - p) if cf >= 0 else p + cf * p

p1 = actualizar_original(actualizar_original(0.4, 0.7), -0.5)
p2 = actualizar_original(actualizar_original(0.4, -0.5), 0.7)
print(f"\ndefinición original, prior 0.4: +0.7 y luego −0.5 → {p1:.2f};  al revés → {p2:.2f}")
print(f"combinación de MYCIN de los mismos números: {combinar(0.7, -0.5):.2f} en cualquier orden")

The first two lines’ errors are rounding (10−1310^{-13} and 10−1410^{-14}): the theorem’s identity is exact and combination associative. Two updates of the original definition reproduce Heckerman’s 0.410.41 versus 0.760.76.

Correlated evidence: double counting

The theorem says when MYCIN works. In practice it breaks on evidence not conditionally independent, most commonly because two rules ultimately read the same fact. Imagine detection rules “source IP is on reputation list A ⇒\Rightarrow compromised account”, likewise lists B and C. If lists share sources, the IP appearing in B after A adds little. Yet each rule evaluated alone is correct: its factor matches its likelihood ratio. The problem is combining them.

The interactive’s model is explicit. HH means “compromised account” with prior P(H)P(H). Each list alone flags an IP with P(marca∣H)=0.5P(\text{marca} \given H) = 0.5 and P(marca∣¬H)=0.5/λP(\text{marca} \given \neg H) = 0.5/\lambda, so its rule has CF=(λ−1)/λ\mathrm{CF} = (\lambda - 1)/\lambda. List A decides independently; each other list copies A’s flag with probability cc or decides independently with the same rates. Thus each retains exactly the same marginal reliability for any cc, with only dependence changing. “Out-of-hours login” evidence, with λ=2\lambda = 2, is independent of everything else.

InteractiveWhen certainty factors mislead
List A0.75List B0.75List C0.75After hours0.50B, C... copy A's flag with probability c = 1.00Hcompromised
According to MYCIN CFs
87.1 %
Correct probability
29.6 %
The black mark on the bars is the prior.
Posterior versus number of lists, with c=1.00c = 1.00
  • MYCIN CFs read as probabilities
  • probability with exact joint distribution
0.05
3
1.00
4.0
CF for each list rule0.750
Combined CF (MYCIN)0.9922
λ\lambda assumed by MYCIN128
Actual λ\lambda of the evidence8.00
P(H∣evidence)P(H \mid \text{evidence}) according to CFs87.1 %
Correct P(H∣evidence)P(H \mid \text{evidence})29.6 %
MYCIN multiplies the odds by 128 where the evidence justifies only 8.0: it counts 2.3 times the information available.
Left: rules concluding HH with certainty factors; right: their claims. Red translates combined CF to probability under Heckerman's interpretation; blue is correct probability from the model's joint law. With c=1c = 1, B and C copy A: increase list count and watch CF approach 1 while probability stays fixed. Reduce cc to 0 and the lower curves merge: MYCIN's assumed conditional independence.

With initial values (prior 0.050.05, three lists with λ=4\lambda = 4 and c=1c = 1, plus out-of-hours login), MYCIN multiplies odds by 43⋅2=1284^3 \cdot 2 = 128 and concludes 87.1 %87.1\,\%; real evidence justifies only 4⋅2=84 \cdot 2 = 8, 29.6 %29.6\,\%. In evidence-weight units log⁡λ\log \lambda, it counts information log⁡128/log⁡8=7/3\log 128 / \log 8 = 7/3 times. The next cell checks the interactive’s closed formula by summing the complete joint law, including latent copy variables, without time-of-day evidence:

[ ]Copied lists: summing the joint distributionBrowser
import itertools
import matplotlib.pyplot as plt

def posterior_enumerando(prior, a, b, n, c):
    """P(H | las n listas marcan) sumando la ley conjunta: H, la marca de A y,
    para cada otra lista, si copia a A y cuál sería su marca propia."""
    num = den = 0.0
    for h in (1, 0):
        ph = prior if h else 1 - prior
        q = a if h else b                                  # P(marca propia | h)
        for mA in (1, 0):
            pA = q if mA else 1 - q
            for resto in itertools.product((1, 0), repeat=2 * (n - 1)):
                p, todas = ph * pA, mA == 1
                for copia, propia in zip(resto[::2], resto[1::2]):
                    p *= (c if copia else 1 - c) * (q if propia else 1 - q)
                    todas &= (mA if copia else propia) == 1
                if todas:
                    den += p
                    num += p * h
    return num / den

def posterior_mycin(prior, a, b, n):
    cf1 = cf_de_lambda(a / b)
    cf = cf1
    for _ in range(n - 1):
        cf = combinar(cf, cf1)
    return posterior(prior, lambda_de_cf(cf)), cf

prior, a, b = 0.05, 0.5, 0.125                             # cada lista sola: λ = 4, CF = 0.75
print(f"{'n':>2} {'CF MYCIN':>9} {'P según CF':>11} {'P (c = 1)':>10} {'P (c = 0.5)':>12} {'P (c = 0)':>10}")
for n in range(1, 7):
    pm, cfn = posterior_mycin(prior, a, b, n)
    fila = [posterior_enumerando(prior, a, b, n, c) for c in (1.0, 0.5, 0.0)]
    print(f"{n:>2} {cfn:>9.4f} {pm:>11.4f} {fila[0]:>10.4f} {fila[1]:>12.4f} {fila[2]:>10.4f}")

ns = range(1, 7)
plt.plot(ns, [posterior_mycin(prior, a, b, n)[0] for n in ns], "o-", label="CF de MYCIN")
for c, ls in ((1.0, "-"), (0.5, "--"), (0.0, ":")):
    plt.plot(ns, [posterior_enumerando(prior, a, b, n, c) for n in ns], ls, marker="s", label=f"probabilidad, c = {c}")
plt.xlabel("listas que marcan la IP"); plt.ylabel("P(H | evidencia)"); plt.legend(); plt.show()

With c=1c = 1 the correct posterior remains 0.17390.1739 for any list count, that of one list, while MYCIN moves from 0.17390.1739 to 0.99540.9954 with six. With c=0c = 0 lists are truly independent evidence and columns agree. With c=0.5c = 0.5, the realistic case, probability grows slowly (0.21920.2192, 0.27230.2723, … to 0.47010.4701) and MYCIN remains far above. Naive Bayes makes the same assumption: adding evidence weights log⁡λi\log \lambda_i is correct exactly under conditional independence. Heckerman notes Peirce proposed that evidence weight in 1878, Turing and Good rediscovered it, and INTERNIST-1’s score closely resembles it. Any risk score adding indicators makes the interactive’s error when two measure the same thing.

Dempster–Shafer theory

Certainty factors have a subtler flaw: one number cannot distinguish “I know nothing about HH” from “balanced evidence for and against”. Nor can one probability: P(H)=0.5P(H) = 0.5 means both. Arthur Dempster (1967) and Glenn Shafer (A Mathematical Theory of Evidence, 1976) built a theory where evidence supports a set of hypotheses without distributing support among its elements.

m(A)m(A) is mass evidence assigns exactly to AA without knowing how to split it. Belief Bel(A)\mathrm{Bel}(A) sums what implies AA; plausibility Pl(A)\mathrm{Pl}(A) what is compatible with AA. Always Bel(A)≤Pl(A)\mathrm{Bel}(A) \le \mathrm{Pl}(A) and Bel(A)+Bel(¬A)≤1\mathrm{Bel}(A) + \mathrm{Bel}(\neg A) \le 1: the gap is ignorance. Two extremes clarify. Vacuous mass m(Θ)=1m(\Theta) = 1 yields Bel(A)=0\mathrm{Bel}(A) = 0 and Pl(A)=1\mathrm{Pl}(A) = 1 for every A≠ΘA \neq \Theta: I know nothing. A Bayesian mass with singleton focal elements gives Bel=Pl=P\mathrm{Bel} = \mathrm{Pl} = P: a probability.

Dempster’s reading explains the rest. A witness is reliable with probability 0.80.8 and says “it was aa”. If reliable the culprit is in {a}\{a\}; otherwise testimony says nothing and the culprit is in Θ\Theta. Mass is m({a})=0.8m(\{a\}) = 0.8, m(Θ)=0.2m(\Theta) = 0.2: a probability over witness states Ω\Omega transferred to 2Θ2^\Theta by multivalued mapping Γ:Ω→2Θ\Gamma: \Omega \to 2^\Theta with m(A)=P(Γ(ω)=A)m(A) = P(\Gamma(\omega) = A). Thus Bel\mathrm{Bel} and Pl\mathrm{Pl} are lower and upper probabilities: every distribution over Θ\Theta compatible with the testimony satisfies Bel(A)≤P(A)≤Pl(A)\mathrm{Bel}(A) \le P(A) \le \mathrm{Pl}(A).

Combination rule

Two independent sources, with mappings Γ1\Gamma_1 and Γ2\Gamma_2, point to Γ1(ω1)∩Γ2(ω2)\Gamma_1(\omega_1) \cap \Gamma_2(\omega_2). If the intersection is empty, source states conflict: Dempster discards them and conditions on compatibility.

It is commutative and associative, vacuous mass is neutral, and if either mass is Bayesian the result is too: with Bayesian masses pp and qq, (p⊕q)({θ})=pθqθ/∑θ′pθ′qθ′(p \oplus q)(\{\theta\}) = p_\theta q_\theta / \sum_{\theta'} p_{\theta'} q_{\theta'}, Bayes’ rule with two likelihoods and uniform prior. General computation is expensive: Orponen (1990) proved evaluating Dempster’s rule #P-complete, a first sign counting is central.

[ ]Dempster-Shafer from scratchBrowser
from itertools import combinations
import numpy as np

def masa(**kw):
    """masa(a=0.5, ab=0.3, abc=0.2): cada clave es un subconjunto del marco escrito como cadena."""
    return {frozenset(k): v for k, v in kw.items()}

def creencia(m, A):
    return sum(v for B, v in m.items() if B <= A)

def plausibilidad(m, A):
    return sum(v for B, v in m.items() if B & A)

def combinar_ds(m1, m2, regla="dempster", marco=None):
    bruto, K = {}, 0.0
    for B, x in m1.items():
        for C, y in m2.items():
            I = B & C
            if I:
                bruto[I] = bruto.get(I, 0.0) + x * y
            else:
                K += x * y
    if regla == "dempster":
        if K >= 1:
            raise ValueError("conflicto total: la regla de Dempster no está definida")
        return {A: v / (1 - K) for A, v in bruto.items()}, K
    if regla == "yager":                                   # el conflicto pasa a ser ignorancia
        bruto[marco] = bruto.get(marco, 0.0) + K
        return bruto, K
    raise ValueError(regla)

def mostrar(m):
    orden = sorted(m.items(), key=lambda t: (len(t[0]), sorted(t[0])))
    return "  ".join(f"{''.join(sorted(A))}: {v:.4f}" for A, v in orden)

m1 = masa(a=0.5, ab=0.3, abc=0.2)
m2 = masa(b=0.6, bc=0.2, abc=0.2)
m12, K = combinar_ds(m1, m2)
print("K =", round(K, 4), "  m1 ⊕ m2 →", mostrar(m12))
for h in "abc":
    A = frozenset(h)
    print(f"  {h}: Bel = {creencia(m12, A):.4f}   Pl = {plausibilidad(m12, A):.4f}")

# el ejemplo de Zadeh: dos médicos casi opuestos
z1, z2 = masa(M=0.99, T=0.01), masa(C=0.99, T=0.01)
mz, Kz = combinar_ds(z1, z2)
print("\nZadeh, Dempster: K =", round(Kz, 4), " ", mostrar(mz))
my, _ = combinar_ds(z1, z2, "yager", frozenset("MCT"))
print("Zadeh, Yager:              ", mostrar(my))

# masas bayesianas: Dempster es el producto normalizado; la masa vacía es el neutro
p, q = np.array([0.6, 0.3, 0.1]), np.array([0.2, 0.5, 0.3])
mb, _ = combinar_ds(masa(a=p[0], b=p[1], c=p[2]), masa(a=q[0], b=q[1], c=q[2]))
print("\nbayesianas:", mostrar(mb), "  producto normalizado:", np.round(p * q / (p @ q), 4))
print("con la masa vacía:", mostrar(combinar_ds(m1, masa(abc=1.0))[0]))

# asociatividad en masas aleatorias sobre los 7 subconjuntos
subs = [frozenset(s) for r in (1, 2, 3) for s in combinations("abc", r)]
g = np.random.default_rng(1)
peor = 0.0
for _ in range(300):
    x, y, z = (dict(zip(subs, g.dirichlet(np.ones(7)))) for _ in range(3))
    izq = combinar_ds(combinar_ds(x, y)[0], z)[0]
    der = combinar_ds(x, combinar_ds(y, z)[0])[0]
    peor = max(peor, max(abs(izq.get(A, 0) - der.get(A, 0)) for A in subs))
print(f"máx diferencia (x⊕y)⊕z frente a x⊕(y⊕z) en 300 tríos: {peor:.1e}")

In the first example, 40% of mass is conflict (one source’s {a}\{a\} clashes with the other’s {b}\{b\} and {b,c}\{b, c\}), and the rest is rescaled by 1/0.61/0.6. Hypothesis bb gets Bel=0.6\mathrm{Bel} = 0.6 and Pl=0.8333\mathrm{Pl} = 0.8333; cc gets Bel=0\mathrm{Bel} = 0 but Pl=0.1333\mathrm{Pl} = 0.1333: nothing supports it, but something is compatible.

Zadeh’s critique

Lotfi Zadeh, reviewing Shafer’s book (AI Magazine, 1984), proposed his namesake example. One physician believes meningitis with probability 0.990.99 or tumor 0.010.01; another contusion 0.990.99 or tumor 0.010.01. Both consider tumor unlikely. Dempster’s rule gives conflict K=0.9999K = 0.9999 and after normalization m({T})=1m(\{T\}) = 1: certainty in what neither believed. The cell shows it; the interactive shows why.

InteractiveDempster combination
∅{T}: 0.0001MC
Columns: focal sets of m1m_1. Rows: focal sets of m2m_2. Area = product of masses; color = intersection.
[Bel,Pl][\mathrm{Bel}, \mathrm{Pl}] interval for each hypothesis
{M}
m1m_1
[0.99, 0.99]
m2m_2
[0.00, 0.00]
m1⊕m2m_1 \oplus m_2
[0.00, 0.00]
{C}
m1m_1
[0.00, 0.00]
m2m_2
[0.99, 0.99]
m1⊕m2m_1 \oplus m_2
[0.00, 0.00]
{T}
m1m_1
[0.01, 0.01]
m2m_2
[0.01, 0.01]
m1⊕m2m_1 \oplus m_2
[1.00, 1.00]
Solid segment: belief (mass implying the hypothesis). Light segment: additional mass compatible with it.
Rule
Edit
0.99
0.00
0.01
0.00
0.00
0.00
m1(Θ)=0.00m_1(\Theta) = 0.00 (remainder)
Conflict KK0.9999
Combined mass{T}: 1.0000
The sources contradict each other on 99.99 % of the mass. Dempster discards that conflict and distributes the remaining 0.01 % as if it were all: the result reflects neither source.
The square is the orthogonal sum: each column is a focal element of source 1, each row of source 2, their rectangle area m1(B) m2(C)m_1(B)\,m_2(C) and color of B∩CB \cap C. Red-hatched rectangles have empty intersection: total area is conflict KK. Start with Zadeh's example: nearly all is red, and Dempster rescales the tiny surviving corner to fill it. Switch to Yager and inspect where conflict goes. Then try an ignorant source and two Bayesian sources.

The rule’s interpretation explains it: Dempster conditions on “the two sources are compatible”, here probability 1−K=0.00011 - K = 0.0001. High conflict discards nearly all evidence, leaving a residue representing neither. Haenni (2005) argued the issue is modeling (experts so confident and opposed cannot both be reliable independent sources) rather than the rule; either way high KK calls for model review, not normalization. Alternatives change conflict’s destination: Yager (1987) assigns it to Θ\Theta, acknowledging ignorance (m(Θ)=0.9999m(\Theta) = 0.9999 in the example), while Smets’ transferable belief model leaves it in m(∅)m(\emptyset) as a signal the frame may be incomplete.

Vagueness is not uncertainty

Fuzzy logic (Zadeh, 1965), popularized around the same time, is often conflated with uncertainty. It addresses something else. “Juan is tall”, with Juan 1.78 m, is not uncertain: height is known exactly. The predicate “tall” is gradual, and fuzzy logic assigns membership degree μalto(1.78)=0.7\mu_{\text{alto}}(1.78) = 0.7. Probability measures uncertainty about a crisp fact, like “it will rain tomorrow”.

The difference is formal. Fuzzy logic is truth-functional: the degree of A∧BA \wedge B is a function of degrees of AA and BB (minimum in Zadeh’s proposal). Probability cannot be: P(A)P(A) and P(B)P(B) only bound P(A∧B)P(A \wedge B) between max⁡{0,P(A)+P(B)−1}\max\{0, P(A) + P(B) - 1\} and min⁡{P(A),P(B)}\min\{P(A), P(B)\} (Fréchet bounds), with any intermediate value possible depending on dependence. With P(A)=P(B)=0.5P(A) = P(B) = 0.5, P(A∧B)P(A \wedge B) is 0.50.5 if B=AB = A, 0.250.25 if independent and 00 if B=¬AB = \neg A; fuzzy minimum says 0.50.5 in all three, also for “AA and not AA”, impossible probabilistically. Fuzzy operators for uncertainty again ignore dependence.

Possible worlds: semantics joining logic and probability

The previous three proposals invent calculi. The alternative is to take propositional logic unchanged and put a probability distribution over its models.

Everything you know about logic and probability still holds: PP is a distribution over an nn-bit random vector, formulas are events. Valid formulas have probability 1, equivalent ones the same probability, and conditional probability is unchanged. Two consequences:

  • Material implication is not a rule. P(A→B)=P(¬A∨B)P(A \to B) = P(\neg A \vee B) is not P(B∣A)P(B \given A). Since P(¬A∨B)=P(¬A)+P(A) P(B∣A)P(\neg A \vee B) = P(\neg A) + P(A)\,P(B \given A), P(A→B)−P(B∣A)=P(¬A) (1−P(B∣A))≥0P(A \to B) - P(B \given A) = P(\neg A)\,(1 - P(B \given A)) \ge 0 holds: material implication is at least as probable, much more if AA is rare. A rule with exceptions “AA usually implies BB” uses the conditional, not the arrow.
  • Knowing probabilities of some formulas bounds, not determines, another’s. This is Nilsson’s probabilistic logic (1986): constraints are linear in 2n2^n unknowns P(ω)P(\omega), and minimum and maximum P(φ)P(\varphi) come from two linear programs.
[ ]Nilsson probabilistic logic: bounds by linear programmingBrowser
import itertools
from scipy.optimize import linprog

def cotas(n, restricciones, consulta):
    """Mín y máx de P(consulta) sobre todas las distribuciones en {0,1}^n que cumplen P(f) = p para cada (f, p)."""
    mundos = list(itertools.product((1, 0), repeat=n))
    fila = lambda f: [1.0 if f(*w) else 0.0 for w in mundos]
    A = [fila(f) for f, _ in restricciones] + [[1.0] * len(mundos)]
    b = [p for _, p in restricciones] + [1.0]
    c = fila(consulta)
    lo = linprog(c, A_eq=A, b_eq=b, bounds=(0, 1)).fun
    hi = -linprog([-x for x in c], A_eq=A, b_eq=b, bounds=(0, 1)).fun
    return f"[{lo + 0.0:.2f}, {hi + 0.0:.2f}]"           # + 0.0 convierte un −0.0 en 0.0

# modus ponens probabilístico
print("P(A) = 0.7, P(A → B) = 0.8   ⟹  P(B) ∈", cotas(2, [(lambda A, B: A, 0.7), (lambda A, B: (not A) or B, 0.8)], lambda A, B: B))
# conocer P(B | A) = 0.8 en lugar de P(A → B) = 0.8
print("P(A) = 0.7, P(B | A) = 0.8   ⟹  P(B) ∈", cotas(2, [(lambda A, B: A, 0.7), (lambda A, B: A and B, 0.56)], lambda A, B: B))
# las cotas de Fréchet: dos marginales no fijan la conjunción
print("P(A) = P(B) = 0.5            ⟹  P(A ∧ B) ∈", cotas(2, [(lambda A, B: A, 0.5), (lambda A, B: B, 0.5)], lambda A, B: A and B))
print("                                  P(A ∧ ¬A) =", cotas(1, [(lambda A: A, 0.5)], lambda A: A and not A))

With P(A)=0.7P(A) = 0.7 and P(A→B)=0.8P(A \to B) = 0.8, P(B)P(B) can range from 0.50.5 to 0.80.8; conditional P(B∣A)=0.8P(B \given A) = 0.8 (i.e. P(A∧B)=0.56P(A \wedge B) = 0.56) changes the interval to [0.56,0.86][0.56, 0.86]. Marginals 0.50.5 and 0.50.5 leave P(A∧B)P(A \wedge B) throughout [0,0.5][0, 0.5], as Fréchet bounds said.

Independence as representation

An arbitrary distribution over Ω\Omega needs 2n−12^n - 1 numbers: over a billion for 30 atoms. No one can elicit or store them. The familiar Bayesian-network solution assumes conditional independences factorizing the distribution into small pieces. Independence is not just a property: it is how the distribution is written.

For rule systems one factorization is natural. Take mutually independent probabilistic facts f1,…,fmf_1, \dots, f_m with P(fi)=piP(f_i) = p_i, and deterministic rules defining other atoms from them. Each fact choice fixes one world by the rules, and its probability is a product:

P(ω)=∏i: fi∈ωpi∏i: fi∉ω(1−pi).P(\omega) = \prod_{i:\ f_i \in \omega} p_i \prod_{i:\ f_i \notin \omega} (1 - p_i).

MYCIN’s rule with exceptions is then written without a rule number: bacteroides←gramneg∧bacilo∧anaerobio∧r1\mathit{bacteroides} \leftarrow \mathit{gramneg} \wedge \mathit{bacilo} \wedge \mathit{anaerobio} \wedge r_1 with fact r1r_1 of probability pp saying “the rule applies in this case”. Exceptions are worlds where r1r_1 is false. Note pp is the fraction of premise-matching cases where the conclusion holds, a conditional probability to estimate; MYCIN’s 0.60.6 is not, since certainty factors measure belief change. Something certainty factors could not do comes for free: observing the conclusion raises cause probabilities (effect-to-cause reasoning), and one cause explaining the conclusion weakens others (explaining away), because all conditions one distribution. Binary Bayesian networks can be written this way losslessly: each conditional probability table entry is a probabilistic fact. This is ProbLog’s idea, seen later.

Computation remains: P(φ)P(\varphi) sums 2m2^m terms, one per fact choice. We must count.

Counting models: #SAT

#SAT is the archetypal #P-complete problem: it is in #P because it counts witnesses of an NP problem, and complete because Cook–Levin reductions preserve witness counts. Counting is much harder than decision. Valiant (1979) proved counting models of a monotone two-literal-per-clause CNF is already #P-complete, although deciding 2-SAT is in P (and this formula is satisfied by setting all true). Toda’s theorem (1991) gives a #P oracle enough power for the entire polynomial hierarchy: PH⊆P#P\mathrm{PH} \subseteq \mathrm{P}^{\#\mathrm{P}}.

Counting DPLL

The exact algorithm starts with familiar DPLL with three changes:

  1. Do not stop at the first model. Branch on xx and add: #F=#(F∣x)+#(F∣¬x)\#F = \#(F \given x) + \#(F \given \neg x), where F∣xF \given x is FF simplified with xx true. If a branch empties all clauses with kk variables unassigned, it contributes 2k2^k models.
  2. Decompose into components. If F=F1∧F2F = F_1 \wedge F_2 and F1F_1, F2F_2 share no variables, #F=#F1⋅#F2\#F = \#F_1 \cdot \#F_2, because each model of FF is a pair of independent models. After a few decisions the residual formula often splits: CSP tree decomposition applied dynamically.
  3. Cache each solved component. The same residual formula appears through different search paths; caching counts it once.

Bacchus, Dalmao and Pitassi (2003) proved component-caching DPLL theoretically competitive with the best Bayesian inference methods, exponential in treewidth. In practice the key was combining caching with CDCL conflict-analysis clause learning, nontrivial because learned clauses cross components and grow without bound. Sang, Bacchus, Beame, Kautz and Pitassi (2004) solved this by analyzing components on the original formula without learned clauses. Their Cachet counter was often orders of magnitude faster than relsat, which decomposes but does not cache: on five random 75-variable 3-CNFs at ratio 1.0, their figure 2 times run 3809–31660 for relsat and 2–20 for Cachet, over three orders of magnitude, and Cachet recorded about twice as many cache hits as decisions.

Lab: a counter from scratch

The counter implements all three changes. It represents CNF as lists of literal sets (signed integers as in DIMACS), simplifies by copying (no watched literals, for readability), and accepts literal weights from the start: all weights 1 count models; next section explains others. The branching variable appears most frequently in the component, as in Cachet.

[ ]#SAT and WMC from scratch: the counterBrowser
import itertools, random
from collections import defaultdict

def asignar(clausulas, lit):
    """Hace cierto lit: quita las cláusulas satisfechas y el literal opuesto. None si alguna se vacía."""
    salida = []
    for c in clausulas:
        if lit in c:
            continue
        if -lit in c:
            c = c - {-lit}
            if not c:
                return None
        salida.append(c)
    return salida

def propagar(clausulas):
    """Propagación unitaria: (cláusulas restantes, literales forzados), o (None, None) si hay conflicto."""
    forzados = []
    while True:
        unidad = next((c for c in clausulas if len(c) == 1), None)
        if unidad is None:
            return clausulas, forzados
        (lit,) = unidad
        forzados.append(lit)
        clausulas = asignar(clausulas, lit)
        if clausulas is None:
            return None, None

def componentes(clausulas):
    """Agrupa las cláusulas que comparten variables (union-find sobre las variables)."""
    padre = {}
    def raiz(v):
        while padre.setdefault(v, v) != v:
            padre[v] = padre[padre[v]]
            v = padre[v]
        return v
    for c in clausulas:
        vs = [abs(l) for l in c]
        for v in vs[1:]:
            padre[raiz(v)] = raiz(vs[0])
    grupos = defaultdict(list)
    for c in clausulas:
        grupos[raiz(abs(next(iter(c))))].append(c)
    return list(grupos.values())

class Contador:
    """WMC exacto: DPLL con propagación unitaria, componentes y caché de componentes.
    w[l] es el peso del literal l (±v). Con todos los pesos a 1 cuenta modelos (#SAT)."""
    def __init__(self, w, cache=True):
        self.w, self.usar_cache = w, cache
        self.cache, self.llamadas, self.aciertos = {}, 0, 0

    def contar(self, clausulas, variables):
        """WMC de la conjunción de 'clausulas' sobre 'variables' (las que no aparecen quedan libres)."""
        clausulas, forzados = propagar(clausulas)
        if clausulas is None:
            return 0.0
        r = 1.0
        for l in forzados:
            r *= self.w[l]
        usadas = {abs(l) for l in forzados}
        for comp in componentes(clausulas):
            vs = {abs(l) for c in comp for l in c}
            usadas |= vs
            r *= self.contar_componente(comp, vs)
            if r == 0.0:
                return 0.0
        for v in variables - usadas:                      # libres: cualquier valor sirve
            r *= self.w[v] + self.w[-v]
        return r

    def contar_componente(self, comp, vs):
        self.llamadas += 1
        clave = frozenset(comp)
        if self.usar_cache and clave in self.cache:
            self.aciertos += 1
            return self.cache[clave]
        frecuencia = defaultdict(int)
        for c in comp:
            for l in c:
                frecuencia[abs(l)] += 1
        x = max(frecuencia, key=lambda v: (frecuencia[v], -v))   # la variable que más aparece
        total = 0.0
        for lit in (x, -x):
            sub = asignar(comp, lit)
            if sub is not None:
                total += self.w[lit] * self.contar(sub, vs - {x})
        if self.usar_cache:
            self.cache[clave] = total
        return total

def wmc(clausulas, variables, w, cache=True):
    c = Contador(w, cache)
    return c.contar([frozenset(x) for x in clausulas], set(variables)), c

def wmc_enumerando(clausulas, variables, w):
    variables, total = sorted(variables), 0.0
    for signos in itertools.product((1, -1), repeat=len(variables)):
        a = {v * s for v, s in zip(variables, signos)}
        if all(any(l in a for l in c) for c in clausulas):
            p = 1.0
            for l in a:
                p *= w[l]
            total += p
    return total

azar = random.Random(0)
for _ in range(300):
    n = azar.randint(1, 9)
    cls = [{azar.choice((1, -1)) * azar.randint(1, n) for _ in range(azar.randint(1, 3))} for _ in range(azar.randint(0, 14))]
    cls = [c for c in cls if not any(-l in c for l in c)]
    w = {s * v: azar.random() for v in range(1, n + 1) for s in (1, -1)}
    a, _ = wmc(cls, range(1, n + 1), w)
    assert abs(a - wmc_enumerando(cls, range(1, n + 1), w)) <= 1e-9 * max(1, a)
uno = {s * v: 1.0 for v in range(1, 4) for s in (1, -1)}
print("300 FNC aleatorias con pesos aleatorios: el contador coincide con la enumeración")
print("#SAT de (x1 ∨ x2) ∧ (¬x2 ∨ x3):", wmc([[1, 2], [-2, 3]], {1, 2, 3}, uno)[0])

Enumeration checks use arbitrary weights, not just ones, and CNFs with free variables, repeated clauses and unsatisfiable formulas. The final example gives 4: of 8 assignments, x1=x2=0x_1 = x_2 = 0 violates the first clause (2 assignments according to x3x_3) and x2=1,x3=0x_2 = 1, x_3 = 0 violates the second (another 2).

Weighted model counting

With w≡1w \equiv 1 this is #SAT. With w(x)=pw(x) = p and w(¬x)=1−pw(\neg x) = 1 - p per variable, each assignment weighs its independent-variable probability, and WMC(F,w)=P(F)\mathrm{WMC}(F, w) = P(F). The counter already calculates it: multiply the decided literal’s weight in branches, forced literal weights in propagation, and for each free variable w(x)+w(¬x)w(x) + w(\neg x) instead of 2.

Probabilistic inference as WMC

Return to possible-world factorization: independent probabilistic facts and deterministic rules. For an acyclic definite program with rules RR, Clark completion writes each derived atom hh as equivalent to the disjunction of its rule bodies h↔⋁(h←B)∈R⋀Bh \leftrightarrow \bigvee_{(h \leftarrow B) \in R} \bigwedge B (with hh false if no rules). Let Δ\Delta be that formula converted to CNF by Tseitin transformation (one auxiliary variable per multi-atom body). Weights are w(f)=pfw(f) = p_f and w(¬f)=1−pfw(\neg f) = 1 - p_f per fact, and w(d)=w(¬d)=1w(d) = w(\neg d) = 1 for derived and auxiliary atoms.

The idea: Δ\Delta adds no uncertainty. In an acyclic program each fact choice has one unique extending model of Δ\Delta, and derived atoms, weight 1 on either literal, do not change the product. You prove this step by step in the guided exercise. With normalized fact weights WMC(Δ)=1\mathrm{WMC}(\Delta) = 1, but the denominator matters with evidence or unnormalized weights, as in Markov logic networks.

Chavira and Darwiche (2008) studied encodings with an indicator variable per value of each variable and a parameter variable per table entry. Their advantage over variable elimination is local structure: parameter 0 or 1 becomes a clause unit propagation exploits (determinism), and equal parameters within a table let the counter decompose where graph structure does not (context-specific independence). Variable elimination and weighted counting are sides of the same calculation; the latter also sees numbers.

Lab: risk in an attack network

A typical defensive analysis models how compromise of one machine can propagate to others. Each possible entry (exposed web server, VPN, a workstation compromised by phishing) and each step between machines (unpatched vulnerability, reused credentials) is a fact with the probability that condition exists. Two rules: a machine is compromised if it is an active entry, or another compromised machine has a step to it. With this example’s probabilities (illustrative, not measured), ask the database’s risk and, if backup falls, the likely entry.

[ ]#SAT and WMC from scratch: from program to CNFBrowser
class Programa:
    """Programa definido acíclico y ya instanciado, con hechos probabilísticos p::f."""
    def __init__(self):
        self.ids, self.nombres, self.w = {}, [], {}
        self.hechos, self.reglas = {}, defaultdict(list)

    def var(self, atomo):
        if atomo not in self.ids:
            self.nombres.append(atomo)
            v = self.ids[atomo] = len(self.nombres)
            self.w[v] = self.w[-v] = 1.0           # derivados y auxiliares: peso 1 a los dos literales
        return self.ids[atomo]

    def hecho(self, p, atomo):
        v = self.var(atomo)
        self.hechos[atomo] = p
        self.w[v], self.w[-v] = p, 1 - p

    def regla(self, cabeza, *cuerpo):
        self.var(cabeza)
        for a in cuerpo:
            self.var(a)
        self.reglas[cabeza].append(cuerpo)

    def cnf(self):
        """Compleción de Clark, con una variable de Tseitin por cada cuerpo de más de un átomo."""
        cls = []
        for h in [a for a in self.nombres if a not in self.hechos and a[0] != "aux"]:
            hv, cuerpos = self.ids[h], []
            for k, cuerpo in enumerate(self.reglas.get(h, [])):
                if len(cuerpo) == 1:
                    cuerpos.append(self.ids[cuerpo[0]])
                    continue
                b, lits = self.var(("aux", h, k)), [self.ids[a] for a in cuerpo]
                cls += [[-b, l] for l in lits] + [[b] + [-l for l in lits]]   # b ↔ ∧ cuerpo
                cuerpos.append(b)
            cls.append([-hv] + cuerpos)               # h → ∨ cuerpos (sin reglas: h falso)
            cls += [[hv, -b] for b in cuerpos]        # cada cuerpo → h
        return cls

    def modelo_minimo(self, ciertos):
        M, cambio = set(ciertos), True
        while cambio:
            cambio = False
            for h, cuerpos in self.reglas.items():
                if h not in M and any(all(a in M for a in c) for c in cuerpos):
                    M.add(h)
                    cambio = True
        return M

def red_de_ataque():
    P = Programa()
    for p, x in ((0.30, "web"), (0.10, "vpn"), (0.25, "ws")):
        P.hecho(p, ("entrada", x))
        P.regla(("comp", x), ("entrada", x))
    for p, x, y in ((0.6, "web", "app"), (0.8, "vpn", "app"), (0.3, "ws", "app"), (0.4, "ws", "ad"),
                    (0.5, "app", "db"), (0.7, "ad", "db"), (0.5, "ad", "backup"), (0.2, "db", "backup")):
        P.hecho(p, ("paso", x, y))
        P.regla(("comp", y), ("comp", x), ("paso", x, y))
    return P

P = red_de_ataque()
delta = P.cnf()
V = set(range(1, len(P.nombres) + 1))
print(f"{len(P.hechos)} hechos, {len(V)} variables, {len(delta)} cláusulas;  WMC(Δ) = {wmc(delta, V, P.w)[0]:.6f}")

def prob(consulta, evidencia=()):
    """P(consulta | evidencia) = WMC(Δ ∧ q ∧ e) / WMC(Δ ∧ e); evidencia: pares (átomo, valor)."""
    e = [[P.ids[a] if v else -P.ids[a]] for a, v in evidencia]
    return wmc(delta + [[P.ids[consulta]]] + e, V, P.w)[0] / wmc(delta + e, V, P.w)[0]

def prob_enumerando(consulta, evidencia=()):
    """La semántica, sin atajos: suma sobre las 2^m elecciones de hechos con su modelo mínimo."""
    hechos, num, den = list(P.hechos), 0.0, 0.0
    for bits in itertools.product((1, 0), repeat=len(hechos)):
        p = 1.0
        for f, b in zip(hechos, bits):
            p *= P.hechos[f] if b else 1 - P.hechos[f]
        M = P.modelo_minimo([f for f, b in zip(hechos, bits) if b])
        if all((a in M) == v for a, v in evidencia):
            den += p
            num += p * (consulta in M)
    return num / den

for x in ("app", "ad", "db", "backup"):
    print(f"P(comp({x})) = {prob(('comp', x)):.6f}   enumerando 2^11 mundos: {prob_enumerando(('comp', x)):.6f}")
ev = [(("comp", "backup"), True)]
print("\nsabiendo que cayó la copia de seguridad:")
for x in ("web", "vpn", "ws"):
    a = ("entrada", x)
    print(f"  P(entrada({x}) | comp(backup)) = {prob(a, ev):.4f}   (prior {P.hechos[a]:.2f})   enumerando: {prob_enumerando(a, ev):.4f}")

The eleven probabilities give 2626 variables (11 facts, 7 derived atoms, 8 auxiliaries) and 42 clauses, and WMC(Δ)=1\mathrm{WMC}(\Delta) = 1 as the theorem predicts. Database compromise probability is 0.20460.2046, backup 0.08320.0832, and counting matches enumeration of 2112^{11} worlds to six figures. Diagnosis is interesting: if backup fell, workstation-entry probability rises from 0.250.25 to 0.77860.7786, web from 0.300.30 to 0.42060.4206 and VPN from 0.100.10 to 0.16140.1614. Workstation dominates because it alone has a path to Active Directory (ad), from which backup falls directly with probability 0.50.5; other entries only reach it through the database with an 0.20.2 step. No program rule reasons effect-to-cause: conditioning does.

Why caching matters

To see caching’s effect we need many variables. The layered network below has two machines per layer, both layer-0 machines already compromised, and four possible steps between each pair of layers, each with probability 0.50.5. With LL layers there are 4L4L facts and 24L2^{4L} worlds.

[ ]#SAT and WMC from scratch: components and caching at scaleBrowser
import matplotlib.pyplot as plt

def escalera(L, p=0.5):
    """Red por capas: dos máquinas por capa, la capa 0 comprometida, cuatro pasos posibles entre capas."""
    E = Programa()
    for a in (0, 1):
        E.hecho(1.0, ("entrada", (0, a)))
        E.regla(("comp", (0, a)), ("entrada", (0, a)))
    for i in range(L):
        for a in (0, 1):
            for b in (0, 1):
                E.hecho(p, ("paso", (i, a), (i + 1, b)))
                E.regla(("comp", (i + 1, b)), ("comp", (i, a)), ("paso", (i, a), (i + 1, b)))
    return E

print(f"{'L':>3} {'hechos':>6} {'P(comp(L,0))':>13} {'llamadas con caché':>19} {'sin caché':>10}")
filas = []
for L in (2, 4, 6, 8, 12, 16, 20):
    E = escalera(L)
    cls, VE, q = E.cnf(), set(range(1, len(E.nombres) + 1)), [[E.ids[("comp", (L, 0))]]]
    val, c1 = wmc(cls + q, VE, E.w)
    sin = wmc(cls + q, VE, E.w, cache=False)[1].llamadas if L <= 8 else None
    filas.append((L, c1.llamadas, sin))
    print(f"{L:>3} {4 * L:>6} {val:>13.6f} {c1.llamadas:>19} {sin if sin else '':>10}")

Ls = [f[0] for f in filas]
plt.semilogy(Ls, [f[1] for f in filas], "o-", label="con caché")
plt.semilogy([f[0] for f in filas if f[2]], [f[2] for f in filas if f[2]], "s--", label="sin caché")
plt.semilogy(Ls, [2.0 ** (4 * L) for L in Ls], ":", color="gray", label="mundos: 2^(4L)")
plt.xlabel("capas L"); plt.ylabel("llamadas a contar_componente"); plt.legend(); plt.show()

With caching, calls grow linearly: from L=4L = 4 exactly 40L−7940L - 79 (81, 161, 241, …, 721), 40 per layer. Without caching they quadruple roughly every two layers (23, 105, 433, 1745). With L=20L = 20 there are 8080 facts and 280≈1.2×10242^{80} \approx 1.2 \times 10^{24} worlds, and the counter answers in 721 calls. Structure explains it: once steps entering layer ii are decided, all prior history reduces to which of its two machines are compromised, so the residual formula has few forms and caching recognizes them. This exploits the ladder’s small treewidth without computing a decomposition.

Knowledge compilation

Each call to prob repeats the entire search. For many queries on one base (all machines, varying evidence and probabilities), save the search. Component-DPLL’s trace is a circuit: each decision on xx is an OR of two branches, (x∧F∣x)∨(¬x∧F∣¬x)(x \wedge F \given x) \vee (\neg x \wedge F \given \neg x), and each decomposition an AND of components. Caching makes it a directed acyclic graph, not a tree, because a reused component has multiple parents.

Proof

Induct from leaves. At a leaf, definition. At an AND with children N1,…,NkN_1, \dots, N_k over disjoint variables, a model of NN over vars(N)\mathrm{vars}(N) is exactly a tuple of models of each NiN_i over vars(Ni)\mathrm{vars}(N_i) (decomposability), with weight the product of part weights; summing over tuples, sum of products is product of sums. At OR, child model sets are disjoint (determinism), so WMC(N)=∑iWMC(Ni)\mathrm{WMC}(N) = \sum_i \mathrm{WMC}(N_i) provided each WMC(Ni)\mathrm{WMC}(N_i) is counted over the same variables as NN, guaranteed by smoothness. If a child omitted xx, its models over vars(N)\mathrm{vars}(N) would be its own with xx free, multiplying weight by w(x)+w(¬x)w(x) + w(\neg x).

∎

Each property protects one proof step, failing concretely without it: without decomposability multiplication treats shared-variable parts as independent; without determinism addition counts common models repeatedly; without smoothness missing-variable factors are lost. Smoothness is cheapest: Darwiche and Marquis (2002) show any d-DNNF can be smoothed in polynomial time by adding (x∨¬x)(x \vee \neg x) where xx is absent. With probability weights w(x)+w(¬x)=1w(x) + w(\neg x) = 1, missing factors are 1 and smoothness unnecessary except when evidence sets a weight to 0.

InteractiveWeighted counting on a circuit
q↔e∧(d∨(a∧b))q \leftrightarrow e \wedge (d \vee (a \wedge b))
e = entrada(web) · a = salto(web,app) · d = salto(web,db) · b = salto(app,db)
e0.50a0.70d0.40¬d0.60b0.60∧∨∧¬a0.30d0.40∧∨∧
Leaves have their weight: w(x) or w(¬x).
Formula
Circuit
Weights
leaves
Fact
0.50
Evidence about this fact
Circuit root0.32600
Exact WMC (enumeration)0.32600
Decomposableyes
Deterministicyes
Smoothno
Nodes13
The root matches the sum over models.
The ProbLog query below compiled to d-DNNF by component decomposition and Shannon expansion, as in the counter. Replay evaluation: each node computes its value from children. Then break properties: ‘proof DNF’ ORs two ways to compromise the database (not deterministic) and ‘cut CNF’ ANDs clauses sharing variables (not decomposable); compare roots with exact value. Switch to ‘count models’ to see why smoothing matters, and mark a fact as evidence: evidence zeroes a weight.

In the proof DNF for the bridge formula, the root is 1.4341.434, a “probability” above 1, because three ways from ss to tt overlap heavily. This is the certainty-factor error, counting nonindependent information twice, now in calculation structure rather than numbers.

Compilation map

Darwiche and Marquis (2002) arranged languages by polynomial-time queries and transformations and succinctness (potential translation growth). From more to less succinct: DNNF, d-DNNF, FBDD, OBDD, fixed-order OBDD, explicit model list. Most relevant here:

LanguageCounting (and WMC)ConditioningConjunction of two circuitsEquivalence
DNNFno (unless P = NP)yesnono
d-DNNFyesyesnounknown
Fixed-order OBDDyesyesyes, bounded (apply)yes

d-DNNF answers consistency, validity, clause entailment, counting and model enumeration in polynomial time, but no target language is closed under conjunction of arbitrary circuits. OBDDs do combine circuits (Bryant’s apply) at a substantial succinctness cost. SDDs (sentential decision diagrams, Darwiche 2011) are intermediate: a d-DNNF subset generalizing OBDDs (an OBDD is an SDD with a linear variable tree), canonical for a given variable tree and with polynomial-time apply. ProbLog2 defaults to them when PySDD is installed: build bottom-up, conjunction by conjunction.

Top-down d-DNNF compilers are trace-saving counters: c2d (Darwiche, 2004), Dsharp (Muise et al., 2012) and d4 (Lagniez and Marquis, 2017) produce decision-DNNF, whose ORs are variable decisions (deterministic by construction) and ANDs are components (decomposable by construction). Your counter is too with small changes: construct corresponding AND/OR nodes instead of multiplying and adding numbers.

[ ]#SAT and WMC from scratch: compile once, query many timesBrowser
class Compilador(Contador):
    """El mismo DPLL, pero devuelve nodos de un circuito d-DNNF suave en lugar de números."""
    def __init__(self):
        super().__init__(w=None)
        self.nodos, self.unicos = [], {}

    def nodo(self, *n):                      # ('lit', l) | ('and', hijos) | ('or', hijos) | ('const', 0 o 1)
        if n not in self.unicos:
            self.unicos[n] = len(self.nodos)
            self.nodos.append(n)
        return self.unicos[n]

    def contar(self, clausulas, variables):
        clausulas, forzados = propagar(clausulas)
        if clausulas is None:
            return self.nodo("const", 0)
        hijos = [self.nodo("lit", l) for l in forzados]
        usadas = {abs(l) for l in forzados}
        for comp in componentes(clausulas):
            vs = {abs(l) for c in comp for l in c}
            usadas |= vs
            hijos.append(self.contar_componente(comp, vs))
        for v in sorted(variables - usadas):  # suavidad: v ∨ ¬v por cada variable libre
            hijos.append(self.nodo("or", (self.nodo("lit", v), self.nodo("lit", -v))))
        return hijos[0] if len(hijos) == 1 else self.nodo("and", tuple(hijos))

    def contar_componente(self, comp, vs):
        clave = frozenset(comp)
        if clave in self.cache:
            return self.cache[clave]
        frecuencia = defaultdict(int)
        for c in comp:
            for l in c:
                frecuencia[abs(l)] += 1
        x = max(frecuencia, key=lambda v: (frecuencia[v], -v))
        ramas = []
        for lit in (x, -x):
            sub = asignar(comp, lit)
            if sub is not None:
                ramas.append(self.nodo("and", (self.nodo("lit", lit), self.contar(sub, vs - {x}))))
        r = ramas[0] if len(ramas) == 1 else self.nodo("or", tuple(ramas))
        self.cache[clave] = r
        return r

def evaluar(nodos, raiz, w):
    """WMC de un d-DNNF suave: hojas con su peso, AND multiplica, OR suma (los hijos tienen índice menor)."""
    val = [0.0] * (raiz + 1)
    for i, n in enumerate(nodos[: raiz + 1]):
        if n[0] == "lit":
            val[i] = w[n[1]]
        elif n[0] == "const":
            val[i] = float(n[1])
        elif n[0] == "and":
            v = 1.0
            for h in n[1]:
                v *= val[h]
            val[i] = v
        else:
            val[i] = sum(val[h] for h in n[1])
    return val[raiz]

compilador = Compilador()
raiz = compilador.contar([frozenset(c) for c in delta], V)
print(f"Δ compilada a d-DNNF suave: {raiz + 1} nodos")

def p_circuito(q, w):
    wq = dict(w)
    wq[-P.ids[q]] = 0.0                       # condicionar a q es anular el peso de ¬q
    return evaluar(compilador.nodos, raiz, wq) / evaluar(compilador.nodos, raiz, w)

nombre = lambda f: f"{f[0]}({', '.join(f[1:])})"
base = p_circuito(("comp", "db"), P.w)
print(f"P(comp(db)) evaluando el circuito: {base:.6f}")
print("\nreducción de P(comp(db)) al eliminar cada condición (p → 0):")
efectos = []
for f in P.hechos:
    w = dict(P.w)
    w[P.ids[f]], w[-P.ids[f]] = 0.0, 1.0
    efectos.append((base - p_circuito(("comp", "db"), w), f))
for d, f in sorted(efectos, reverse=True)[:5]:
    print(f"  {nombre(f):16s} {d:.4f}")

The Δ\Delta circuit has 200 nodes and is compiled once; each later query is a linear pass, with query and evidence as zeroed weights (derived atoms are circuit variables too). This makes a mitigation question trivial: which condition should be removed first? Since P(comp(db))P(\text{comp(db)}) is multilinear in fact probabilities, ∂P/∂pi=P(q∣fi)−P(q∣¬fi)\partial P / \partial p_i = P(q \given f_i) - P(q \given \neg f_i), and moving pip_i to 0 reduces risk by exactly pi ∂P/∂pip_i\,\partial P/\partial p_i. The application-to-database step is most profitable to close (0.13460.1346 of 0.20460.2046), followed by phishing entry (0.08180.0818); web-to-application and web entry tie at 0.07250.0725 because web threatens the database only through that step.

Probabilistic logic programming

Everything above can be written by hand: facts, rules, completion, counter. ProbLog turns it into a language.

This is possible-world semantics factorized by independent facts, with the least model acting as deterministic rules. An important difference from completion: the least model is defined for cyclic programs too, like reachability, making distribution semantics more than a Bayesian network with different syntax. The interactive program has four facts, hence 16 worlds.

InteractiveWorlds of a ProbLog program
0.50::entrada(web).  0.70::salto(web,app).
0.40::salto(web,db).  0.60::salto(app,db).
comp(X) :- entrada(X).
comp(Y) :- comp(X), salto(X, Y).
query(comp(db)).
#ent(web)s(web,app)s(web,db)s(app,db)modelP(world)
6✗✓✗✓∅
12.6 %
14✓✓✗✓web, app, db
12.6 %
5✗✓✗✗∅
8.4 %
13✓✓✗✗web, app
8.4 %
8✗✓✓✓∅
8.4 %
16✓✓✓✓web, app, db
8.4 %
7✗✓✓✗∅
5.6 %
15✓✓✓✗web, app, db
5.6 %
2✗✗✗✓∅
5.4 %
10✓✗✗✓web
5.4 %
1✗✗✗✗∅
3.6 %
4✗✗✓✓∅
3.6 %
9✓✗✗✗web
3.6 %
12✓✗✓✓web, db
3.6 %
3✗✗✓✗∅
2.4 %
11✓✗✓✗web, db
2.4 %
✓ selected fact, ✗ discarded fact. “Model”: compromised machines in that world's least model. Blue rows satisfy the query.
0.50
0.70
0.40
0.60
Query
Evidence
P(comp(db))0.3260
Worlds satisfying the query5 of 16
The two proofs of comp(db) sum to 0.200 + 0.210 = 0.410, more than 0.326: worlds satisfying both would be counted twice.
Each row is a total choice of four facts, with its resulting least model (compromised machines) and probability. Blue rows make the query true: their sum is P(q)P(q). Change probabilities and watch world weights change. Add evidence: contradicting worlds dim and the rest renormalize. With evidence ‘db = true’ and query comp(app), observe how effect observation raises cause probability.

With initial values P(comp(db))=0.5 (0.4+0.6⋅0.7⋅0.6)=0.326P(\text{comp(db)}) = 0.5\,(0.4 + 0.6 \cdot 0.7 \cdot 0.6) = 0.326; adding probabilities of the two proofs, 0.5⋅0.4+0.5⋅0.7⋅0.6=0.410.5 \cdot 0.4 + 0.5 \cdot 0.7 \cdot 0.6 = 0.41, overestimates because worlds with both paths are counted twice. This is the disjoint-sum problem: original ProbLog (De Raedt, Kimmig and Toivonen, 2007) gathered proofs into DNF and compiled it to a BDD precisely to make them disjoint.

How ProbLog infers

Fierens, Van den Broeck et al. (2015) describe ProbLog2’s pipeline, reusing this lesson:

  1. Ground only relevant parts. SLD resolution and tabling from queries and evidence collect ground rules influencing them. In their experiments, removing 17% of ground-program rules reduced formula clauses by up to 90%, as each removed rule may break formula-expanding cycles.
  2. Convert to a formula. For acyclic rules, Clark completion. With positive cycles (like comp(Y) :- comp(X), paso(X, Y) in a cyclic graph), completion is incorrect: it admits models in which atoms mutually support one another without external cause. ProbLog uses cycle-breaking conversion, rule-based (Janhunen, 2004) or proof-based (Mantadelis and Janssens, 2010).
  3. Compile and count. Compile the weighted formula to d-DNNF or SDD and evaluate with WMC. On WebKB, BDDs were manageable only for domains of size 3 or 4, while d-DNNFs reached 18.

Unlike PRISM, which requires acyclic programs and mutually exclusive bodies for rules sharing a head, ProbLog admits cycles and overlapping bodies and must truly count. The translation also gives the most probable explanation (MPE) as weighted MaxSAT and supports learning fact probabilities from partial interpretations with EM (LFI-ProbLog, Gutmann et al., 2011): the E-step uses circuits to calculate each fact’s probability given each observation.

Lab: ProbLog in practice

The following cells need the local lab, with pip install problog pysdd. The first hidden cell repeats counter and attack-network definitions locally because that process does not share browser memory.

First, the same model in ProbLog. Notice its brevity: two variable rules rather than eight hand-written instances, query and evidence as language predicates. Then a positive cycle shows Clark completion failing.

[ ]ProbLog in practice: queries, evidence and cyclesLocal GPU
from problog.program import PrologString
from problog import get_evaluatable

RED = """
0.30::entrada(web).  0.10::entrada(vpn).  0.25::entrada(ws).
0.6::paso(web, app). 0.8::paso(vpn, app). 0.3::paso(ws, app). 0.4::paso(ws, ad).
0.5::paso(app, db).  0.7::paso(ad, db).   0.5::paso(ad, backup). 0.2::paso(db, backup).
comp(X) :- entrada(X).
comp(Y) :- comp(X), paso(X, Y).
"""

def problog(programa, motor="sdd"):
    """Evalúa todas las consultas del programa (con su evidencia): {consulta: probabilidad}."""
    res = get_evaluatable(motor).create_from(PrologString(programa)).evaluate()
    return {str(k): v for k, v in res.items()}

r = problog(RED + "query(comp(app)). query(comp(db)). query(comp(backup)).")
for x in ("app", "db", "backup"):
    print(f"comp({x}):  ProbLog {r[f'comp({x})']:.6f}   contador propio {prob(('comp', x)):.6f}")

r = problog(RED + "evidence(comp(backup), true). query(entrada(_)).")
print("\ncon evidence(comp(backup), true):", {k: round(v, 4) for k, v in sorted(r.items())})

# un ciclo positivo: desde la aplicación también se puede comprometer la web
CICLO = RED + "0.5::paso(app, web).\n"
print("\ncon el ciclo web → app → web, P(comp(web)) según ProbLog:", round(problog(CICLO + "query(comp(web)).")["comp(web)"], 6))
P = red_de_ataque()
P.hecho(0.5, ("paso", "app", "web"))
P.regla(("comp", "web"), ("comp", "app"), ("paso", "app", "web"))
delta = P.cnf()
V = set(range(1, len(P.nombres) + 1))
print(f"compleción de Clark: WMC(Δ) = {wmc(delta, V, P.w)[0]:.6f},  WMC(Δ ∧ comp(web)) / WMC(Δ) = {prob(('comp', 'web')):.6f}")
print(f"suma sobre los modelos mínimos:          P(comp(web)) = {prob_enumerando(('comp', 'web')):.6f}")
P = red_de_ataque()                                  # restablece la red acíclica
delta = P.cnf()
V = set(range(1, len(P.nombres) + 1))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

ProbLog and the custom counter agree to six figures on all three queries and diagnosis with evidence (0.42060.4206, 0.16140.1614, 0.77860.7786). With the cycle the difference is Fierens’ prediction: completion gives WMC(Δ)=1.1787>1\mathrm{WMC}(\Delta) = 1.1787 > 1 because worlds with both steps paso(web, app) and paso(app, web) where no entry reaches web or application admit two models (both compromised, mutually supporting, or neither), yielding false probability 0.45040.4504. Correct least-model probability is 0.35220.3522, as ProbLog returns.

Now learning. Simulate incidents with the true model and retain only what responders would observe: which machines ended compromised, not entry or steps. LFI-ProbLog estimates eleven probabilities from those partial interpretations.

[ ]ProbLog in practice: learning from partially observed incidentsLocal GPU
from problog.logic import Term
from problog.learning import lfi

VERDAD = {("entrada", "web"): 0.30, ("entrada", "vpn"): 0.10, ("entrada", "ws"): 0.25,
          ("paso", "web", "app"): 0.6, ("paso", "vpn", "app"): 0.8, ("paso", "ws", "app"): 0.3,
          ("paso", "ws", "ad"): 0.4, ("paso", "app", "db"): 0.5, ("paso", "ad", "db"): 0.7,
          ("paso", "ad", "backup"): 0.5, ("paso", "db", "backup"): 0.2}
MAQUINAS = ["web", "vpn", "ws", "app", "ad", "db", "backup"]

def interpretacion(azar):
    """Un incidente simulado: se sortean los hechos y solo se observa qué máquinas acabaron comprometidas."""
    ciertos = [f for f, p in VERDAD.items() if azar.random() < p]
    M = P.modelo_minimo(ciertos)
    return [(Term("comp", Term(m)), ("comp", m) in M) for m in MAQUINAS]

PLANTILLA = "\n".join(f"t(_)::{f[0]}({', '.join(f[1:])})." for f in VERDAD) + """
comp(X) :- entrada(X).
comp(Y) :- comp(X), paso(X, Y).
"""
azar = random.Random(0)
for n in (100, 1000):
    datos = [interpretacion(azar) for _ in range(n)]
    _, pesos, atomos, iters, _ = lfi.run_lfi(PrologString(PLANTILLA), datos, max_iter=500, min_improv=1e-6)
    aprendido = {str(a).split("::")[1]: float(w) for a, w in zip(atomos, pesos)}
    clave = lambda f: f"{f[0]}({','.join(f[1:])})"
    err = [abs(aprendido[clave(f)] - p) for f, p in VERDAD.items()]
    print(f"\n{n} incidentes, {iters} iteraciones de EM: error medio {sum(err) / len(err):.3f}, máximo {max(err):.3f}")
    if n == 1000:
        for f, p in VERDAD.items():
            print(f"  {clave(f):20s} real {p:.2f}   aprendido {aprendido[clave(f)]:.3f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With 100 incidents mean error is 0.0990.099 and maximum 0.3000.300; with 1000 they fall to 0.0240.024 and 0.0890.089. Entries are learned well because comp(web), comp(vpn) and comp(ws) can only be true via their entry. Worst-estimated steps are rarely tested: paso(vpn, app) (0.7110.711 versus 0.800.80) is observed only when VPN fell, 10% of 1000, and still confounded with two other paths to app. This limits learning from partial interpretations: a parameter is identified only as well as data exercise it.

Finally compare timing against the custom counter on the ladder, where results must agree:

[ ]ProbLog in practice: our counter versus ProbLogLocal GPU
print(f"{'L':>3} {'hechos':>6} {'contador propio (s)':>20} {'ProbLog con SDD (s)':>20} {'cociente':>9}")
for L in (4, 8, 16, 32):
    E = escalera(L)
    cls, VE = E.cnf(), set(range(1, len(E.nombres) + 1))
    t = time.perf_counter()
    a = wmc(cls + [[E.ids[("comp", (L, 0))]]], VE, E.w)[0]
    t1 = time.perf_counter() - t
    prog = "1.0::entrada(n0_0). 1.0::entrada(n0_1).\n" + "".join(
        f"0.5::paso(n{i}_{x}, n{i + 1}_{y}).\n" for i in range(L) for x in (0, 1) for y in (0, 1))
    prog += "comp(X) :- entrada(X).\ncomp(Y) :- comp(X), paso(X, Y).\n" + f"query(comp(n{L}_0)).\n"
    t = time.perf_counter()
    b = problog(prog)[f"comp(n{L}_0)"]
    t2 = time.perf_counter() - t
    assert abs(a - b) < 1e-9, (a, b)
    print(f"{L:>3} {4 * L:>6} {t1:>20.3f} {t2:>20.3f} {t2 / t1:>9.2f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Both give the same number in every row. Timing trends matter, not machine-dependent absolute values: with few layers the custom counter wins because ProbLog pays fixed grounding and compilation overhead; after about eight layers ProbLog is faster and the gap grows with LL. The custom counter grows approximately with L2L^2: linearly many calls, but each copies the clause list without watched literals or incremental structures. This distinguishes a correct algorithm from production implementation.

A look at Markov logic networks

ProbLog defines distribution generatively: independent facts and rules deriving the rest, with probabilities summing to 1 by construction. Markov logic networks (Richardson and Domingos, 2006) take the undirected route: first-order formulas φi\varphi_i with real weights wiw_i, and for each grounded world ω\omega,

P(ω)=1Zexp⁡(∑iwi ni(ω)),P(\omega) = \frac{1}{Z} \exp\Big(\sum_i w_i\, n_i(\omega)\Big),

where ni(ω)n_i(\omega) counts instances of φi\varphi_i true in ω\omega and ZZ normalizes. Infinite weight is a hard constraint and first-order logic the limiting case. With one formula Fuma(x)⇒Cancer(x)\mathit{Fuma}(x) \Rightarrow \mathit{Cancer}(x) of weight ww and one person there are four worlds; it is true in three weighing ewe^w and false in one weighing 11. Each formula multiplies odds of satisfying worlds by ewe^{w} rather than prohibiting others.

Inference is also WMC: auxiliary variable ai↔φia_i \leftrightarrow \varphi_i per instance, with w(ai)=ewiw(a_i) = e^{w_i} and w(¬ai)=1w(\neg a_i) = 1, and weights 1 elsewhere. The denominator is no longer 1: Z=WMC(Δ)Z = \mathrm{WMC}(\Delta), hence the earlier ratio theorem. The modeling difference is directed versus undirected: in ProbLog each number is a locally readable, learnable probability; in a Markov network weights only make sense together.

Common mistakes

Exercises

NumericTwo MYCIN rules and their posterior
Two rules conclude hypothesis HH with certainty factors 0.60.6 and 0.50.5. Combine them with MYCIN and interpret using Heckerman (CF =(λ−1)/λ= (\lambda - 1)/\lambda for λ≥1\lambda \ge 1). If prior P(H)=0.1P(H) = 0.1 and evidence is conditionally independent given HH and given ¬H\neg H, what is P(H∣E1,E2)P(H \given E_1, E_2)?
NumericEvidence for and against
Combine MYCIN certainty factors 0.60.6 and −0.4-0.4 for the same hypothesis.
NumericConflict between two sources
On frame Θ={a,b,c}\Theta = \{a, b, c\}, one source gives m1({a})=0.4m_1(\{a\}) = 0.4, m1({a,b})=0.4m_1(\{a, b\}) = 0.4, m1(Θ)=0.2m_1(\Theta) = 0.2, and another m2({b})=0.5m_2(\{b\}) = 0.5, m2({b,c})=0.3m_2(\{b, c\}) = 0.3, m2(Θ)=0.2m_2(\Theta) = 0.2. What is conflict KK in Dempster's rule?
NumericA hypothesis's combined mass
With the same two sources as the previous exercise, what is (m1⊕m2)({b})(m_1 \oplus m_2)(\{b\})?
QuizZadeh's diagnosis example
Two physicians give m1({M})=0.99m_1(\{M\}) = 0.99, m1({T})=0.01m_1(\{T\}) = 0.01 and m2({C})=0.99m_2(\{C\}) = 0.99, m2({T})=0.01m_2(\{T\}) = 0.01; Dempster gives m({T})=1m(\{T\}) = 1. What explains this?
QuizDegrees and probabilities
Juan is 1.78 m tall and μalto(Juan)=0.7\mu_{\text{alto}}(\text{Juan}) = 0.7. Tomorrow rain has probability 0.70.7. Which claim is correct?
QuizCounting versus deciding
Which claims are true?

More than one answer may be correct.

ProofProbability as a ratio of counts
Prove: Consider a program with independent probabilistic facts f1,…,fmf_1, \dots, f_m (probabilities pip_i) and acyclic definite rules RR over derived atoms DD, and let Δ\Delta be Clark's completion of RR. With weights w(fi)=piw(f_i) = p_i, w(¬fi)=1−piw(\neg f_i) = 1 - p_i and w(d)=w(¬d)=1w(d) = w(\neg d) = 1 for d∈Dd \in D, P(q)=WMC(Δ∧q)/WMC(Δ)P(q) = \mathrm{WMC}(\Delta \wedge q)/\mathrm{WMC}(\Delta) holds for every atom qq in the program.
0
Call each assignment LL of facts a total choice, with P(L)=∏fi∈Lpi∏fi∉L(1−pi)P(L) = \prod_{f_i \in L} p_i \prod_{f_i \notin L}(1 - p_i), and M(L)M(L) the minimal model of L∪RL \cup R. By distribution semantics, P(q)=∑L: q∈M(L)P(L)P(q) = \sum_{L:\ q \in M(L)} P(L).

Step 1 of 4. How many models of Δ\Delta extend a given total choice LL?

CodeWMC over a d-DNNF, smooth or not
Implement wmc_circuito(nodos, raiz, w, variables), which calculates the weighted model count of a d-DNNF circuit (decomposable and deterministic) which need not be smooth. Nodes are tuples ('lit', l) with l a signed integer, ('const', 0) or ('const', 1), ('and', hijos) or ('or', hijos), where hijos is a tuple of indices smaller than the node's own. w gives each literal's weight (w[v] and w[-v]), and variables is the set of variables counted over: those the circuit does not mention, or that are missing from an OR child, must contribute their factor w[v] + w[-v].
def wmc_circuito(nodos, raiz, w, variables):
  """WMC de un d-DNNF no necesariamente suave, sobre el conjunto 'variables'."""
  # tu código: para cada nodo, su valor y sus variables; en los OR, completa a cada hijo
  # con las variables que le faltan; en la raíz, con las de 'variables' que no aparezcan
  return None
Shift+Enter to run
QuizRequirements for bottom-up evaluation
You evaluate an NNF circuit bottom-up, with each literal's weight at the leaves, products at ANDs and sums at ORs, and want the root to be WMC over all variables for arbitrary weights. What properties are needed if evaluation makes no corrections?

More than one answer may be correct.

NumericConditioning on an effect
Using the interactive ProbLog program but with probabilities 0.80.8 for entrada(web), 0.50.5 for salto(web,app), 0.30.3 for salto(web,db) and 0.90.9 for salto(app,db), calculate the probability that the direct hop existed, P(salto(web,db)∣comp(db))P(\text{salto(web,db)} \given \text{comp(db)}). This is a forensic question: the database fell; did they enter by the direct path?
NumericMarkov logic network weights
A Markov logic network has one formula, Fuma(x)⇒Cancer(x)\mathit{Fuma}(x) \Rightarrow \mathit{Cancer}(x), of weight w=1.5w = 1.5, and one person. What is the probability of the world in which that person smokes and does not have cancer?

Summary

Key idea
Reasoning with uncertainty over rules is counting: a query’s probability is the mass of worlds where it holds, calculated as a ratio of weighted model counts with the same machinery as SAT solvers.
  • MYCIN certainty factors are modular and therefore incoherent: parallel combination is equivalent to multiplying likelihood ratios (Heckerman), which is correct only when evidence is conditionally independent given the hypothesis and its negation. Correlated evidence is counted repeatedly.
  • Dempster-Shafer represents ignorance with masses on sets and bounds each hypothesis between belief and plausibility, but its rule conditions on source compatibility: with high conflict (Zadeh, K=0.9999K = 0.9999), the result represents neither source. Fuzzy logic models vagueness, not uncertainty, and cannot be probability because it is truth-functional.
  • Possible-worlds semantics puts a distribution over models of a theory; with independent probabilistic facts and deterministic rules, exceptions are worlds and reasoning from effect to cause follows from conditioning.
  • #SAT is #P-complete; DPLL with propagation, components and caching counts in practice, and with weights computes WMC: P(q∣e)=WMC(Δ∧q∧e)/WMC(Δ∧e)P(q \given e) = \mathrm{WMC}(\Delta \wedge q \wedge e)/\mathrm{WMC}(\Delta \wedge e).
  • The counter trace is a d-DNNF circuit; in a decomposable, deterministic and smooth circuit, WMC is evaluated in linear time, and compiling once supports many queries. Without determinism models are counted repeatedly, as when adding proofs.
  • ProbLog defines probability through Sato’s distribution semantics and computes it by instantiating what is relevant, converting to a formula (taking care with positive cycles, where Clark completion fails), compiling and counting; it also learns probabilities from partial data using EM. Markov logic networks are its undirected counterpart, with Z=WMC(Δ)Z = \mathrm{WMC}(\Delta).