implement bayesNet
open core
constants
className = "bayesNet".
classVersion = "".
clauses
classInfo(className, classVersion).
domains
event = string.
ev = yes(event); not(event).
evList = ev*.
cp = cp(evList, real).
cpList = cp*.
class predicates
parent : (ev E1, ev E2) nondeterm anyflow.
pBase : (ev E, real R) determ (i,o).
p : (ev E, evList L, real P) nondeterm (i,o,o).
prob : (evList L1, evList L2, real Prob) nondeterm (i,i,o).
prob1 : (ev E, evList L2, real Prob) nondeterm (i,i,o).
predecessor : (ev E1, ev E2) nondeterm (i,i).
sum_probs : (cpList CPList, evList L, real P) nondeterm (i,i,o).
member : (ev E, evList L) nondeterm (i,i).
delete : (ev E, evList L1, evList L2) nondeterm (o,i,o).
clauses
% Байесова сеть доверия.
parent(yes("burglary"), yes("sensor")).
parent(yes("lightning"), yes("sensor")).
parent(yes("sensor"), yes("call")).
parent(yes("sensor"), yes("alarm")).
pBase(yes("burglary"), 0.001).
pBase(yes("lightning"), 0.9).
p(yes("sensor"), [yes("burglary"), yes("lightning")], 0.9).
p(yes("sensor"), [yes("burglary"), not("lightning")], 0.9).
p(yes("sensor"), [not("burglary"), yes("lightning")], 0.1).
p(yes("sensor"), [not("burglary"), not("lightning")], 0.001).
p(yes("call"), [yes("sensor")], 0.95).
p(yes("call"), [not("sensor")], 0.001).
p(yes("alarm"), [yes("sensor")], 0.9).
p(yes("alarm"), [not("sensor")], 0).
% Интерпретатор Байесовских сетей доверия.
prob([], _, 1) :- !.
prob([X|Xs], Cond, P) :- !,
prob1(X, Cond, Px),
prob(Xs, [X|Cond], PRest),
P=Px*PRest.
prob1(X, Cond, 1) :- member (X, Cond), !.
prob1(yes(X), Cond, 0) :- member (not(X), Cond), !.
prob1(not(X), Cond, P) :- prob1(yes(X), Cond, P0), P=1-P0.
prob1(X, Cond0, P) :-
delete(Y, Cond0, Cond),
predecessor(X, Y), !,
prob1(X, Cond, Px),
prob1(Y, [X|Cond], PyGivenX),
prob1(Y, Cond, Py),
P=Px*PyGivenX/Py.
prob1(X, _, P) :- pBase(X, P), !.
prob1(X, Cond, P) :- !,
findall(cp(Condi, Pi), p(X, Condi, Pi), CPList),
sum_probs(CPList, Cond, P).
sum_probs([], _, 0).
sum_probs([cp(Cond1, P1)|CondsProbs], Cond, P) :-
prob(Cond1, Cond, PC1),
sum_probs(CondsProbs, Cond, PRest),
P=P1*PC1+PRest.
predecessor(yes(X), not(Y)) :- !, predecessor(yes(X), yes(Y)).
predecessor(X, Y) :- parent(X, Y).
predecessor(X, Z) :- parent(X, Y), predecessor(Y, Z).
member(X, [X|_]).
member(X, [_|L]) :- member(X, L).
delete(X, [X|L], L).
delete(X, [Y|L], [Y|L2]) :- delete(X, L, L2).
/*
Пример вызова по Братко: prob([yes("burglary")], [yes("alarm"), not("lightning")], P).
Ответ: P=0.473934
*/
clauses
run():-
console::init(),
prob([yes("burglary")], [yes("alarm"), not("lightning")], P),
console::write("P = ", P),!, _=console::readchar(),
succeed(). % place your own code here
run().
end implement bayesNet
goal
mainExe::run(bayesNet::run).