Examples¶
examples/alarm.py is the program of Getting started; its
docstring works the answers out by hand:
"""The alarm example of Fierens et al. (2015): the probabilities of three
queries given that John calls, and the probability that he calls.
P(alarm) = 1 - 0.9 * 0.8 = 0.28 and P(calls(john)) = 0.28 * 0.7 = 0.196, so
P(burglary | calls(john)) = 0.1 * 0.7 / 0.196 = 0.357143. Run it with
python examples/alarm.py
to print
burglary: 0.357143
earthquake: 0.714286
calls(mary): 0.400000
P(e) = 0.196000 (log10 -0.707744)
"""
import tddlog
PROGRAM = """
0.1::burglary.
0.2::earthquake.
0.7::hears_alarm(john).
0.4::hears_alarm(mary).
alarm :- burglary.
alarm :- earthquake.
calls(X) :- alarm, hears_alarm(X).
evidence(calls(john), true).
query(burglary).
query(earthquake).
query(calls(mary)).
"""
solution = tddlog.solve(PROGRAM, evidence_probability=True)
for query, probability in solution.answers.items():
print(f"{query}: {probability:.6f}")
print(
f"P(e) = {solution.evidence_probability:.6f}"
f" (log10 {solution.log10_evidence_probability:.6f})"
)
examples/graph.py builds a program from Python data:
"""A program built from Python data: the probability that a path joins two
nodes of a graph whose edges are present independently, ProbLog's system
test 7. ProbLog answers path(1,5) 0.25824 and path(1,6) 0.2167296.
Run it with
python examples/graph.py
to print
path(1,5): 0.258240
path(1,6): 0.216730
"""
import tddlog
EDGES = {
(1, 2): 0.6,
(1, 3): 0.1,
(2, 5): 0.4,
(2, 6): 0.3,
(3, 4): 0.3,
(4, 5): 0.8,
(5, 6): 0.2,
}
QUERIES = [(1, 5), (1, 6)]
facts = [f"{p}::edge({a},{b})." for (a, b), p in EDGES.items()]
rules = [
"path(X,Y) :- edge(X,Y).",
"path(X,Y) :- edge(X,Z), path(Z,Y).",
]
queries = [f"query(path({a},{b}))." for a, b in QUERIES]
program = "\n".join(facts + rules + queries)
solution = tddlog.solve(program)
for query, probability in solution.answers.items():
print(f"{query}: {probability:.6f}")
The guide describes the language tddlog reads, with worked examples that open in the playground.