This commit is contained in:
Vitor Santos Costa 2013-01-09 16:48:16 +00:00
commit ff953eb20a
157 changed files with 6307 additions and 5898 deletions

View File

@ -28,9 +28,9 @@ INSTALL=@INSTALL@
INSTALL_DATA=@INSTALL_DATA@ INSTALL_DATA=@INSTALL_DATA@
INSTALL_PROGRAM=@INSTALL_PROGRAM@ INSTALL_PROGRAM=@INSTALL_PROGRAM@
srcdir=@srcdir@ srcdir=@srcdir@
PDFLATEX=pdflatex
CLPBN_TOP= $(srcdir)/clpbn.yap \ PFL_MANUAL = $(srcdir)/pfl
$(srcdir)/pfl.yap
CLPBN_SRCDIR = $(srcdir)/clpbn CLPBN_SRCDIR = $(srcdir)/clpbn
@ -38,6 +38,10 @@ CLPBN_LEARNING_SRCDIR = $(srcdir)/learning
CLPBN_EXDIR = $(srcdir)/examples CLPBN_EXDIR = $(srcdir)/examples
CLPBN_TOP= \
$(srcdir)/clpbn.yap \
$(srcdir)/pfl.yap
CLPBN_PROGRAMS= \ CLPBN_PROGRAMS= \
$(CLPBN_SRCDIR)/aggregates.yap \ $(CLPBN_SRCDIR)/aggregates.yap \
$(CLPBN_SRCDIR)/bdd.yap \ $(CLPBN_SRCDIR)/bdd.yap \
@ -74,15 +78,24 @@ CLPBN_LEARNING_PROGRAMS= \
$(CLPBN_LEARNING_SRCDIR)/learn_utils.yap \ $(CLPBN_LEARNING_SRCDIR)/learn_utils.yap \
$(CLPBN_LEARNING_SRCDIR)/mle.yap $(CLPBN_LEARNING_SRCDIR)/mle.yap
CLPBN_EXAMPLES= \
$(CLPBN_EXDIR)/burglary-alarm.fg \
$(CLPBN_EXDIR)/burglary-alarm.pfl \
$(CLPBN_EXDIR)/burglary-alarm.uai \
$(CLPBN_EXDIR)/cg.yap \
$(CLPBN_EXDIR)/city.pfl \
$(CLPBN_EXDIR)/comp_workshops.pfl \
$(CLPBN_EXDIR)/social_network1.pfl \
$(CLPBN_EXDIR)/social_network2.pfl \
$(CLPBN_EXDIR)/sprinkler.pfl \
$(CLPBN_EXDIR)/workshop_attrs.pfl
CLPBN_SCHOOL_EXAMPLES= \ CLPBN_SCHOOL_EXAMPLES= \
$(CLPBN_EXDIR)/School/README \ $(CLPBN_EXDIR)/School/README \
$(CLPBN_EXDIR)/School/evidence_128.yap \ $(CLPBN_EXDIR)/School/evidence_128.yap \
$(CLPBN_EXDIR)/School/schema.yap \
$(CLPBN_EXDIR)/School/parschema.pfl \ $(CLPBN_EXDIR)/School/parschema.pfl \
$(CLPBN_EXDIR)/School/school_128.yap \ $(CLPBN_EXDIR)/School/school_128.yap \
$(CLPBN_EXDIR)/School/school_32.yap \ $(CLPBN_EXDIR)/School/school_32.yap \
$(CLPBN_EXDIR)/School/sch32.yap \
$(CLPBN_EXDIR)/School/school32_data.yap \
$(CLPBN_EXDIR)/School/school_64.yap \ $(CLPBN_EXDIR)/School/school_64.yap \
$(CLPBN_EXDIR)/School/tables.yap $(CLPBN_EXDIR)/School/tables.yap
@ -102,20 +115,8 @@ CLPBN_LEARNING_EXAMPLES= \
$(CLPBN_EXDIR)/learning/sprinkler_params.yap \ $(CLPBN_EXDIR)/learning/sprinkler_params.yap \
$(CLPBN_EXDIR)/learning/train.yap $(CLPBN_EXDIR)/learning/train.yap
CLPBN_EXAMPLES= \
$(CLPBN_EXDIR)/burglary-alarm.fg \
$(CLPBN_EXDIR)/burglary-alarm.pfl \
$(CLPBN_EXDIR)/burglary-alarm.uai \
$(CLPBN_EXDIR)/cg.yap \
$(CLPBN_EXDIR)/city.pfl \
$(CLPBN_EXDIR)/comp_workshops.pfl \
$(CLPBN_EXDIR)/social_domain1.pfl \
$(CLPBN_EXDIR)/social_domain2.pfl \
$(CLPBN_EXDIR)/sprinkler.pfl \
$(CLPBN_EXDIR)/workshop_attrs.pfl
install: $(CLBN_TOP) $(CLBN_PROGRAMS) $(CLPBN_LEARNING_PROGRAMS) $(CLPBN_SCHOOL_EXAMPLES) $(CLPBN_HMMER_EXAMPLES) $(CLPBN_LEARNING_EXAMPLES)
install: $(CLBN_TOP) $(CLBN_PROGRAMS) $(CLPBN_PROGRAMS)
mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn
mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn/learning mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn/learning
mkdir -p $(DESTDIR)$(EXDIR) mkdir -p $(DESTDIR)$(EXDIR)
@ -130,3 +131,13 @@ install: $(CLBN_TOP) $(CLBN_PROGRAMS) $(CLPBN_PROGRAMS)
for h in $(CLPBN_HMMER_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(EXDIR)/HMMer; done for h in $(CLPBN_HMMER_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(EXDIR)/HMMer; done
for h in $(CLPBN_LEARNING_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(EXDIR)/learning; done for h in $(CLPBN_LEARNING_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(EXDIR)/learning; done
docs: $(MANUAL)
$(PDFLATEX) $(PFL_MANUAL)
$(PDFLATEX) $(PFL_MANUAL)
rm -f pfl.aux pfl.bbl pfl.blg pfl.log pfl.out
install_docs: docs
$(INSTALL_DATA) pfl.pdf $(DESTDIR)$(EXDIR)

View File

@ -1,111 +0,0 @@
Prolog Factor Language (PFL)
Prolog Factor Language (PFL) is a extension of the Prolog language that
allows a natural representation of this first-order probabilistic models
(either directed or undirected). PFL is also capable of solving probabilistic
queries on this models through the implementation of several inference
techniques: variable elimination, belief propagation, lifted variable
elimination and lifted belief propagation.
Language
-------------------------------------------------------------------------------
A graphical model in PFL is represented using parfactors. A PFL parfactor
has the following four components:
Type ; Formulas ; Phi ; Constraint .
- Type refers the type of the network over which the parfactor is defined.
It can be bayes for directed networks, or markov for undirected ones.
- Formulas is a sequence of Prolog terms that define sets of random variables
under the constraint.
- Phi is either a list of parameters or a call to a Prolog goal that will
unify its last argument with a list of parameters.
- Constraint is a list (possible empty) of Prolog goals that will impose
bindings on the logical variables that appear in the formulas.
The "examples" directory contains some popular graphical models described
using PFL.
Querying
-------------------------------------------------------------------------------
Now we show how to use PFL to solve probabilistic queries. We will
use the burlgary alarm network as an example. First, we load the model:
$ yap -l examples/burglary-alarm.yap
Now let's suppose that we want to estimate the probability of a earthquake
ocurred given that mary called. We can do it with the following query:
?- earthquake(X), mary_calls(t).
Suppose now that we want the joint distribution for john_calls and
mary_calls. We can obtain this with the following query:
?- john_calls(X), mary_calls(Y).
Inference Options
-------------------------------------------------------------------------------
PFL supports both ground and lifted inference. The inference algorithm
can be chosen using the set_solver/1 predicate. The following algorithms
are supported:
- lve: generalized counting first-order variable elimination (GC-FOVE)
- hve: (ground) variable elimination
- lbp: lifted first-order belief propagation
- cbp: counting belief propagation
- bp: (ground) belief propagation
- lkc: lifted first-order knowledge compilation
For example, if we want to use ground variable elimination to solve some
query, we need to call first the following goal:
?- set_solver(hve).
It is possible to tweak several parameters of PFL through the
set_horus_flag/2 predicate. The first argument is a key that
identifies the parameter that we desire to tweak, while the second
is some possible value for this key.
The verbosity key controls the level of log information that will be
printed by the corresponding solver. Its possible values are positive
integers. The bigger the number, more log information will be printed.
For example, to view some basic log information we need to call the
following goal:
?- set_horus_flag(verbosity, 1).
The use_logarithms key controls whether the calculations performed
during inference should be done in the log domain or not. Its values
can be true or false. By default is false.
There are also keys specific to the inference algorithm. For example,
elim_heuristic key controls the elimination heuristic that will be
used by ground variable elimination. The following heuristics are
supported:
- sequential
- min_neighbors
- min_weight
- min_fill
- weighted_min_fill
An explanation of this heuristics can be found in Probabilistic Graphical
Models by Daphne Koller.
The schedule, accuracy and max_iter keys are specific for inference
algorithms based on message passing, namely lbp, cbp and bp.
The key schedule can be used to specify the order in which the messages
are sent in belief propagation. The possible values are:
- seq_fixed: at each iteration, all messages are sent in the same order
- seq_random: at each iteration, the messages are sent with a random order
- parallel: at each iteration, the messages are all calculated using the
values of the previous iteration.
- max_residual: the next message to be sent is the one with maximum residual,
(Residual Belief Propagation:Informed Scheduling for Asynchronous Message
Passing)
The max_iter key sets the maximum number of iterations. One iteration
consists in sending all possible messages. The accuracy key indicate
when we should stop sending messages. If the largest difference between
a message sent in the current iteration and one message sent in the previous
iteration is less that accuracy value given, we terminate belief propagation.

View File

@ -1,5 +1,4 @@
function prepare_new_run function prepare_new_run
{ {
YAP=~/bin/$SHORTNAME-$SOLVER YAP=~/bin/$SHORTNAME-$SOLVER
@ -17,32 +16,33 @@ function prepare_new_run
function run_solver function run_solver
{ {
constraint=$1 echo $LOG_FILE
CONSTRAINT=$1
solver_flag=true solver_flag=true
if [ -n "$2" ]; then if [ -n "$2" ]; then
if [ $SOLVER = hve ]; then if [ $SOLVER = hve ]; then
solver_flag=clpbn_horus:set_horus_flag\(elim_heuristic,$2\) SOLVER_FLAG=set_horus_flag\(hve_elim_heuristic,$2\)
elif [ $SOLVER = bp ]; then elif [ $SOLVER = bp ]; then
solver_flag=clpbn_horus:set_horus_flag\(schedule,$2\) SOLVER_FLAG=set_horus_flag\(bp_msg_schedule,$2\)
elif [ $SOLVER = cbp ]; then elif [ $SOLVER = cbp ]; then
solver_flag=clpbn_horus:set_horus_flag\(schedule,$2\) SOLVER_FLAG=set_horus_flag\(bp_msg_schedule,$2\)
elif [ $SOLVER = lbp ]; then elif [ $SOLVER = lbp ]; then
solver_flag=clpbn_horus:set_horus_flag\(schedule,$2\) SOLVER_FLAG=set_horus_flag\(bp_msg_schedule,$2\)
else else
echo "unknow flag $2" echo "unknow flag $2"
fi fi
fi fi
/usr/bin/time -o $LOG_FILE -a -f "%U\t%S\t%e\t%M" \ /usr/bin/time -o $LOG_FILE -a -f "%U\t%S\t%e\t%M" \
$YAP << EOF >> $LOG_FILE &>> ignore.$LOG_FILE $YAP << EOF >> ignore.$LOG_FILE 2>> ignore.$LOG_FILE
nogc. nogc.
[$NETWORK]. [$NETWORK].
[$constraint]. [$CONSTRAINT].
clpbn_horus:set_solver($SOLVER). set_solver($SOLVER).
clpbn_horus:set_horus_flag(use_logarithms, true). set_horus_flag(verbosity, 1).
clpbn_horus:set_horus_flag(verbosity, 1). set_horus_flag(use_logarithms, true).
$solver_flag. $SOLVER_FLAG.
$QUERY. $QUERY.
open("$LOG_FILE", 'append', S), format(S, '$constraint ~15+ ', []), close(S). open("$LOG_FILE", 'append', S), format(S, "$CONSTRAINT ~15+ ", []), close(S).
EOF EOF
} }
@ -52,12 +52,16 @@ function clear_log_files
{ {
rm -f *~ rm -f *~
rm -f ../*~ rm -f ../*~
rm -f school/*.log school/*~
rm -f ../school/*.log ../school/*~
rm -f city/*.log city/*~
rm -f ../city/*.log ../city/*~
rm -f workshop_attrs/*.log workshop_attrs/*~ rm -f workshop_attrs/*.log workshop_attrs/*~
rm -f ../workshop_attrs/*.log ../workshop_attrs/*~ rm -f ../workshop_attrs/*.log ../workshop_attrs/*~
rm -f comp_workshops/*.log comp_workshops/*~
rm -f ../comp_workshops/*.log ../comp_workshops/*~
rm -f city/*.log city/*~
rm -f ../city/*.log ../city/*~
rm -f social_network2/*.log social_network2/*~
rm -f ../social_network2/*.log ../social_network2/*~
rm -f social_network2_evidence/*.log social_network2_evidence/*~
rm -f ../social_network2_evidence/*.log ../social_network2_evidence/*~
echo all done! echo all done!
} }

View File

@ -33,5 +33,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "bp(shedule=seq_fixed) " seq_fixed run_all_graphs "bp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -32,5 +32,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "cbp(shedule=seq_fixed) " seq_fixed run_all_graphs "cbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
NETWORK="'../../examples/city'" NETWORK="'../../examples/city.pfl'"
SHORTNAME="city" SHORTNAME="city"
QUERY="is_joe_guilty(X)" QUERY="is_joe_guilty(X)"

View File

@ -19,7 +19,7 @@ main :-
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
Counting > N, !. Counting > N, !.
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
format(S, 'people(p~w, nyc).~n', [Counting]), format(S, 'person(p~w, nyc).~n', [Counting]),
Counting1 is Counting + 1, Counting1 is Counting + 1,
generate_people(S, N, Counting1). generate_people(S, N, Counting1).

View File

@ -33,5 +33,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "hve(elim_heuristic=min_neighbors) " min_neighbors run_all_graphs "hve(hve_elim_heuristic=min_neighbors) " min_neighbors

View File

@ -32,5 +32,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "lbp(shedule=seq_fixed) " seq_fixed run_all_graphs "lbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -27,5 +27,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "bp(shedule=seq_fixed) " seq_fixed run_all_graphs "bp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -26,5 +26,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "cbp(shedule=seq_fixed) " seq_fixed run_all_graphs "cbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
NETWORK="'../../examples/comp_workshops'" NETWORK="'../../examples/comp_workshops.pfl'"
SHORTNAME="cw" SHORTNAME="cw"
QUERY="series(X)" QUERY="series(X)"

View File

@ -29,7 +29,7 @@ gen(S, NP, NW, Count) :-
gen_workshops(_, _, NW, Count) :- gen_workshops(_, _, NW, Count) :-
Count > NW, !. Count > NW, !.
gen_workshops(S, P, NW, Count) :- gen_workshops(S, P, NW, Count) :-
format(S, 'c(p~w,w~w).~n', [P,Count]), format(S, 'reg(p~w,w~w).~n', [P,Count]),
Count1 is Count + 1, Count1 is Count + 1,
gen_workshops(S, P, NW, Count1). gen_workshops(S, P, NW, Count1).

View File

@ -26,5 +26,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "hve(elim_heuristic=min_neighbors) " min_neighbors run_all_graphs "hve(hve_elim_heuristic=min_neighbors) " min_neighbors

View File

@ -26,5 +26,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "lbp(shedule=seq_fixed) " seq_fixed run_all_graphs "lbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -24,7 +24,7 @@ source lbp_tests.sh
source cbp_tests.sh source cbp_tests.sh
cd .. cd ..
cd smokers cd social_network2
source hve_tests.sh source hve_tests.sh
source bp_tests.sh source bp_tests.sh
source lve_tests.sh source lve_tests.sh

View File

@ -1,95 +1,64 @@
#!/bin/bash #!/bin/bash
#cp ~/bin/yap ~/bin/school_all source ../benchs.sh
#YAP=~/bin/school_all
YAP=~/bin/yap
#OUT_FILE_NAME=results`date "+ %H:%M:%S %d-%m-%Y"`.log SHORTNAME="school"
OUT_FILE_NAME=results.log SOLVER="school"
rm -f $OUT_FILE_NAME
rm -f ignore.$OUT_FILE_NAME
# yap -g "['../../../../examples/School/sch32'], [missing5], use_module(library(clpbn/learning/em)), graph(L), clpbn:set_clpbn_flag(em_solver,bp), clpbn_horus:set_horus_flag(inf_alg, bp), statistics(runtime, _), em(L,0.01,10,_,Lik), statistics(runtime, [T,_])."
function run_solver function learn_params
{ {
if [ $2 = bp ] NETWORK="'./../../examples/School/school_32'"
then CONSTRAINT=$2
if [ $4 = ve ] SOLVER=$1
then echo $NETWORK
extra_flag1=clpbn_horus:set_horus_flag\(inf_alg,$4\) /usr/bin/time -o $LOG_FILE -a -f "%U\t%S\t%e\t%M" \
extra_flag2=clpbn_horus:set_horus_flag\(elim_heuristic,$5\) $YAP << EOF >> ignore.$LOG_FILE 2>> ignore.$LOG_FILE
else use_module(library(pfl)).
extra_flag1=clpbn_horus:set_horus_flag\(inf_alg,$4\) use_module(library(clpbn/learning/em)).
extra_flag2=clpbn_horus:set_horus_flag\(schedule,$5\) [$NETWORK].
fi [$CONSTRAINT].
else set_em_solver($SOLVER).
extra_flag1=true
extra_flag2=true
fi
/usr/bin/time -o "$OUT_FILE_NAME" -a -f "real:%E\tuser:%U\tsys:%S" $YAP << EOF &>> "ignore.$OUT_FILE_NAME"
:- [pos:train].
:- ['../../../../examples/School/sch32'].
:- use_module(library(clpbn/learning/em)).
:- use_module(library(clpbn/bp)).
[$1].
graph(L), graph(L),
clpbn:set_clpbn_flag(em_solver,$2), % em(L, 0.01, 10, _, Lik),
$extra_flag1, $extra_flag2, open("$LOG_FILE", 'append', S),
em(L,0.01,10,_,Lik), format(S, "$CONSTRAINT: ~15+ Lik = ~3f\t", [Lik]),
open("$OUT_FILE_NAME", 'append',S),
format(S, '$3: ~11+ Lik = ~3f, ',[Lik]),
close(S). close(S).
EOF EOF
} }
function run_all_graphs prepare_new_run
{
echo "************************************************************************" >> "$OUT_FILE_NAME"
echo "results for solver $2" >> "$OUT_FILE_NAME"
echo "************************************************************************" >> "$OUT_FILE_NAME"
run_solver missing5 $1 missing5 $3 $4 $5
run_solver missing10 $1 missing10 $3 $4 $5
#run_solver missing20 $1 missing20 $3 $4 $5
#run_solver missing30 $1 missing30 $3 $4 $5
#run_solver missing40 $1 missing40 $3 $4 $5
#run_solver missing50 $1 missing50 $3 $4 $5
}
write_header hve
learn_params hve missing5
learn_params hve missing10
learn_params hve missing20
#learn_params hve missing30
#learn_params hve missing40
#learn_params hve missing50
#run_all_graphs bp "hve(min_neighbors) " ve min_neighbors write_header ve
#run_all_graphs bp "bp(seq_fixed) " bp seq_fixed learn_params ve missing5
#run_all_graphs bp "cbp(seq_fixed) " cbp seq_fixed learn_params ve missing10
exit learn_params ve missing20
#learn_params ve missing30
#learn_params ve missing40
#learn_params hve missing50
write_header bp
learn_params bp missing5
learn_params bp missing10
learn_params bp missing20
#learn_params bp missing30
#learn_params bp missing40
#learn_params bp missing50
run_all_graphs bp "hve(min_neighbors) " ve min_neighbors write_header cbp
run_all_graphs bp "hve(min_weight) " ve min_weight learn_params cbp missing5
run_all_graphs bp "hve(min_fill) " ve min_fill learn_params cbp missing10
run_all_graphs bp "hve(w_min_fill) " ve weighted_min_fill learn_params cbp missing20
run_all_graphs bp "bp(seq_fixed) " bp seq_fixed #learn_params cbp missing30
run_all_graphs bp "bp(max_residual) " bp max_residual #learn_params cbp missing40
run_all_graphs bp "cbp(seq_fixed) " cbp seq_fixed #learn_params cbp missing50
run_all_graphs bp "cbp(max_residual) " cbp max_residual
run_all_graphs gibbs "gibbs "
echo "************************************************************************" >> "$OUT_FILE_NAME"
echo "results for solver ve" >> "$OUT_FILE_NAME"
echo "************************************************************************" >> "$OUT_FILE_NAME"
run_solver missing5 ve missing5 $3 $4 $5
run_solver missing10 ve missing10 $3 $4 $5
run_solver missing20 ve missing20 $3 $4 $5
run_solver missing30 ve missing30 $3 $4 $5
run_solver missing40 ve missing40 $3 $4 $5
#run_solver missing50 ve missing50 $3 $4 $5 #+24h!
echo "************************************************************************" >> "$OUT_FILE_NAME"
echo "results for solver jt" >> "$OUT_FILE_NAME"
echo "************************************************************************" >> "$OUT_FILE_NAME"
run_solver missing5 jt missing5 $3 $4 $5
run_solver missing10 jt missing10 $3 $4 $5
run_solver missing20 jt missing20 $3 $4 $5
#run_solver missing30 jt missing30 $3 $4 $5 #+24h!
#run_solver missing40 jt missing40 $3 $4 $5 #+24h!
#run_solver missing50 jt missing50 $3 $4 $5 #+24h!
exit

View File

@ -1,8 +0,0 @@
#!/bin/bash
NETWORK="'../../examples/social_domain2'"
SHORTNAME="sm"
QUERY="query(X)"
POP=500

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2.sh
source ../benchs.sh source ../benchs.sh
SOLVER="bp" SOLVER="bp"
@ -26,5 +26,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "bp(shedule=seq_fixed) " seq_fixed run_all_graphs "bp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2.sh
source ../benchs.sh source ../benchs.sh
SOLVER="cbp" SOLVER="cbp"
@ -26,5 +26,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "cbp(shedule=seq_fixed) " seq_fixed run_all_graphs "cbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -17,7 +17,7 @@ main :-
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
Counting > N, !. Counting > N, !.
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
format(S, 'people(p~w).~n', [Counting]), format(S, 'person(p~w).~n', [Counting]),
Counting1 is Counting + 1, Counting1 is Counting + 1,
generate_people(S, N, Counting1). generate_people(S, N, Counting1).

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2.sh
source ../benchs.sh source ../benchs.sh
SOLVER="hve" SOLVER="hve"
@ -26,8 +26,8 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "hve(elim_heuristic=min_neighbors) " min_neighbors run_all_graphs "hve(hve_elim_heuristic=min_neighbors) " min_neighbors
#run_all_graphs "hve(elim_heuristic=min_weight) " min_weight #run_all_graphs "hve(hve_elim_heuristic=min_weight) " min_weight
#run_all_graphs "hve(elim_heuristic=min_fill) " min_fill #run_all_graphs "hve(hve_elim_heuristic=min_fill) " min_fill
#run_all_graphs "hve(elim_heuristic=weighted_min_fill) " weighted_min_fill #run_all_graphs "hve(hve_elim_heuristic=weighted_min_fill) " weighted_min_fill

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2.sh
source ../benchs.sh source ../benchs.sh
SOLVER="lbp" SOLVER="lbp"
@ -26,5 +26,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "lbp(shedule=seq_fixed) " seq_fixed run_all_graphs "lbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2.sh
source ../benchs.sh source ../benchs.sh
SOLVER="lve" SOLVER="lve"

View File

@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
NETWORK="'../../examples/social_domain2'" NETWORK="'../../examples/social_network2.pfl'"
SHORTNAME="sm" SHORTNAME="sn2"
#QUERY="smokes(p1,t), smokes(p2,t), friends(p1,p2,X)" #QUERY="smokes(p1,t), smokes(p2,t), friends(p1,p2,X)"
QUERY="friends(p1,p2,X)" QUERY="friends(p1,p2,X)"

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2ev.sh
source ../benchs.sh source ../benchs.sh
SOLVER="bp" SOLVER="bp"
@ -30,5 +30,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "bp(shedule=seq_fixed) " seq_fixed run_all_graphs "bp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2ev.sh
source ../benchs.sh source ../benchs.sh
SOLVER="cbp" SOLVER="cbp"
@ -30,5 +30,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "cbp(shedule=seq_fixed) " seq_fixed run_all_graphs "cbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -26,7 +26,7 @@ main :-
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
Counting > N, !. Counting > N, !.
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
format(S, 'people(p~w).~n', [Counting]), format(S, 'person(p~w).~n', [Counting]),
Counting1 is Counting + 1, Counting1 is Counting + 1,
generate_people(S, N, Counting1). generate_people(S, N, Counting1).

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2ev.sh
source ../benchs.sh source ../benchs.sh
SOLVER="hve" SOLVER="hve"
@ -30,8 +30,8 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "hve(elim_heuristic=min_neighbors) " min_neighbors run_all_graphs "hve(hve_elim_heuristic=min_neighbors) " min_neighbors
#run_all_graphs "hve(elim_heuristic=min_weight) " min_weight #run_all_graphs "hve(hve_elim_heuristic=min_weight) " min_weight
#run_all_graphs "hve(elim_heuristic=min_fill) " min_fill #run_all_graphs "hve(hve_elim_heuristic=min_fill) " min_fill
#run_all_graphs "hve(elim_heuristic=weighted_min_fill) " weighted_min_fill #run_all_graphs "hve(hve_elim_heuristic=weighted_min_fill) " weighted_min_fill

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
source sm.sh source sn2ev.sh
source ../benchs.sh source ../benchs.sh
SOLVER="lve" SOLVER="lve"

View File

@ -0,0 +1,8 @@
#!/bin/bash
NETWORK="'../../examples/social_network2.pfl'"
SHORTNAME="sn2ev"
QUERY="query(X)"
POP=500

View File

@ -33,5 +33,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "bp(shedule=seq_fixed) " seq_fixed run_all_graphs "bp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -32,5 +32,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "cbp(shedule=seq_fixed) " seq_fixed run_all_graphs "cbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -23,7 +23,7 @@ main :-
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
Counting > N, !. Counting > N, !.
generate_people(S, N, Counting) :- generate_people(S, N, Counting) :-
format(S, 'people(p~w).~n', [Counting]), format(S, 'person(p~w).~n', [Counting]),
Counting1 is Counting + 1, Counting1 is Counting + 1,
generate_people(S, N, Counting1). generate_people(S, N, Counting1).
@ -31,9 +31,9 @@ generate_people(S, N, Counting) :-
generate_attrs(S, N, Counting) :- generate_attrs(S, N, Counting) :-
Counting > N, !. Counting > N, !.
generate_attrs(S, N, Counting) :- generate_attrs(S, N, Counting) :-
%format(S, 'people(p~w).~n', [Counting]), %format(S, 'person(p~w).~n', [Counting]),
format(S, 'markov attends(P)::[t,f], attr~w::[t,f]', [Counting]), format(S, 'markov attends(P)::[t,f], attr~w::[t,f]', [Counting]),
format(S, '; [0.7, 0.3, 0.3, 0.3] ; [people(P)].~n',[]), format(S, '; [0.7, 0.3, 0.3, 0.3] ; [person(P)].~n',[]),
Counting1 is Counting + 1, Counting1 is Counting + 1,
generate_attrs(S, N, Counting1). generate_attrs(S, N, Counting1).

View File

@ -32,5 +32,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "hve(elim_heuristic=min_neighbors) " min_neighbors run_all_graphs "hve(hve_elim_heuristic=min_neighbors) " min_neighbors

View File

@ -32,5 +32,5 @@ function run_all_graphs
} }
prepare_new_run prepare_new_run
run_all_graphs "lbp(shedule=seq_fixed) " seq_fixed run_all_graphs "lbp(bp_msg_shedule=seq_fixed) " seq_fixed

View File

@ -1,6 +1,6 @@
#!/bin/bash #!/bin/bash
NETWORK="'../../examples/workshop_attrs'" NETWORK="'../../examples/workshop_attrs.pfl'"
SHORTNAME="wa" SHORTNAME="wa"
QUERY="series(X)" QUERY="series(X)"

View File

@ -1,40 +1,36 @@
:- module(clpbn, [{}/1, :- module(clpbn,
[{}/1,
clpbn_flag/2, clpbn_flag/2,
set_clpbn_flag/2, set_clpbn_flag/2,
set_solver/1,
set_em_solver/1,
clpbn_flag/3, clpbn_flag/3,
clpbn_key/2, clpbn_key/2,
clpbn_init_graph/1,
clpbn_init_solver/4, clpbn_init_solver/4,
clpbn_run_solver/3, clpbn_run_solver/3,
pfl_init_solver/6, pfl_init_solver/5,
pfl_run_solver/4, pfl_run_solver/3,
clpbn_finalize_solver/1, pfl_end_solver/1,
clpbn_init_solver/5,
clpbn_run_solver/4,
clpbn_init_graph/1,
probability/2, probability/2,
conditional_probability/3, conditional_probability/3,
use_parfactors/1, use_parfactors/1,
op( 500, xfy, with)]). op(500, xfy, with)
]).
:- use_module(library(atts)). :- use_module(library(atts)).
:- use_module(library(bhash)). :- use_module(library(bhash)).
:- use_module(library(lists)). :- use_module(library(lists)).
:- use_module(library(terms)). :- use_module(library(terms)).
:- use_module(library(maplist)). :- use_module(library(maplist)).
%
% avoid the overhead of using goal_expansion/2.
%
:- multifile
user:term_expansion/2.
:- dynamic
user:term_expansion/2.
:- attribute key/1, dist/2, evidence/1. :- attribute key/1, dist/2, evidence/1.
:- use_module('clpbn/ve', :- use_module('clpbn/ve',
[ve/3, [ve/3,
check_if_ve_done/1, check_if_ve_done/1,
@ -45,22 +41,6 @@
call_ve_ground_solver/6 call_ve_ground_solver/6
]). ]).
:- use_module('clpbn/horus_ground',
[call_horus_ground_solver/6,
check_if_horus_ground_solver_done/1,
init_horus_ground_solver/5,
run_horus_ground_solver/4,
finalize_horus_ground_solver/1
]).
:- use_module('clpbn/horus_lifted',
[call_horus_lifted_solver/3,
check_if_horus_lifted_solver_done/1,
init_horus_lifted_solver/4,
run_horus_lifted_solver/3,
finalize_horus_lifted_solver/1
]).
:- use_module('clpbn/jt', :- use_module('clpbn/jt',
[jt/3, [jt/3,
init_jt_solver/4, init_jt_solver/4,
@ -76,11 +56,6 @@
call_bdd_ground_solver/6 call_bdd_ground_solver/6
]). ]).
%% :- use_module('clpbn/bnt',
%% [do_bnt/3,
%% check_if_bnt_done/1
%% ]).
:- use_module('clpbn/gibbs', :- use_module('clpbn/gibbs',
[gibbs/3, [gibbs/3,
check_if_gibbs_done/1, check_if_gibbs_done/1,
@ -89,19 +64,34 @@
]). ]).
:- use_module('clpbn/pgrammar', :- use_module('clpbn/pgrammar',
[init_pcg_solver/4, [pcg_init_graph/0,
run_pcg_solver/3, init_pcg_solver/4,
pcg_init_graph/0 run_pcg_solver/3
]). ]).
:- use_module('clpbn/graphs', :- use_module('clpbn/horus_ground',
[ [call_horus_ground_solver/6,
clpbn2graph/1 check_if_horus_ground_solver_done/1,
init_horus_ground_solver/5,
run_horus_ground_solver/3,
end_horus_ground_solver/1
]). ]).
:- use_module('clpbn/horus_lifted',
[call_horus_lifted_solver/3,
check_if_horus_lifted_solver_done/1,
init_horus_lifted_solver/4,
run_horus_lifted_solver/3,
end_horus_lifted_solver/1
]).
%% :- use_module('clpbn/bnt',
%% [do_bnt/3,
%% check_if_bnt_done/1
%% ]).
:- use_module('clpbn/dists', :- use_module('clpbn/dists',
[ [dist/4,
dist/4,
get_dist/4, get_dist/4,
get_evidence_position/3, get_evidence_position/3,
get_evidence_from_position/3, get_evidence_from_position/3,
@ -109,39 +99,65 @@
]). ]).
:- use_module('clpbn/evidence', :- use_module('clpbn/evidence',
[ [store_evidence/1,
store_evidence/1,
add_stored_evidence/2, add_stored_evidence/2,
incorporate_evidence/2, incorporate_evidence/2,
check_stored_evidence/2, check_stored_evidence/2,
put_evidence/2 put_evidence/2
]). ]).
:- use_module('clpbn/ground_factors',
[generate_network/5]).
:- use_module('clpbn/utils', :- use_module('clpbn/utils',
[ [sort_vars_by_key/3]).
sort_vars_by_key/3
]). :- use_module('clpbn/graphs',
[clpbn2graph/1]).
:- use_module('clpbn/graphviz', :- use_module('clpbn/graphviz',
[clpbn2gviz/4]). [clpbn2gviz/4]).
:- use_module(clpbn/ground_factors, %
[generate_network/5]). % avoid the overhead of using goal_expansion/2.
%
:- multifile user:term_expansion/2.
:- dynamic user:term_expansion/2.
:- dynamic solver/1,output/1,use/1,suppress_attribute_display/1, parameter_softening/1, em_solver/1, use_parfactors/1. :- dynamic
solver/1,
solver(ve). em_solver/1,
em_solver(bp). suppress_attribute_display/1,
parameter_softening/1,
use_parfactors/1,
output/1,
use/1.
:- meta_predicate probability(:,-), conditional_probability(:,:,-). :- meta_predicate probability(:,-), conditional_probability(:,:,-).
%output(xbif(user_error)).
%output(gviz(user_error)). solver(hve).
output(no). em_solver(hve).
suppress_attribute_display(false). suppress_attribute_display(false).
parameter_softening(m_estimate(10)). parameter_softening(m_estimate(10)).
use_parfactors(off). use_parfactors(off).
output(no).
%output(xbif(user_error)).
%output(gviz(user_error)).
ground_solver(ve).
ground_solver(hve).
ground_solver(jt).
ground_solver(bdd).
ground_solver(bp).
ground_solver(cbp).
ground_solver(gibbs).
lifted_solver(lve).
lifted_solver(lkc).
lifted_solver(lbp).
clpbn_flag(Flag, Option) :- clpbn_flag(Flag, Option) :-
clpbn_flag(Flag, Option, Option). clpbn_flag(Flag, Option, Option).
@ -149,34 +165,48 @@ clpbn_flag(Flag,Option) :-
set_clpbn_flag(Flag,Option) :- set_clpbn_flag(Flag,Option) :-
clpbn_flag(Flag, _, Option). clpbn_flag(Flag, _, Option).
clpbn_flag(output,Before,After) :-
retract(output(Before)),
assert(output(After)).
clpbn_flag(solver,Before,After) :- clpbn_flag(solver,Before,After) :-
retract(solver(Before)), retract(solver(Before)),
assert(solver(After)). assert(solver(After)).
clpbn_flag(em_solver,Before,After) :- clpbn_flag(em_solver,Before,After) :-
retract(em_solver(Before)), retract(em_solver(Before)),
assert(em_solver(After)). assert(em_solver(After)).
clpbn_flag(bnt_solver,Before,After) :- clpbn_flag(bnt_solver,Before,After) :-
retract(bnt:bnt_solver(Before)), retract(bnt:bnt_solver(Before)),
assert(bnt:bnt_solver(After)). assert(bnt:bnt_solver(After)).
clpbn_flag(bnt_path,Before,After) :- clpbn_flag(bnt_path,Before,After) :-
retract(bnt:bnt_path(Before)), retract(bnt:bnt_path(Before)),
assert(bnt:bnt_path(After)). assert(bnt:bnt_path(After)).
clpbn_flag(bnt_model,Before,After) :- clpbn_flag(bnt_model,Before,After) :-
retract(bnt:bnt_model(Before)), retract(bnt:bnt_model(Before)),
assert(bnt:bnt_model(After)). assert(bnt:bnt_model(After)).
clpbn_flag(suppress_attribute_display,Before,After) :- clpbn_flag(suppress_attribute_display,Before,After) :-
retract(suppress_attribute_display(Before)), retract(suppress_attribute_display(Before)),
assert(suppress_attribute_display(After)). assert(suppress_attribute_display(After)).
clpbn_flag(parameter_softening,Before,After) :- clpbn_flag(parameter_softening,Before,After) :-
retract(parameter_softening(Before)), retract(parameter_softening(Before)),
assert(parameter_softening(After)). assert(parameter_softening(After)).
clpbn_flag(use_factors,Before,After) :- clpbn_flag(use_factors,Before,After) :-
retract(use_parfactors(Before)), retract(use_parfactors(Before)),
assert(use_parfactors(After)). assert(use_parfactors(After)).
clpbn_flag(output,Before,After) :-
retract(output(Before)),
assert(output(After)).
set_solver(Solver) :-
set_clpbn_flag(solver,Solver).
set_em_solver(Solver) :-
set_clpbn_flag(em_solver,Solver).
{_} :- {_} :-
solver(none), !. solver(none), !.
{ Var = Key with Dist } :- { Var = Key with Dist } :-
@ -203,8 +233,10 @@ init_clpbn_vars(El) :-
create_mutable(El, Mutable), create_mutable(El, Mutable),
b_setval(clpbn_qvars, Mutable). b_setval(clpbn_qvars, Mutable).
check_constraint(Constraint, _, _, Constraint) :- var(Constraint), !. check_constraint(Constraint, _, _, Constraint) :-
check_constraint((A->D), _, _, (A->D)) :- var(A), !. var(Constraint), !.
check_constraint((A->D), _, _, (A->D)) :-
var(A), !.
check_constraint((([A|B].L)->D), Vars, NVars, (([A|B].NL)->D)) :- !, check_constraint((([A|B].L)->D), Vars, NVars, (([A|B].NL)->D)) :- !,
check_cpt_input_vars(L, Vars, NVars, NL). check_cpt_input_vars(L, Vars, NVars, NL).
check_constraint(Dist, _, _, Dist). check_constraint(Dist, _, _, Dist).
@ -240,11 +272,13 @@ clpbn_marginalise(V, Dist) :-
% %
project_attributes(GVars0, _AVars0) :- project_attributes(GVars0, _AVars0) :-
use_parfactors(on), use_parfactors(on),
clpbn_flag(solver, Solver), Solver \= fove, !, clpbn_flag(solver, Solver),
ground_solver(Solver),
generate_network(GVars0, GKeys, Keys, Factors, Evidence), generate_network(GVars0, GKeys, Keys, Factors, Evidence),
b_setval(clpbn_query_variables, f(GVars0,Evidence)), b_setval(clpbn_query_variables, f(GVars0,Evidence)),
simplify_query(GVars0, GVars), simplify_query(GVars0, GVars),
( GKeys = [] (
GKeys = []
-> ->
GVars0 = [V|_], GVars0 = [V|_],
clpbn_display:put_atts(V, [posterior([],[],[],[])]) clpbn_display:put_atts(V, [posterior([],[],[],[])])
@ -322,35 +356,27 @@ get_rid_of_ev_vars([V|LVs0],[V|LVs]) :-
get_rid_of_ev_vars(LVs0,LVs). get_rid_of_ev_vars(LVs0,LVs).
% do nothing if we don't have query variables to compute. % Call a solver with keys, not actual variables
write_out(_, [], _, _) :- !.
write_out(graphs, _, AVars, _) :-
clpbn2graph(AVars).
write_out(ve, GVars, AVars, DiffVars) :-
ve(GVars, AVars, DiffVars).
write_out(jt, GVars, AVars, DiffVars) :-
jt(GVars, AVars, DiffVars).
write_out(bdd, GVars, AVars, DiffVars) :-
bdd(GVars, AVars, DiffVars).
write_out(bp, _GVars, _AVars, _DiffVars) :-
writeln('interface not supported any longer').
%bp(GVars, AVars, DiffVars).
write_out(gibbs, GVars, AVars, DiffVars) :-
gibbs(GVars, AVars, DiffVars).
write_out(bnt, GVars, AVars, DiffVars) :-
do_bnt(GVars, AVars, DiffVars).
write_out(fove, GVars, AVars, DiffVars) :-
call_horus_lifted_solver(GVars, AVars, DiffVars).
% call a solver with keys, not actual variables
call_ground_solver(bp, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
call_horus_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(bdd, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
call_bdd_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(ve, GVars, GoalKeys, Keys, Factors, Evidence) :- !, call_ground_solver(ve, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
call_ve_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ). call_ve_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(hve, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
clpbn_horus:set_horus_flag(ground_solver, ve),
call_horus_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(bdd, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
call_bdd_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(bp, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
clpbn_horus:set_horus_flag(ground_solver, bp),
call_horus_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(cbp, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
clpbn_horus:set_horus_flag(ground_solver, cbp),
call_horus_ground_solver(GVars, GoalKeys, Keys, Factors, Evidence, _Answ).
call_ground_solver(Solver, GVars, _GoalKeys, Keys, Factors, Evidence) :- call_ground_solver(Solver, GVars, _GoalKeys, Keys, Factors, Evidence) :-
% traditional solver % fall back to traditional solver
b_hash_new(Hash0), b_hash_new(Hash0),
foldl(gvar_in_hash, GVars, Hash0, HashI), foldl(gvar_in_hash, GVars, Hash0, HashI),
foldl(key_to_var, Keys, AllVars, HashI, Hash1), foldl(key_to_var, Keys, AllVars, HashI, Hash1),
@ -362,6 +388,44 @@ call_ground_solver(Solver, GVars, _GoalKeys, Keys, Factors, Evidence) :-
write_out(Solver, [GVars], AllVars, _), write_out(Solver, [GVars], AllVars, _),
assert(use_parfactors(on)). assert(use_parfactors(on)).
% do nothing if we don't have query variables to compute.
write_out(_, [], _, _) :- !.
write_out(graphs, _, AVars, _) :- !,
clpbn2graph(AVars).
write_out(ve, GVars, AVars, DiffVars) :- !,
ve(GVars, AVars, DiffVars).
write_out(jt, GVars, AVars, DiffVars) :- !,
jt(GVars, AVars, DiffVars).
write_out(bdd, GVars, AVars, DiffVars) :- !,
bdd(GVars, AVars, DiffVars).
write_out(gibbs, GVars, AVars, DiffVars) :- !,
gibbs(GVars, AVars, DiffVars).
write_out(lve, GVars, AVars, DiffVars) :- !,
clpbn_horus:set_horus_flag(lifted_solver, lve),
call_horus_lifted_solver(GVars, AVars, DiffVars).
write_out(lkc, GVars, AVars, DiffVars) :- !,
clpbn_horus:set_horus_flag(lifted_solver, lkc),
call_horus_lifted_solver(GVars, AVars, DiffVars).
write_out(lbp, GVars, AVars, DiffVars) :- !,
clpbn_horus:set_horus_flag(lifted_solver, lbp),
call_horus_lifted_solver(GVars, AVars, DiffVars).
write_out(bnt, GVars, AVars, DiffVars) :- !,
do_bnt(GVars, AVars, DiffVars).
write_out(Solver, _, _, _) :-
format("Error: solver '~w' is unknown.", [Solver]),
fail.
% %
% convert a PFL network (without constraints) % convert a PFL network (without constraints)
% into CLP(BN) for evaluation % into CLP(BN) for evaluation
@ -466,14 +530,11 @@ bind_clpbn(T, Var, Key, Dist, Parents, []) :- var(T),
; ;
fail fail
). ).
bind_clpbn(_, Var, _, _, _, _, []) :-
use(bnt),
check_if_bnt_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :- bind_clpbn(_, Var, _, _, _, _, []) :-
use(ve), use(ve),
check_if_ve_done(Var), !. check_if_ve_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :- bind_clpbn(_, Var, _, _, _, _, []) :-
use(bp), use(hve),
check_if_horus_ground_solver_done(Var), !. check_if_horus_ground_solver_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :- bind_clpbn(_, Var, _, _, _, _, []) :-
use(jt), use(jt),
@ -481,6 +542,15 @@ bind_clpbn(_, Var, _, _, _, _, []) :-
bind_clpbn(_, Var, _, _, _, _, []) :- bind_clpbn(_, Var, _, _, _, _, []) :-
use(bdd), use(bdd),
check_if_bdd_done(Var), !. check_if_bdd_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :-
use(bp),
check_if_horus_ground_solver_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :-
use(cbp),
check_if_horus_ground_solver_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :-
use(bnt),
check_if_bnt_done(Var), !.
bind_clpbn(T, Var, Key0, _, _, _, []) :- bind_clpbn(T, Var, Key0, _, _, _, []) :-
get_atts(Var, [key(Key)]), !, get_atts(Var, [key(Key)]), !,
( (
@ -532,6 +602,15 @@ user:term_expansion((A :- {}), ( :- true )) :- !, % evidence
clpbn_key(Var,Key) :- clpbn_key(Var,Key) :-
get_atts(Var, [key(Key)]). get_atts(Var, [key(Key)]).
%
% only useful for probabilistic context free grammars
%
clpbn_init_graph(pcg) :- !,
pcg_init_graph.
clpbn_init_graph(_).
% %
% This is a routine to start a solver, called by the learning procedures (ie, em). % This is a routine to start a solver, called by the learning procedures (ie, em).
% LVs is a list of lists of variables one is interested in eventually marginalising out % LVs is a list of lists of variables one is interested in eventually marginalising out
@ -544,90 +623,112 @@ clpbn_init_solver(LVs, Vs0, VarsWithUnboundKeys, State) :-
solver(Solver), solver(Solver),
clpbn_init_solver(Solver, LVs, Vs0, VarsWithUnboundKeys, State). clpbn_init_solver(Solver, LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(gibbs, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_gibbs_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(ve, LVs, Vs0, VarsWithUnboundKeys, State) :- clpbn_init_solver(ve, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_ve_solver(LVs, Vs0, VarsWithUnboundKeys, State). init_ve_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(bp, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_horus_ground_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(jt, LVs, Vs0, VarsWithUnboundKeys, State) :- clpbn_init_solver(jt, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_jt_solver(LVs, Vs0, VarsWithUnboundKeys, State). init_jt_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(bdd, LVs, Vs0, VarsWithUnboundKeys, State) :- clpbn_init_solver(bdd, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_bdd_solver(LVs, Vs0, VarsWithUnboundKeys, State). init_bdd_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(gibbs, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_gibbs_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(pcg, LVs, Vs0, VarsWithUnboundKeys, State) :- clpbn_init_solver(pcg, LVs, Vs0, VarsWithUnboundKeys, State) :-
init_pcg_solver(LVs, Vs0, VarsWithUnboundKeys, State). init_pcg_solver(LVs, Vs0, VarsWithUnboundKeys, State).
%
% This is a routine to start a solver, called by the learning procedures (ie, em).
% LVs is a list of lists of variables one is interested in eventually marginalising out
% Vs0 gives the original graph
% AllDiffs gives variables that are not fully constrainted, ie, we don't fully know
% the key. In this case, we assume different instances will be bound to different
% values at the end of the day.
%
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, VE, bdd) :-
init_bdd_ground_solver(QueryKeys, AllKeys, Factors, Evidence, VE).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, VE, ve) :-
init_ve_ground_solver(QueryKeys, AllKeys, Factors, Evidence, VE).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, VE, bp) :-
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, VE).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, VE, hve) :-
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, VE).
% %
% LVs is the list of lists of variables to marginalise % LVs is the list of lists of variables to marginalise
% Vs is the full graph % Vs is the full graph
% Ps are the probabilities on LVs. % Ps are the probabilities on LVs.
% %
%
clpbn_run_solver(LVs, LPs, State) :- clpbn_run_solver(LVs, LPs, State) :-
solver(Solver), solver(Solver),
clpbn_run_solver(Solver, LVs, LPs, State). clpbn_run_solver(Solver, LVs, LPs, State).
clpbn_run_solver(gibbs, LVs, LPs, State) :-
run_gibbs_solver(LVs, LPs, State).
clpbn_run_solver(ve, LVs, LPs, State) :- clpbn_run_solver(ve, LVs, LPs, State) :-
run_ve_solver(LVs, LPs, State). run_ve_solver(LVs, LPs, State).
clpbn_run_solver(bp, LVs, LPs, State) :-
run_horus_ground_solver(LVs, LPs, State).
clpbn_run_solver(jt, LVs, LPs, State) :- clpbn_run_solver(jt, LVs, LPs, State) :-
run_jt_solver(LVs, LPs, State). run_jt_solver(LVs, LPs, State).
clpbn_run_solver(bdd, LVs, LPs, State) :- clpbn_run_solver(bdd, LVs, LPs, State) :-
run_bdd_solver(LVs, LPs, State). run_bdd_solver(LVs, LPs, State).
clpbn_run_solver(gibbs, LVs, LPs, State) :-
run_gibbs_solver(LVs, LPs, State).
clpbn_run_solver(pcg, LVs, LPs, State) :- clpbn_run_solver(pcg, LVs, LPs, State) :-
run_pcg_solver(LVs, LPs, State). run_pcg_solver(LVs, LPs, State).
pfl_run_solver(LVs, LPs, State, ve) :- %
% This is a routine to start a solver, called by the learning procedures (ie, em).
%
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State) :-
em_solver(Solver),
(lifted_solver(Solver) ->
format("Error: you cannot use a lifted solver for learning.", [Solver]), fail
;
true
),
(ground_solver(Solver) ->
true
;
format("Error: solver '~w' is unknown.", [Solver]), fail
),
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State, Solver).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State, ve) :- !,
init_ve_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State, hve) :- !,
clpbn_horus:set_horus_flag(ground_solver, ve),
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State, bdd) :- !,
init_bdd_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State, bp) :- !,
clpbn_horus:set_horus_flag(ground_solver, bp),
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State).
pfl_init_solver(QueryKeys, AllKeys, Factors, Evidence, State, cbp) :- !,
clpbn_horus:set_horus_flag(ground_solver, cbp),
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State).
pfl_init_solver(_, _, _, _, _, Solver) :-
format("Error: solver '~w' can't be used for learning.", [Solver]),
fail.
pfl_run_solver(LVs, LPs, State) :-
em_solver(Solver),
pfl_run_solver(LVs, LPs, State, Solver).
pfl_run_solver(LVs, LPs, State, ve) :- !,
run_ve_ground_solver(LVs, LPs, State). run_ve_ground_solver(LVs, LPs, State).
pfl_run_solver(LVs, LPs, State, bdd) :-
pfl_run_solver(LVs, LPs, State, hve) :- !,
run_horus_ground_solver(LVs, LPs, State).
pfl_run_solver(LVs, LPs, State, bdd) :- !,
run_bdd_ground_solver(LVs, LPs, State). run_bdd_ground_solver(LVs, LPs, State).
pfl_run_solver(LVs, LPs, State, bp) :-
run_horus_ground_solver(LVs, LPs, State, bp). pfl_run_solver(LVs, LPs, State, bp) :- !,
pfl_run_solver(LVs, LPs, State, hve) :- run_horus_ground_solver(LVs, LPs, State).
run_horus_ground_solver(LVs, LPs, State, hve).
pfl_run_solver(LVs, LPs, State, cbp) :- !,
run_horus_ground_solver(LVs, LPs, State).
pfl_end_solver(State) :-
(em_solver(hve) ; em_solver(bp) ; em_solver(cbp)),
end_horus_ground_solver(State).
pfl_end_solver(_State).
add_keys(Key1+V1,_Key2,Key1+V1). add_keys(Key1+V1,_Key2,Key1+V1).
%
% only useful for probabilistic context free grammars
%
clpbn_init_graph(pcg) :- !,
pcg_init_graph.
clpbn_init_graph(_).
clpbn_finalize_solver(State) :-
solver(bp), !,
functor(State, _, Last),
arg(Last, State, Info),
finalize_horus_ground_solver(Info).
clpbn_finalize_solver(_State).
probability(Goal, Prob) :- probability(Goal, Prob) :-
findall(Prob, do_probability(Goal, [], Prob), [Prob]). findall(Prob, do_probability(Goal, [], Prob), [Prob]).

View File

@ -1,8 +1,8 @@
% %
% generate explicit CPTs % generate explicit CPTs
% %
:- module(clpbn_aggregates, [ :- module(clpbn_aggregates,
check_for_agg_vars/2, [check_for_agg_vars/2,
cpt_average/6, cpt_average/6,
cpt_average/7, cpt_average/7,
cpt_max/6, cpt_max/6,
@ -10,7 +10,8 @@
avg_factors/5 avg_factors/5
]). ]).
:- use_module(library(clpbn), [{}/1]). :- use_module(library(clpbn),
[{}/1]).
:- use_module(library(lists), :- use_module(library(lists),
[last/2, [last/2,
@ -24,19 +25,21 @@
:- use_module(library(matrix), :- use_module(library(matrix),
[matrix_new/3, [matrix_new/3,
matrix_to_list/2, matrix_to_list/2,
matrix_set/3]). matrix_set/3
]).
:- use_module(library(clpbn/dists), :- use_module(library(clpbn/dists),
[ [add_dist/6,
add_dist/6, get_dist_domain_size/2
get_dist_domain_size/2]). ]).
:- use_module(library(clpbn/matrix_cpt_utils), :- use_module(library(clpbn/matrix_cpt_utils),
[normalise_CPT_on_lines/3]). [normalise_CPT_on_lines/3]).
:- use_module(library(pfl), :- use_module(library(pfl),
[skolem/2, [skolem/2,
add_ground_factor/5]). add_ground_factor/5
]).
:- use_module(library(bhash)). :- use_module(library(bhash)).
@ -270,7 +273,9 @@ include_qevidence(_, MAT, MAT, NewParents, NewParents, _, Vs, Vs).
check_consistency(L1, Ev, MAT0, MAT1, L1, MAT, NewParents0, NewParents, Vs, IVs, NewVs) :- check_consistency(L1, Ev, MAT0, MAT1, L1, MAT, NewParents0, NewParents, Vs, IVs, NewVs) :-
sumlist(L1, Tot), sumlist(L1, Tot),
nth0(Ev, L1, Val), nth0(Ev, L1, Val),
(Val == Tot -> (
Val == Tot
->
MAT1 = MAT, MAT1 = MAT,
NewParents = [], NewParents = [],
Vs = NewVs Vs = NewVs

View File

@ -1064,4 +1064,3 @@ build_cnf(CNF, IVs, Indics, AllParms, AllParmValues, Val) :-
set_to_ones(Extra), set_to_ones(Extra),
ddnnf_is(F, Val). ddnnf_is(F, Val).

View File

@ -1,20 +1,23 @@
:- module(bnt, [do_bnt/3, :- module(bnt,
[do_bnt/3,
create_bnt_graph/2, create_bnt_graph/2,
check_if_bnt_done/1]). check_if_bnt_done/1
]).
:- use_module(library('clpbn/display'), [ :- use_module(library('clpbn/display'),
clpbn_bind_vals/3]). [clpbn_bind_vals/3]).
:- use_module(library('clpbn/dists'), [ :- use_module(library('clpbn/dists'),
get_dist_domain_size/2, [get_dist_domain_size/2,
get_dist_domain/2, get_dist_domain/2,
get_dist_params/2 get_dist_params/2
]). ]).
:- use_module(library('clpbn/discrete_utils'), [ :- use_module(library('clpbn/discrete_utils'),
reorder_CPT/5]). [reorder_CPT/5]).
:- use_module(library(matlab), [start_matlab/1, :- use_module(library(matlab),
[start_matlab/1,
close_matlab/0, close_matlab/0,
matlab_on/0, matlab_on/0,
matlab_eval_string/1, matlab_eval_string/1,
@ -27,7 +30,8 @@
matlab_call/2 matlab_call/2
]). ]).
:- use_module(library(dgraphs), [dgraph_new/1, :- use_module(library(dgraphs),
[dgraph_new/1,
dgraph_add_vertices/3, dgraph_add_vertices/3,
dgraph_add_edges/3, dgraph_add_edges/3,
dgraph_top_sort/2, dgraph_top_sort/2,
@ -35,11 +39,13 @@
dgraph_edges/2 dgraph_edges/2
]). ]).
:- use_module(library(lists), [append/3, :- use_module(library(lists),
member/2,nth/3]). [append/3,
member/2,nth/3
]).
:- use_module(library(ordsets), [ :- use_module(library(ordsets),
ord_insert/3]). [ord_insert/3]).
:- yap_flag(write_strings,on). :- yap_flag(write_strings,on).
@ -422,4 +428,3 @@ mk_evidence_query([V|L], [H|T], [ar(1,Pos,El)|LN]) :-
nth(El,D,H), nth(El,D,H),
mk_evidence_query(L, T, LN). mk_evidence_query(L, T, LN).

View File

@ -3,8 +3,8 @@
[influences/3, [influences/3,
factor_influences/4, factor_influences/4,
init_influences/3, init_influences/3,
influences/4] influences/4
). ]).
:- use_module(library(maplist)). :- use_module(library(maplist)).
@ -14,13 +14,15 @@
dgraph_add_vertex/3, dgraph_add_vertex/3,
dgraph_neighbors/3, dgraph_neighbors/3,
dgraph_edge/3, dgraph_edge/3,
dgraph_transpose/2]). dgraph_transpose/2
]).
:- use_module(library(rbtrees), :- use_module(library(rbtrees),
[rb_new/1, [rb_new/1,
rb_lookup/3, rb_lookup/3,
rb_insert/4, rb_insert/4,
rb_visit/2]). rb_visit/2
]).
factor_influences(Vs, QVars, Ev, LV) :- factor_influences(Vs, QVars, Ev, LV) :-
init_factor_influences(Vs, G, RG), init_factor_influences(Vs, G, RG),
@ -90,7 +92,8 @@ process_new_variable(V, Evs, G, RG, Vs0, Vs2) :-
throw_below(Evs, G, RG, Child, Vs0, Vs1) :- throw_below(Evs, G, RG, Child, Vs0, Vs1) :-
rb_lookup(Child, [_|B], Vs0), !, rb_lookup(Child, [_|B], Vs0), !,
( (
B == b -> B == b
->
Vs0 = Vs1 % been there before Vs0 = Vs1 % been there before
; ;
B = b, % mark it B = b, % mark it
@ -120,7 +123,8 @@ handle_ball_from_above(V, Evs, G, RG, Vs0, Vs1) :-
throw_above(Evs, G, RG, Parent, Vs0, Vs1) :- throw_above(Evs, G, RG, Parent, Vs0, Vs1) :-
rb_lookup(Parent, [T|_], Vs0), !, rb_lookup(Parent, [T|_], Vs0), !,
( (
T == t -> T == t
->
Vs1 = Vs0 % been there before Vs1 = Vs0 % been there before
; ;
T = t, % mark it T = t, % mark it

View File

@ -1,10 +1,14 @@
:- module(discrete_utils, [project_from_CPT/3, :- module(discrete_utils,
[project_from_CPT/3,
reorder_CPT/5, reorder_CPT/5,
get_dist_size/2]). get_dist_size/2
]).
:- use_module(library(clpbn/dists), [get_dist_domain_size/2, :- use_module(library(clpbn/dists),
get_dist_domain/2]). [get_dist_domain_size/2,
get_dist_domain/2
]).
% %
% remove columns from a table % remove columns from a table
% %
@ -143,4 +147,3 @@ get_sizes([V|Deps], [Sz|Sizes]) :-
get_dist_domain_size(Id,Sz), get_dist_domain_size(Id,Sz),
get_sizes(Deps, Sizes). get_sizes(Deps, Sizes).

View File

@ -1,17 +1,20 @@
:- module(clpbn_display, [
clpbn_bind_vals/3]). :- module(clpbn_display,
[clpbn_bind_vals/3]).
:- use_module(library(lists), :- use_module(library(lists),
[ [member/2]).
member/2
]).
:- use_module(library(clpbn/dists), [get_dist_domain/2]). :- use_module(library(clpbn/dists),
[get_dist_domain/2]).
:- use_module(library(clpbn), [use_parfactors/1]). :- use_module(library(clpbn),
[use_parfactors/1]).
:- use_module(library(maplist)). :- use_module(library(maplist)).
:- use_module(library(atts)).
:- attribute posterior/4. :- attribute posterior/4.

View File

@ -3,8 +3,7 @@
% %
:- module(clpbn_dist, :- module(clpbn_dist,
[ [dist/1,
dist/1,
dist/4, dist/4,
dists/1, dists/1,
dist_new_table/2, dist_new_table/2,
@ -30,7 +29,10 @@
additive_dists/6 additive_dists/6
]). ]).
:- use_module(library(lists),[nth0/3,append/3]). :- use_module(library(lists),
[nth0/3,
append/3
]).
:- use_module(library(clpbn), :- use_module(library(clpbn),
[use_parfactors/1]). [use_parfactors/1]).
@ -39,11 +41,13 @@
[matrix_new/4, [matrix_new/4,
matrix_new/3, matrix_new/3,
matrix_to_list/2, matrix_to_list/2,
matrix_to_logs/1]). matrix_to_logs/1
]).
:- use_module(library(clpbn/matrix_cpt_utils), :- use_module(library(clpbn/matrix_cpt_utils),
[random_CPT/2, [random_CPT/2,
uniform_CPT/2]). uniform_CPT/2
]).
/* /*
:- mode dist(+, -). :- mode dist(+, -).
@ -365,3 +369,4 @@ reset_all_dists.
additive_dists(ip(Domain,Tabs1), ip(Domain,Tabs2), Parents1, Parents2, ip(Domain,Tabs), Parents) :- additive_dists(ip(Domain,Tabs1), ip(Domain,Tabs2), Parents1, Parents2, ip(Domain,Tabs), Parents) :-
append(Tabs1, Tabs2, Tabs), append(Tabs1, Tabs2, Tabs),
append(Parents1, Parents2, Parents). append(Parents1, Parents2, Parents).

View File

@ -4,26 +4,24 @@
% %
:- module(clpbn_evidence, :- module(clpbn_evidence,
[ [store_evidence/1,
store_evidence/1,
incorporate_evidence/2, incorporate_evidence/2,
check_stored_evidence/2, check_stored_evidence/2,
add_stored_evidence/2, add_stored_evidence/2,
put_evidence/2 put_evidence/2
]). ]).
:- use_module(library(clpbn), [ :- use_module(library(clpbn),
{}/1, [{}/1,
clpbn_flag/3, clpbn_flag/3,
set_clpbn_flag/2 set_clpbn_flag/2
]). ]).
:- use_module(library('clpbn/dists'), [ :- use_module(library('clpbn/dists'),
get_dist/4 [get_dist/4]).
]).
:- use_module(library(rbtrees), [ :- use_module(library(rbtrees),
rb_new/1, [rb_new/1,
rb_lookup/3, rb_lookup/3,
rb_insert/4 rb_insert/4
]). ]).
@ -86,7 +84,6 @@ add_links([K0|TVs],K) :-
assert(edge(K,K0)), assert(edge(K,K0)),
add_links(TVs,K). add_links(TVs,K).
incorporate_evidence(Vs,AllVs) :- incorporate_evidence(Vs,AllVs) :-
rb_new(Cache0), rb_new(Cache0),
create_open_list(Vs, OL, FL, Cache0, CacheI), create_open_list(Vs, OL, FL, Cache0, CacheI),

View File

@ -11,48 +11,51 @@
[gibbs/3, [gibbs/3,
check_if_gibbs_done/1, check_if_gibbs_done/1,
init_gibbs_solver/4, init_gibbs_solver/4,
run_gibbs_solver/3]). run_gibbs_solver/3
]).
:- use_module(library(rbtrees), :- use_module(library(rbtrees),
[rb_new/1, [rb_new/1,
rb_insert/4, rb_insert/4,
rb_lookup/3]). rb_lookup/3
]).
:- use_module(library(lists), :- use_module(library(lists),
[member/2, [member/2,
append/3, append/3,
delete/3, delete/3,
max_list/2, max_list/2,
sum_list/2]). sum_list/2
]).
:- use_module(library(ordsets), :- use_module(library(ordsets),
[ord_subtract/3]). [ord_subtract/3]).
:- use_module(library('clpbn/matrix_cpt_utils'), [ :- use_module(library('clpbn/matrix_cpt_utils'),
project_from_CPT/3, [project_from_CPT/3,
reorder_CPT/5, reorder_CPT/5,
multiply_possibly_deterministic_factors/3, multiply_possibly_deterministic_factors/3,
column_from_possibly_deterministic_CPT/3, column_from_possibly_deterministic_CPT/3,
normalise_possibly_deterministic_CPT/2, normalise_possibly_deterministic_CPT/2,
list_from_CPT/2]). list_from_CPT/2
]).
:- use_module(library('clpbn/utils'), [ :- use_module(library('clpbn/utils'),
check_for_hidden_vars/3]). [check_for_hidden_vars/3]).
:- use_module(library('clpbn/dists'), [ :- use_module(library('clpbn/dists'),
get_possibly_deterministic_dist_matrix/5, [get_possibly_deterministic_dist_matrix/5,
get_dist_domain_size/2]). get_dist_domain_size/2
]).
:- use_module(library('clpbn/topsort'), [ :- use_module(library('clpbn/topsort'),
topsort/2]). [topsort/2]).
:- use_module(library('clpbn/display'), [ :- use_module(library('clpbn/display'),
clpbn_bind_vals/3]). [clpbn_bind_vals/3]).
:- use_module(library('clpbn/connected'), :- use_module(library('clpbn/connected'),
[ [influences/3]).
influences/3
]).
:- dynamic gibbs_params/3. :- dynamic gibbs_params/3.
@ -542,5 +545,3 @@ divide_list([C|Add], Sum, [P|Dist]) :-
P is C/Sum, P is C/Sum,
divide_list(Add, Sum, Dist). divide_list(Add, Sum, Dist).

View File

@ -3,13 +3,14 @@
% Just output a graph with all the variables. % Just output a graph with all the variables.
% %
:- module(clpbn2graph, [clpbn2graph/1]). :- module(clpbn2graph,
[clpbn2graph/1]).
:- use_module(library('clpbn/utils'), [ :- use_module(library('clpbn/utils'),
check_for_hidden_vars/3]). [check_for_hidden_vars/3]).
:- use_module(library('clpbn/dists'), [ :- use_module(library('clpbn/dists'),
get_dist/4]). [get_dist/4]).
:- attribute node/0. :- attribute node/0.
@ -37,7 +38,3 @@ translate_vars([V|Vs],[K|Ks]) :-
clpbn:get_atts(V, [key(K)]), clpbn:get_atts(V, [key(K)]),
translate_vars(Vs,Ks). translate_vars(Vs,Ks).

View File

@ -1,4 +1,6 @@
:- module(clpbn_gviz, [clpbn2gviz/4]).
:- module(clpbn_gviz,
[clpbn2gviz/4]).
clpbn2gviz(Stream, Name, Network, Output) :- clpbn2gviz(Stream, Name, Network, Output) :-
format(Stream, 'digraph ~w { format(Stream, 'digraph ~w {

View File

@ -1,40 +1,34 @@
%parfactor( :- module(pfl_ground_factors,
% [ability(P),grade(C,S), satisfaction(C,S,P)], [generate_network/5,
% \phi = [....],
% [P,C,S],
% [P \in [p1,p2,p4], C \in [c1,c3], S \in [s2,s3]]).
% [S \= s2])
:- module(pfl_ground_factors, [
generate_network/5,
f/3 f/3
]). ]).
:- use_module(library(bhash), [ :- use_module(library(bhash),
b_hash_new/1, [b_hash_new/1,
b_hash_lookup/3, b_hash_lookup/3,
b_hash_insert/4, b_hash_insert/4,
b_hash_to_list/2]). b_hash_to_list/2
]).
:- use_module(library(lists), [ :- use_module(library(lists),
delete/3, [member/2]).
nth0/3,
member/2]).
:- use_module(library(maplist)). :- use_module(library(maplist)).
:- use_module(library(pfl), [ :- use_module(library(atts)).
factor/6,
:- use_module(library(pfl),
[factor/6,
defined_in_factor/2, defined_in_factor/2,
skolem/2]). skolem/2
]).
:- use_module(library(clpbn/aggregates), [ :- use_module(library(clpbn/aggregates),
avg_factors/5]). [avg_factors/5]).
:- use_module(library(clpbn/dists), [ :- use_module(library(clpbn/dists),
dist/4]). [dist/4]).
:- dynamic currently_defined/1, queue/1, f/4. :- dynamic currently_defined/1, queue/1, f/4.
@ -140,7 +134,8 @@ do_propagate(_K) :-
add_factor(factor(Type, Id, Ks, _, _Phi, Constraints), NKs) :- add_factor(factor(Type, Id, Ks, _, _Phi, Constraints), NKs) :-
% writeln(+Ks), % writeln(+Ks),
( Ks = [K,Els], var(Els) (
Ks = [K,Els], var(Els)
-> ->
% aggregate factor % aggregate factor
once(run(Constraints)), once(run(Constraints)),

View File

@ -1,8 +1,9 @@
:- module(hmm,
:- module(hmm, [init_hmm/0, [init_hmm/0,
hmm_state/1, hmm_state/1,
emission/1]). emission/1
]).
:- ensure_loaded(library(clpbn)). :- ensure_loaded(library(clpbn)).
@ -49,18 +50,15 @@ hmm_state(N/A,Mod) :-
(First > 2 -> (First > 2 ->
Last = Key, ! Last = Key, !
; ;
nb_getval(trie, Trie), trie_check_entry(Trie, Key, _) nb_getval(trie, Trie), trie_check_entry(Trie, Key, _) ->
->
% leave work for solver! % leave work for solver!
%
Last = Key, ! Last = Key, !
; ;
% first time we saw this entry % first time we saw this entry
nb_getval(trie, Trie), trie_put_entry(Trie, Key, _), nb_getval(trie, Trie), trie_put_entry(Trie, Key, _),
fail fail
) )
) )).
).
build_args(4,[A,B,C,D],[A,B,C],A,D). build_args(4,[A,B,C,D],[A,B,C],A,D).
build_args(3, [A,B,C], [A,B],A,C). build_args(3, [A,B,C], [A,B],A,C).
@ -79,5 +77,3 @@ cvt_vals([A|B],[A|B]).
find_probs(Logs,Nth,Log) :- find_probs(Logs,Nth,Log) :-
arg(Nth,Logs,Log). arg(Nth,Logs,Log).

View File

@ -5,12 +5,11 @@
********************************************************/ ********************************************************/
:- module(clpbn_horus, :- module(clpbn_horus,
[set_solver/1, [set_horus_flag/2,
set_horus_flag/1,
cpp_create_lifted_network/3, cpp_create_lifted_network/3,
cpp_create_ground_network/4, cpp_create_ground_network/4,
cpp_set_parfactors_params/2, cpp_set_parfactors_params/3,
cpp_set_factors_params/2, cpp_set_factors_params/3,
cpp_run_lifted_solver/3, cpp_run_lifted_solver/3,
cpp_run_ground_solver/3, cpp_run_ground_solver/3,
cpp_set_vars_information/2, cpp_set_vars_information/2,
@ -19,8 +18,9 @@
cpp_free_ground_network/1 cpp_free_ground_network/1
]). ]).
:- use_module(library(clpbn),
[set_clpbn_flag/2]). :- catch(load_foreign_files([horus], [], init_predicates), _, patch_things_up)
-> true ; warning.
patch_things_up :- patch_things_up :-
@ -28,38 +28,29 @@ patch_things_up :-
warning :- warning :-
format(user_error,"Horus library not installed: cannot use bp, fove~n.",[]). format(user_error,"Horus library not installed: cannot use hve, bp, cbp, lve, lkc and lbp~n.",[]).
:- catch(load_foreign_files([horus], [], init_predicates), _, patch_things_up)
-> true ; warning.
set_solver(ve) :- !, set_clpbn_flag(solver,ve).
set_solver(bdd) :- !, set_clpbn_flag(solver,bdd).
set_solver(jt) :- !, set_clpbn_flag(solver,jt).
set_solver(gibbs) :- !, set_clpbn_flag(solver,gibbs).
set_solver(lve) :- !, set_clpbn_flag(solver,fove), set_horus_flag(lifted_solver, lve).
set_solver(lbp) :- !, set_clpbn_flag(solver,fove), set_horus_flag(lifted_solver, lbp).
set_solver(lkc) :- !, set_clpbn_flag(solver,fove), set_horus_flag(lifted_solver, lkc).
set_solver(hve) :- !, set_clpbn_flag(solver,bp), set_horus_flag(ground_solver, ve).
set_solver(bp) :- !, set_clpbn_flag(solver,bp), set_horus_flag(ground_solver, bp).
set_solver(cbp) :- !, set_clpbn_flag(solver,bp), set_horus_flag(ground_solver, cbp).
set_solver(S) :- throw(error('unknown solver ', S)).
set_horus_flag(K,V) :- cpp_set_horus_flag(K,V). set_horus_flag(K,V) :- cpp_set_horus_flag(K,V).
:- cpp_set_horus_flag(schedule, seq_fixed). :- cpp_set_horus_flag(verbosity, 0).
%:- cpp_set_horus_flag(schedule, seq_random).
%:- cpp_set_horus_flag(schedule, parallel).
%:- cpp_set_horus_flag(schedule, max_residual).
:- cpp_set_horus_flag(accuracy, 0.0001). %:- cpp_set_horus_flag(use_logarithms, false).
:- cpp_set_horus_flag(use_logarithms, true).
:- cpp_set_horus_flag(max_iter, 1000). %:- cpp_set_horus_flag(hve_elim_heuristic, sequential).
%:- cpp_set_horus_flag(hve_elim_heuristic, min_neighbors).
%:- cpp_set_horus_flag(hve_elim_heuristic, min_weight).
%:- cpp_set_horus_flag(hve_elim_heuristic, min_fill).
:- cpp_set_horus_flag(hve_elim_heuristic, weighted_min_fill).
:- cpp_set_horus_flag(use_logarithms, false). :- cpp_set_horus_flag(bp_msg_schedule, seq_fixed).
% :- cpp_set_horus_flag(use_logarithms, true). %:- cpp_set_horus_flag(bp_msg_schedule, seq_random).
%:- cpp_set_horus_flag(bp_msg_schedule, parallel).
%:- cpp_set_horus_flag(bp_msg_schedule, max_residual).
:- cpp_set_horus_flag(bp_accuracy, 0.0001).
:- cpp_set_horus_flag(bp_max_iter, 1000).

View File

@ -11,92 +11,79 @@
[call_horus_ground_solver/6, [call_horus_ground_solver/6,
check_if_horus_ground_solver_done/1, check_if_horus_ground_solver_done/1,
init_horus_ground_solver/5, init_horus_ground_solver/5,
run_horus_ground_solver/4, run_horus_ground_solver/3,
finalize_horus_ground_solver/1 end_horus_ground_solver/1
]). ]).
:- use_module(horus, :- use_module(horus,
[cpp_create_ground_network/4, [cpp_create_ground_network/4,
cpp_set_factors_params/2, cpp_set_factors_params/3,
cpp_run_ground_solver/3, cpp_run_ground_solver/3,
cpp_set_vars_information/2,
cpp_free_ground_network/1, cpp_free_ground_network/1,
set_solver/1 cpp_set_vars_information/2
]). ]).
:- use_module(library('clpbn/dists'), :- use_module(library('clpbn/numbers'),
[dist/4, [lists_of_keys_to_ids/6,
get_dist_domain/2, keys_to_numbers/7
get_dist_domain_size/2,
get_dist_params/2
]). ]).
:- use_module(library('clpbn/display'), :- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]). [clpbn_bind_vals/3]).
:- use_module(library(clpbn/numbers)). :- use_module(library(pfl),
[get_pfl_parameters/2,
skolem/2
]).
:- use_module(library(charsio), :- use_module(library(charsio),
[term_to_atom/2]). [term_to_atom/2]).
:- use_module(library(pfl),
[skolem/2]).
:- use_module(library(maplist)). :- use_module(library(maplist)).
:- use_module(library(lists)).
:- use_module(library(atts)). call_horus_ground_solver(QueryVars, QueryKeys, AllKeys, Factors, Evidence,
Output) :-
:- use_module(library(bhash)).
call_horus_ground_solver(QueryVars, QueryKeys, AllKeys, Factors, Evidence, Output) :-
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State), init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, State),
run_solver(State, [QueryKeys], Solutions), run_horus_ground_solver([QueryKeys], Solutions, State),
clpbn_bind_vals([QueryVars], Solutions, Output), clpbn_bind_vals([QueryVars], Solutions, Output),
finalize_horus_ground_solver(State). end_horus_ground_solver(State).
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, state(Network,Hash4,Id4)) :- init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence,
get_factors_type(Factors, Type), state(Network,Hash,Id,DistIds)) :-
keys_to_numbers(AllKeys, Factors, Evidence, Hash4, Id4, FactorIds, EvidenceIds), factors_type(Factors, Type),
cpp_create_ground_network(Type, FactorIds, EvidenceIds, Network), keys_to_numbers(AllKeys, Factors, Evidence, Hash, Id, FacIds, EvIds),
%writeln(network:(Type, FactorIds, EvidenceIds, Network)), writeln(''), %writeln(network:(type=Type, factors=FacIds, evidence=EvIds)), nl,
maplist(get_var_information, AllKeys, StatesNames), cpp_create_ground_network(Type, FacIds, EvIds, Network),
maplist(term_to_atom, AllKeys, KeysAtoms), %maplist(term_to_atom, AllKeys, VarNames),
cpp_set_vars_information(KeysAtoms, StatesNames). %maplist(get_domain, AllKeys, Domains),
%cpp_set_vars_information(VarNames, Domains),
maplist(get_dist_id, FacIds, DistIds0),
sort(DistIds0, DistIds).
run_horus_ground_solver(_QueryVars, Solutions, horus(GKeys, Keys, Factors, Evidence), Solver) :- run_horus_ground_solver(QueryKeys, Solutions,
set_solver(Solver), state(Network,Hash,Id, DistIds)) :-
call_horus_ground_solver_for_probabilities(GKeys, Keys, Factors, Evidence, Solutions).
% TODO this is not beeing called!
finalize_horus_ground_solver(state(Network,_Hash,_Id)) :-
cpp_free_ground_network(Network).
run_solver(state(Network,Hash,Id), QueryKeys, Solutions) :-
%get_dists_parameters(DistIds, DistsParams),
%cpp_set_factors_params(Network, DistsParams),
lists_of_keys_to_ids(QueryKeys, QueryIds, Hash, _, Id, _), lists_of_keys_to_ids(QueryKeys, QueryIds, Hash, _, Id, _),
%maplist(get_pfl_parameters, DistIds, DistParams),
%cpp_set_factors_params(Network, DistIds, DistParams),
cpp_run_ground_solver(Network, QueryIds, Solutions). cpp_run_ground_solver(Network, QueryIds, Solutions).
get_factors_type([f(bayes, _, _)|_], bayes) :- ! . end_horus_ground_solver(state(Network,_Hash,_Id, _DistIds)) :-
get_factors_type([f(markov, _, _)|_], markov) :- ! . cpp_free_ground_network(Network).
get_var_information(_:Key, Domain) :- !, factors_type([f(bayes, _, _)|_], bayes) :- ! .
factors_type([f(markov, _, _)|_], markov) :- ! .
get_dist_id(f(_, _, _, DistId), DistId).
get_domain(_:Key, Domain) :- !,
skolem(Key, Domain). skolem(Key, Domain).
get_var_information(Key, Domain) :- get_domain(Key, Domain) :-
skolem(Key, Domain). skolem(Key, Domain).
%get_dists_parameters([],[]).
%get_dists_parameters([Id|Ids], [dist(Id, Params)|DistsInfo]) :-
% get_dist_params(Id, Params),
% get_dists_parameters(Ids, DistsInfo).

View File

@ -12,12 +12,12 @@
check_if_horus_lifted_solver_done/1, check_if_horus_lifted_solver_done/1,
init_horus_lifted_solver/4, init_horus_lifted_solver/4,
run_horus_lifted_solver/3, run_horus_lifted_solver/3,
finalize_horus_lifted_solver/1 end_horus_lifted_solver/1
]). ]).
:- use_module(horus, :- use_module(horus,
[cpp_create_lifted_network/3, [cpp_create_lifted_network/3,
cpp_set_parfactors_params/2, cpp_set_parfactors_params/3,
cpp_run_lifted_solver/3, cpp_run_lifted_solver/3,
cpp_free_lifted_network/1 cpp_free_lifted_network/1
]). ]).
@ -25,83 +25,65 @@
:- use_module(library('clpbn/display'), :- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]). [clpbn_bind_vals/3]).
:- use_module(library('clpbn/dists'),
[get_dist_params/2]).
:- use_module(library(pfl), :- use_module(library(pfl),
[factor/6, [factor/6,
skolem/2, skolem/2,
get_pfl_parameters/2 get_pfl_parameters/2
]). ]).
:- use_module(library(maplist)).
call_horus_lifted_solver(QueryVars, AllVars, Output) :- call_horus_lifted_solver(QueryVars, AllVars, Output) :-
init_horus_lifted_solver(_, AllVars, _, State), init_horus_lifted_solver(_, AllVars, _, State),
run_horus_lifted_solver(QueryVars, Solutions, State), run_horus_lifted_solver(QueryVars, Solutions, State),
clpbn_bind_vals(QueryVars, Solutions, Output), clpbn_bind_vals(QueryVars, Solutions, Output),
finalize_horus_lifted_solver(State). end_horus_lifted_solver(State).
init_horus_lifted_solver(_, AllVars, _, state(ParfactorList, DistIds)) :- init_horus_lifted_solver(_, AllVars, _, state(Network, DistIds)) :-
get_parfactors(Parfactors), get_parfactors(Parfactors),
get_dist_ids(Parfactors, DistIds0), get_observed_keys(AllVars, ObservedKeys),
sort(DistIds0, DistIds), %writeln(network:(parfactors=Parfactors, evidence=ObservedKeys)), nl,
get_observed_vars(AllVars, ObservedVars), cpp_create_lifted_network(Parfactors, ObservedKeys, Network),
%writeln(parfactors:Parfactors:'\n'), maplist(get_dist_id, Parfactors, DistIds0),
%writeln(evidence:ObservedVars:'\n'), sort(DistIds0, DistIds).
cpp_create_lifted_network(Parfactors, ObservedVars, ParfactorList).
run_horus_lifted_solver(QueryVars, Solutions, state(ParfactorList, DistIds)) :- run_horus_lifted_solver(QueryVars, Solutions, state(Network, DistIds)) :-
get_query_keys(QueryVars, QueryKeys), maplist(get_query_keys, QueryVars, QueryKeys),
get_dists_parameters(DistIds, DistsParams), %maplist(get_pfl_parameters, DistIds,DistsParams),
%writeln(dists:DistsParams), writeln(''), %cpp_set_parfactors_params(Network, DistIds, DistsParams),
cpp_set_parfactors_params(ParfactorList, DistsParams), cpp_run_lifted_solver(Network, QueryKeys, Solutions).
cpp_run_lifted_solver(ParfactorList, QueryKeys, Solutions).
finalize_horus_lifted_solver(state(ParfactorList, _)) :- end_horus_lifted_solver(state(Network, _)) :-
cpp_free_lifted_network(ParfactorList). cpp_free_lifted_network(Network).
%
% Enumerate all parfactors and enumerate their domain as tuples.
%
:- table get_parfactors/1. :- table get_parfactors/1.
%
% enumerate all parfactors and enumerate their domain as tuples.
%
% output is list of pf(
% Id: an unique number
% Ks: a list of keys, also known as the pf formula [a(X),b(Y),c(X,Y)]
% Vs: the list of free variables [X,Y]
% Phi: the table following usual CLP(BN) convention
% Tuples: ground bindings for variables in Vs, of the form [fv(x,y)]
%
get_parfactors(Factors) :- get_parfactors(Factors) :-
findall(F, is_factor(F), Factors). findall(F, is_factor(F), Factors).
is_factor(pf(Id, Ks, Rs, Phi, Tuples)) :- is_factor(pf(Id, Ks, Rs, Phi, Tuples)) :-
factor(_Type, Id, Ks, Vs, Table, Constraints), factor(_Type, Id, Ks, Vs, Table, Constraints),
get_ranges(Ks,Rs), maplist(get_range, Ks, Rs),
Table \= avg, Table \= avg,
gen_table(Table, Phi), gen_table(Table, Phi),
all_tuples(Constraints, Vs, Tuples). all_tuples(Constraints, Vs, Tuples).
get_ranges([],[]). get_range(K, Range) :-
get_ranges(K.Ks, Range.Rs) :- !,
skolem(K, Domain), skolem(K, Domain),
length(Domain,Range), length(Domain, Range).
get_ranges(Ks, Rs).
gen_table(Table, Phi) :- gen_table(Table, Phi) :-
( is_list(Table) ( is_list(Table) -> Phi = Table ; call(user:Table, Phi) ).
->
Phi = Table
;
call(user:Table, Phi)
).
all_tuples(Constraints, Tuple, Tuples) :- all_tuples(Constraints, Tuple, Tuples) :-
@ -114,35 +96,20 @@ run(Goal.Constraints) :-
run(Constraints). run(Constraints).
get_dist_ids([], []). get_dist_id(pf(DistId, _, _, _, _), DistId).
get_dist_ids(pf(Id, _, _, _, _).Parfactors, Id.DistIds) :-
get_dist_ids(Parfactors, DistIds).
get_observed_vars([], []). get_observed_keys([], []).
get_observed_vars(V.AllAttVars, [K:E|ObservedVars]) :- get_observed_keys(V.AllAttVars, [K:E|ObservedKeys]) :-
clpbn:get_atts(V,[key(K)]), clpbn:get_atts(V,[key(K)]),
( clpbn:get_atts(V,[evidence(E)]) ; pfl:evidence(K,E) ), !, ( clpbn:get_atts(V,[evidence(E)]) ; pfl:evidence(K,E) ), !,
get_observed_vars(AllAttVars, ObservedVars). get_observed_keys(AllAttVars, ObservedKeys).
get_observed_vars(V.AllAttVars, ObservedVars) :- get_observed_keys(_V.AllAttVars, ObservedKeys) :-
clpbn:get_atts(V,[key(_K)]), !, get_observed_keys(AllAttVars, ObservedKeys).
get_observed_vars(AllAttVars, ObservedVars).
get_query_keys([], []). get_query_keys([], []).
get_query_keys(E1.L1, E2.L2) :- get_query_keys(V.AttVars, K.Ks) :-
get_query_keys_2(E1,E2), clpbn:get_atts(V,[key(K)]), !,
get_query_keys(L1, L2). get_query_keys(AttVars, Ks).
get_query_keys_2([], []).
get_query_keys_2(V.AttVars, [RV|RVs]) :-
clpbn:get_atts(V,[key(RV)]), !,
get_query_keys_2(AttVars, RVs).
get_dists_parameters([], []).
get_dists_parameters([Id|Ids], [dist(Id, Params)|DistsInfo]) :-
get_pfl_parameters(Id, Params),
get_dists_parameters(Ids, DistsInfo).

View File

@ -1,8 +1,9 @@
:- module(jt, [jt/3, :- module(jt,
[jt/3,
init_jt_solver/4, init_jt_solver/4,
run_jt_solver/3]). run_jt_solver/3
]).
:- use_module(library(dgraphs), :- use_module(library(dgraphs),
[dgraph_new/1, [dgraph_new/1,
@ -41,14 +42,16 @@
:- use_module(library(rbtrees), :- use_module(library(rbtrees),
[rb_new/1, [rb_new/1,
rb_insert/4, rb_insert/4,
rb_lookup/3]). rb_lookup/3
]).
:- use_module(library(ordsets), :- use_module(library(ordsets),
[ord_subset/2, [ord_subset/2,
ord_insert/3, ord_insert/3,
ord_intersection/3, ord_intersection/3,
ord_del_element/3, ord_del_element/3,
ord_memberchk/2]). ord_memberchk/2
]).
:- use_module(library(lists), :- use_module(library(lists),
[reverse/2]). [reverse/2]).
@ -61,7 +64,8 @@
:- use_module(library('clpbn/dists'), :- use_module(library('clpbn/dists'),
[get_dist_domain_size/2, [get_dist_domain_size/2,
get_dist_domain/2, get_dist_domain/2,
get_dist_matrix/5]). get_dist_matrix/5
]).
:- use_module(library('clpbn/matrix_cpt_utils'), :- use_module(library('clpbn/matrix_cpt_utils'),
[project_from_CPT/3, [project_from_CPT/3,
@ -74,14 +78,14 @@
get_CPT_sizes/2, get_CPT_sizes/2,
reset_CPT_that_disagrees/5, reset_CPT_that_disagrees/5,
sum_out_from_CPT/4, sum_out_from_CPT/4,
list_from_CPT/2]). list_from_CPT/2
]).
:- use_module(library('clpbn/display'), [ :- use_module(library('clpbn/display'),
clpbn_bind_vals/3]). [clpbn_bind_vals/3]).
:- use_module(library('clpbn/connected'), :- use_module(library('clpbn/connected'),
[ [init_influences/3,
init_influences/3,
influences/4 influences/4
]). ]).
@ -290,8 +294,7 @@ add_clique_edges([], _, _, Edges, Edges).
add_clique_edges([Clique1|Cliques], Clique, Sz, Edges0, EdgesF) :- add_clique_edges([Clique1|Cliques], Clique, Sz, Edges0, EdgesF) :-
ord_intersection(Clique1, Clique, Int), ord_intersection(Clique1, Clique, Int),
Int \== Clique, Int \== Clique,
( (Int = [] ->
Int = [] ->
add_clique_edges(Cliques, Clique, Sz, Edges0, EdgesF) add_clique_edges(Cliques, Clique, Sz, Edges0, EdgesF)
; ;
% we connect % we connect

View File

@ -1,3 +1,4 @@
:- module(clpbn_matrix_utils, :- module(clpbn_matrix_utils,
[init_CPT/3, [init_CPT/3,
project_from_CPT/3, project_from_CPT/3,
@ -21,7 +22,8 @@
random_CPT/2, random_CPT/2,
uniform_CPT/2, uniform_CPT/2,
uniform_CPT_as_list/2, uniform_CPT_as_list/2,
normalise_CPT_on_lines/3]). normalise_CPT_on_lines/3
]).
:- use_module(library(matrix), :- use_module(library(matrix),
[matrix_new/4, [matrix_new/4,
@ -45,7 +47,8 @@
matrix_agg_lines/3, matrix_agg_lines/3,
matrix_agg_cols/3, matrix_agg_cols/3,
matrix_op_to_lines/4, matrix_op_to_lines/4,
matrix_column/3]). matrix_column/3
]).
init_CPT(List, Sizes, TAB) :- init_CPT(List, Sizes, TAB) :-
matrix_new(floats, Sizes, List, TAB), matrix_new(floats, Sizes, List, TAB),

View File

@ -1,13 +1,13 @@
:- module(clpbn_numbers, :- module(clpbn_numbers,
[ [keys_to_numbers/7,
keys_to_numbers/7,
keys_to_numbers/9, keys_to_numbers/9,
lists_of_keys_to_ids/6 lists_of_keys_to_ids/6
]). ]).
:- use_module(library(bhash)). :- use_module(library(bhash)).
:- use_module(library(maplist)). :- use_module(library(maplist)).
:- use_module(library(pfl), :- use_module(library(pfl),
[skolem/2, [skolem/2,
get_pfl_cpt/5 get_pfl_cpt/5
@ -60,4 +60,3 @@ evidence_to_id(Key=Ev, I0=Ev, Hash0, Hash, I0, I) :-
b_hash_insert(Hash0, Key, I0, Hash), b_hash_insert(Hash0, Key, I0, Hash),
I is I0+1. I is I0+1.

View File

@ -2,21 +2,20 @@
:- style_check(all). :- style_check(all).
:- module(clpbn_pgrammar,[grammar_to_atts/1, :- module(clpbn_pgrammar,
[grammar_to_atts/1,
grammar_prob/2, grammar_prob/2,
grammar_mle/2, grammar_mle/2,
init_pcg_solver/4, init_pcg_solver/4,
run_pcg_solver/3, run_pcg_solver/3,
pcg_init_graph/0]). pcg_init_graph/0
]).
:- load_files([library(clpbn)], :- load_files([library(clpbn)],
[ if(not_loaded), [if(not_loaded), silent(true)]).
silent(true)
]).
:- use_module([library(lists)], :- use_module([library(lists)],
[ sum_list/2 [sum_list/2]).
]).
:- use_module([library(matrix)], :- use_module([library(matrix)],
[matrix_new/3, [matrix_new/3,

View File

@ -29,7 +29,8 @@
:- use_module(library(bhash), :- use_module(library(bhash),
[b_hash_new/4, [b_hash_new/4,
b_hash_lookup/3, b_hash_lookup/3,
b_hash_insert/4]). b_hash_insert/4
]).
:- meta_predicate clpbn_table(:), :- meta_predicate clpbn_table(:),
clpbn_tabled_clause(:.?), clpbn_tabled_clause(:.?),
@ -43,14 +44,13 @@
clpbn_tabled_number_of_clauses(:,-), clpbn_tabled_number_of_clauses(:,-),
clpbn_is_tabled(:). clpbn_is_tabled(:).
:- use_module(library(terms), [ :- use_module(library(terms),
instantiated_term_hash/4, [instantiated_term_hash/4,
variant/2 variant/2
]). ]).
:- use_module(evidence, [ :- use_module(evidence,
put_evidence/2 [put_evidence/2]).
]).
:- dynamic clpbn_table/3. :- dynamic clpbn_table/3.
@ -108,8 +108,7 @@ clpbn_table(F/N,M) :-
L0 = [_|Args0], L0 = [_|Args0],
IGoal =.. [NF|Args0], IGoal =.. [NF|Args0],
asserta(clpbn_table(S, M, IGoal)), asserta(clpbn_table(S, M, IGoal)),
assert( assert((M:S :-
(M:S :-
!, !,
% write(S: ' ' ), % write(S: ' ' ),
b_getval(clpbn_tables, Tab), b_getval(clpbn_tables, Tab),
@ -130,8 +129,7 @@ clpbn_table(F/N,M) :-
; ;
throw(error(tabled_clpbn_predicate_should_never_fail,S)) throw(error(tabled_clpbn_predicate_should_never_fail,S))
) )
) )).
).
take_tail([V], V, [], V1, [V1]) :- !. take_tail([V], V, [], V1, [V1]) :- !.
take_tail([A|L0], V, [A|L1], V1, [A|L2]) :- take_tail([A|L0], V, [A|L1], V1, [A|L2]) :-
@ -154,8 +152,7 @@ clpbn_tableallargs(F/N,M) :-
atom_concat(F, '___tabled', NF), atom_concat(F, '___tabled', NF),
NKey =.. [NF|Args], NKey =.. [NF|Args],
asserta(clpbn_table(Key, M, NKey)), asserta(clpbn_table(Key, M, NKey)),
assert( assert((M:Key :-
(M:Key :-
!, !,
b_getval(clpbn_tables, Tab), b_getval(clpbn_tables, Tab),
(b_hash_lookup(Key, Out, Tab) -> (b_hash_lookup(Key, Out, Tab) ->
@ -165,8 +162,7 @@ clpbn_tableallargs(F/N,M) :-
b_setval(clpbn_tables, NewTab), b_setval(clpbn_tables, NewTab),
once(M:NKey) once(M:NKey)
) )
) )).
).
clpbn_table_nondet(M:X) :- !, clpbn_table_nondet(M:X) :- !,
clpbn_table_nondet(X,M). clpbn_table_nondet(X,M).
@ -185,8 +181,8 @@ clpbn_table_nondet(F/N,M) :-
atom_concat(F, '___tabled', NF), atom_concat(F, '___tabled', NF),
NKey =.. [NF|Args], NKey =.. [NF|Args],
asserta(clpbn_table(Key, M, NKey)), asserta(clpbn_table(Key, M, NKey)),
assert( assert((M:Key :-
(M:Key :- % writeln(in:Key), % writeln(in:Key),
b_getval(clpbn_tables, Tab), b_getval(clpbn_tables, Tab),
(b_hash_lookup(Key, Out, Tab) -> (b_hash_lookup(Key, Out, Tab) ->
fail fail
@ -195,8 +191,7 @@ clpbn_table_nondet(F/N,M) :-
b_setval(clpbn_tables, NewTab), b_setval(clpbn_tables, NewTab),
M:NKey M:NKey
) )
) )).
).
user:term_expansion((P :- Gs), NC) :- user:term_expansion((P :- Gs), NC) :-
clpbn_table(P, M, NP), clpbn_table(P, M, NP),
@ -364,4 +359,3 @@ clpbn_is_tabled(M:Clause, _) :- !,
clpbn_is_tabled(Head, M) :- clpbn_is_tabled(Head, M) :-
clpbn_table(Head, M, _). clpbn_table(Head, M, _).

View File

@ -1,11 +1,13 @@
:- module(topsort, [topsort/2]). :- module(topsort,
[topsort/2]).
:- use_module(library(dgraphs), :- use_module(library(dgraphs),
[dgraph_new/1, [dgraph_new/1,
dgraph_add_edges/3, dgraph_add_edges/3,
dgraph_add_vertices/3, dgraph_add_vertices/3,
dgraph_top_sort/2]). dgraph_top_sort/2
]).
/* simple implementation of a topological sorting algorithm */ /* simple implementation of a topological sorting algorithm */
/* graph is as Node-[Parents] */ /* graph is as Node-[Parents] */
@ -31,4 +33,3 @@ add_edges([], _V) --> [].
add_edges([P|Parents], V) --> [P-V], add_edges([P|Parents], V) --> [P-V],
add_edges(Parents, V). add_edges(Parents, V).

View File

@ -1,9 +1,11 @@
:- module(clpbn_utils, [
clpbn_not_var_member/2, :- module(clpbn_utils,
[clpbn_not_var_member/2,
clpbn_var_member/2, clpbn_var_member/2,
check_for_hidden_vars/3, check_for_hidden_vars/3,
sort_vars_by_key/3, sort_vars_by_key/3,
sort_vars_by_key_and_parents/3]). sort_vars_by_key_and_parents/3
]).
% %
% It may happen that variables from a previous query may still be around. % It may happen that variables from a previous query may still be around.
@ -52,12 +54,10 @@ get_keys([_|AVars], KeysVars) :- % may be non-CLPBN vars.
merge_same_key([], [], _, []). merge_same_key([], [], _, []).
merge_same_key([K1-V1,K2-V2|Vs], SortedAVars, Ks, UnifiableVars) :- merge_same_key([K1-V1,K2-V2|Vs], SortedAVars, Ks, UnifiableVars) :-
K1 == K2, !, K1 == K2, !,
(clpbn:get_atts(V1, [evidence(E)]) (clpbn:get_atts(V1, [evidence(E)]) ->
->
clpbn:put_atts(V2, [evidence(E)]) clpbn:put_atts(V2, [evidence(E)])
; ;
clpbn:get_atts(V2, [evidence(E)]) clpbn:get_atts(V2, [evidence(E)]) ->
->
clpbn:put_atts(V1, [evidence(E)]) clpbn:put_atts(V1, [evidence(E)])
; ;
true true
@ -113,4 +113,3 @@ transform_parents([P|Parents0],[P|NParents],KeyVarsF,KeyVars0) :-
transform_parents([P|Parents0],[V|NParents],[P-V|KeyVarsF],KeyVars0) :- transform_parents([P|Parents0],[V|NParents],[P-V|KeyVarsF],KeyVars0) :-
transform_parents(Parents0,NParents,KeyVarsF,KeyVars0). transform_parents(Parents0,NParents,KeyVarsF,KeyVars0).

View File

@ -14,41 +14,45 @@
*********************************/ *********************************/
:- module(clpbn_ve, [ve/3, :- module(clpbn_ve,
[ve/3,
check_if_ve_done/1, check_if_ve_done/1,
init_ve_solver/4, init_ve_solver/4,
run_ve_solver/3, run_ve_solver/3,
init_ve_ground_solver/5, init_ve_ground_solver/5,
run_ve_ground_solver/3, run_ve_ground_solver/3,
call_ve_ground_solver/6]). call_ve_ground_solver/6
]).
:- attribute size/1, all_diffs/1. :- use_module(library(atts)).
:- use_module(library(ordsets), :- use_module(library(ordsets),
[ord_union/3, [ord_union/3,
ord_member/2]). ord_member/2
]).
:- use_module(library('clpbn/xbif'), [clpbn2xbif/3]). :- use_module(library('clpbn/xbif'),
[clpbn2xbif/3]).
:- use_module(library('clpbn/graphviz'), [clpbn2gviz/4]). :- use_module(library('clpbn/graphviz'),
[clpbn2gviz/4]).
:- use_module(library('clpbn/dists'), :- use_module(library('clpbn/dists'),
[ [dist/4,
dist/4,
get_dist_domain_size/2, get_dist_domain_size/2,
get_dist_params/2, get_dist_params/2,
get_dist_domain_size/2, get_dist_domain_size/2,
get_dist_matrix/5]). get_dist_matrix/5
]).
:- use_module(library('clpbn/utils'), [ :- use_module(library('clpbn/utils'),
clpbn_not_var_member/2]). [clpbn_not_var_member/2]).
:- use_module(library('clpbn/display'), [ :- use_module(library('clpbn/display'),
clpbn_bind_vals/3]). [clpbn_bind_vals/3]).
:- use_module(library('clpbn/connected'), :- use_module(library('clpbn/connected'),
[ [init_influences/3,
init_influences/3,
influences/4, influences/4,
factor_influences/4 factor_influences/4
]). ]).
@ -58,8 +62,7 @@
:- use_module(library(clpbn/numbers)). :- use_module(library(clpbn/numbers)).
:- use_module(library(lists), :- use_module(library(lists),
[ [member/2,
member/2,
append/3, append/3,
delete/3 delete/3
]). ]).
@ -73,6 +76,8 @@
:- use_module(library('clpbn/aggregates'), :- use_module(library('clpbn/aggregates'),
[check_for_agg_vars/2]). [check_for_agg_vars/2]).
:- attribute size/1, all_diffs/1.
% %
% uses a bipartite graph where bigraph(Vs, NFs, Fs) % uses a bipartite graph where bigraph(Vs, NFs, Fs)
% Vs=map variables to lists of factors % Vs=map variables to lists of factors
@ -472,4 +477,3 @@ multiply([F0|Fs], Vs, T) :-
multiply_factor(f(_,Vs1,T1), f(_,Vs0,T0), f(_,Vs,T)) :- multiply_factor(f(_,Vs1,T1), f(_,Vs0,T0), f(_,Vs,T)) :-
multiply_CPTs(T1, Vs1, T0, Vs0, T, Vs). multiply_CPTs(T1, Vs1, T0, Vs0, T, Vs).

View File

@ -1,11 +1,13 @@
%:- style_check(all). %:- style_check(all).
:- module(viterbi, [viterbi/4]). :- module(viterbi,
[viterbi/4]).
:- use_module(library(lists), :- use_module(library(lists),
[nth/3, [nth/3,
member/2]). member/2
]).
:- use_module(library(assoc)). :- use_module(library(assoc)).
@ -17,8 +19,8 @@
:- ensure_loaded(library('clpbn/hmm')). :- ensure_loaded(library('clpbn/hmm')).
:- use_module(library('clpbn/dists'), [ :- use_module(library('clpbn/dists'),
get_dist_params/2]). [get_dist_params/2]).
:- meta_predicate viterbi(:,:,+,-). :- meta_predicate viterbi(:,:,+,-).
@ -231,5 +233,3 @@ trace(L1,Next,Dump,Map,Trace0,Trace) :-
matrix_get(Dump,[NL,P],New), matrix_get(Dump,[NL,P],New),
trace(NL,New,Dump,Map,[Key|Trace0],Trace). trace(NL,New,Dump,Map,[Key|Trace0],Trace).

View File

@ -1,7 +1,6 @@
:- module(clpbn_vmap, :- module(clpbn_vmap,
[ [init_vmap/1, % init_vmap(-Vmap)
init_vmap/1, % init_vmap(-Vmap)
add_to_vmap/4, % add_to_vmap(+V,-I,+VMap0,VMapF) add_to_vmap/4, % add_to_vmap(+V,-I,+VMap0,VMapF)
get_from_vmap/3, % add_to_vmap(+V,-I,+VMap0) get_from_vmap/3, % add_to_vmap(+V,-I,+VMap0)
vars_to_numbers/4, % vars_to_numbers(+Vs,-Is,+VMap0,VMapF) vars_to_numbers/4, % vars_to_numbers(+Vs,-Is,+VMap0,VMapF)
@ -39,6 +38,3 @@ lvars_to_numbers(LVs, LIs, VMap0, VMap) :-
vmap_to_list(vmap(_,Map), L) :- vmap_to_list(vmap(_,Map), L) :-
rb_visit(Map, L). rb_visit(Map, L).

View File

@ -2,10 +2,11 @@
% XMLBIF support for CLP(BN) % XMLBIF support for CLP(BN)
% %
:- module(xbif, [clpbn2xbif/3]). :- module(xbif,
[clpbn2xbif/3]).
:- use_module(library('clpbn/dists'), [ :- use_module(library('clpbn/dists'),
get_dist_domain/2]). [get_dist_domain/2]).
clpbn2xbif(Stream, Name, Network) :- clpbn2xbif(Stream, Name, Network) :-
format(Stream, '<?xml version="1.0" encoding="US-ASCII"?> format(Stream, '<?xml version="1.0" encoding="US-ASCII"?>

View File

@ -5,7 +5,10 @@
% support for a single sequence. % support for a single sequence.
% %
:- module(fasta, [fa2atoms/2,fa2atoms/3]). :- module(fasta,
[fa2atoms/2,
fa2atoms/3
]).
fa2atoms(F, L) :- fa2atoms(F, L) :-
fa2atoms(F, L, []). fa2atoms(F, L, []).
@ -44,4 +47,3 @@ skip_header(_,S) :-
skip_header(C,S). skip_header(C,S).

View File

@ -327,4 +327,3 @@ max_index([_|L],I0,Max0,MaxIndex0,Max,MaxIndex) :-
I is I0+1, I is I0+1,
max_index(L,I,Max0,MaxIndex0,Max,MaxIndex). max_index(L,I,Max0,MaxIndex0,Max,MaxIndex).

View File

@ -9,8 +9,7 @@
[fa2atoms/3]). [fa2atoms/3]).
:- use_module(library(lists), :- use_module(library(lists),
[ [nth/3,
nth/3,
append/3 append/3
]). ]).

View File

@ -1,18 +1,14 @@
This is a version of the school database, based on the PRM School example. This is a version of the school database, based on the PRM School example.
There are four main files: There are the following main files:
school_128.yap: a school with 128 professors, 256 courses and 4096 students. school_32.yap: school with 32 professors, 64 courses and 256 students
school_64.yap: medium size school school_64.yap: school with 64 professors, 128 courses and 1024 students
school_32.yap: small school (CLP(BN)) school_128.yap: school with 128 professors, 256 courses and 4096 students
sch32.yap: small school (PFL)
parschema.pfl: the PFL schema parschema.pfl: the PFL schema
schema.yap: the CLP(BN) schema
tables: CPTs tables: CPTs
============================================================================= =============================================================================

View File

@ -1,25 +0,0 @@
/*
total_professors(32).
total_courses(64).
total_students(256).
*/
:- use_module(library(pfl)).
:- source.
:- style_check(all).
:- yap_flag(unknown,error).
:- yap_flag(write_strings,on).
:- ensure_loaded('parschema.pfl').
:- ensure_loaded(school32_data).
:- set_solver(hve).

View File

@ -1,68 +0,0 @@
/* Base file for school database. Supposed to be called from school_*.yap */
professor_key(Key) :-
professor(Key).
professor_ability(Key,Abi) :-
abi_table(Key, AbiDist),
{ Abi = ability(Key) with p([h,m,l], AbiDist) }.
professor_popularity(Key, Pop) :-
professor_ability(Key, Abi),
pop_table(Key,PopTable),
{ Pop = popularity(Key) with
p([h,m,l], PopTable,[Abi]) }.
registration_key(Key) :-
registration(Key, _, _).
registration_course(Key, CKey) :-
registration(Key, CKey, _).
registration_student(Key, SKey) :-
registration(Key, _, SKey).
registration_grade(Key, Grade) :-
registration(Key, CKey, SKey),
course_difficulty(CKey, Dif),
student_intelligence(SKey, Int),
grade_table(Int, Dif, Table),
{ Grade = grade(Key) with Table }.
% registration_satisfaction(r0, h) :- {}.
registration_satisfaction(Key, Sat) :-
registration_course(Key, CKey),
course_professor(CKey, PKey),
professor_ability(PKey, Abi),
registration_grade(Key, Grade),
satisfaction_table(Abi, Grade, Table),
{ Sat = satisfaction(Key) with Table }.
course_key(Key) :-
course(Key,_).
course_professor(Key, PKey) :-
course(Key, PKey).
course_rating(CKey, Rat) :-
setof(Sat, RKey^(registration_course(RKey,CKey), registration_satisfaction(RKey,Sat)), Sats),
{ Rat = rating(CKey) with avg([h,m,l],Sats) }.
course_difficulty(Key, Dif) :-
dif_table(Key, Dist),
{ Dif = difficulty(Key) with p([h,m,l], Dist) }.
student_key(Key) :-
student(Key).
student_intelligence(Key, Int) :-
int_table(Key, IDist, Domain),
{ Int = intelligence(Key) with p(Domain, IDist) }.
student_ranking(Key, Rank) :-
setof(Grade, CKey^(registration_student(CKey,Key),
registration_grade(CKey, Grade)), Grades),
{ Rank = ranking(Key) with avg([a,b,c,d],Grades) }.
:- ensure_loaded(tables).

File diff suppressed because it is too large Load Diff

View File

@ -4,9 +4,10 @@ total_professors(128).
total_courses(256). total_courses(256).
total_students(4096). total_students(4096).
*/ */
:- use_module(library(pfl)).
:- source. :- source.
:- style_check(all). :- style_check(all).
@ -15,9 +16,7 @@ total_students(4096).
:- yap_flag(write_strings,on). :- yap_flag(write_strings,on).
:- use_module(library(clpbn)). :- ensure_loaded('parschema.pfl').
:- [-schema].
professor(p0). professor(p0).
professor(p1). professor(p1).

File diff suppressed because it is too large Load Diff

View File

@ -4,9 +4,10 @@ total_professors(64).
total_courses(128). total_courses(128).
total_students(1024). total_students(1024).
*/ */
:- use_module(library(pfl)).
:- source. :- source.
:- style_check(all). :- style_check(all).
@ -15,9 +16,7 @@ total_students(1024).
:- yap_flag(write_strings,on). :- yap_flag(write_strings,on).
:- use_module(library(clpbn)). :- ensure_loaded('parschema.pfl').
:- [-schema].
professor(p0). professor(p0).
professor(p1). professor(p1).

View File

@ -1,33 +1,26 @@
/* CTPs for school database. */
abi_table( abi_table(
/* h */ [ 0.50, /* h */ [ 0.50,
/* m */ 0.40, /* m */ 0.40,
/* l */ 0.10 ]). /* l */ 0.10 ]).
abi_table(_, T) :- abi_table(T).
pop_table( pop_table(
/* h m l */ /* h m l */
/* h */ [ 0.9, 0.2, 0.01, /* h */ [ 0.9, 0.2, 0.01,
/* m */ 0.09, 0.6, 0.09, /* m */ 0.09, 0.6, 0.09,
/* l */ 0.01, 0.2, 0.9 ]). /* l */ 0.01, 0.2, 0.9 ]).
pop_table(_, T) :- pop_table(T).
diff_table( diff_table(
/* h */ [ 0.25, /* h */ [ 0.25,
/* m */ 0.50, /* m */ 0.50,
/* l */ 0.25 ]). /* l */ 0.25 ]).
dif_table(_, T) :- diff_table(T).
int_table( int_table(
/* h */ [ 0.5, /* h */ [ 0.5,
/* m */ 0.4, /* m */ 0.4,
/* l */ 0.1 ]). /* l */ 0.1 ]).
int_table(_,T ,[h,m,l]) :- int_table(T).
grade_table( grade_table(
/* h h h m h l m h m m m l l h l m l l */ /* h h h m h l m h m m m l l h l m l l */
/* a */ [ 0.2, 0.7, 0.85, 0.1, 0.2, 0.5, 0.01, 0.05, 0.1, /* a */ [ 0.2, 0.7, 0.85, 0.1, 0.2, 0.5, 0.01, 0.05, 0.1,
@ -35,27 +28,9 @@ grade_table(
/* c */ 0.15, 0.04, 0.02, 0.4, 0.15, 0.12, 0.5, 0.6, 0.4, /* c */ 0.15, 0.04, 0.02, 0.4, 0.15, 0.12, 0.5, 0.6, 0.4,
/* d */ 0.05, 0.01, 0.01, 0.2, 0.05, 0.03, 0.45, 0.2, 0.1 ]). /* d */ 0.05, 0.01, 0.01, 0.2, 0.05, 0.03, 0.45, 0.2, 0.1 ]).
grade_table(I, D,
p([a,b,c,d], T, [I,D])) :- grade_table(T).
sat_table( sat_table(
/* h a h b h c h d m a m b m c m d l a l b l c l d */ /* h a h b h c h d m a m b m c m d l a l b l c l d */
/* h */ [ 0.98, 0.9, 0.8 , 0.6, 0.9, 0.4, 0.2, 0.01, 0.5, 0.2, 0.01, 0.01, /* h */ [ 0.98, 0.9, 0.8 , 0.6, 0.9, 0.4, 0.2, 0.01, 0.5, 0.2, 0.01, 0.01,
/* m */ 0.01, 0.09, 0.15, 0.3, 0.05, 0.4, 0.3, 0.04, 0.35, 0.3, 0.09, 0.01, /* m */ 0.01, 0.09, 0.15, 0.3, 0.05, 0.4, 0.3, 0.04, 0.35, 0.3, 0.09, 0.01,
/* l */ 0.01, 0.01, 0.05, 0.1, 0.05, 0.2, 0.5, 0.95, 0.15, 0.5, 0.9, 0.98 ]). /* l */ 0.01, 0.01, 0.05, 0.1, 0.05, 0.2, 0.5, 0.95, 0.15, 0.5, 0.9, 0.98 ]).
satisfaction_table(A, G, p([h,m,l], T, [A,G])) :- sat_table(T).
% The idea is quite simple:
% hs = h -> r = ( 0.9, 0.1, 0)
% hs = m -> r = ( 0.2, 0.6, 0.2)
% hs = l -> r = ( 0, 0.1, 0.9)
%
% add all and divide on the number of elements on the table!
%
rating_prob_table(
[ 0.9, 0.05, 0.01,
0.09, 0.9, 0.09,
0.01, 0.05, 0.9 ]).

View File

@ -1,28 +1,26 @@
MARKOV BAYES
5 5
2 2 2 2 2 2 2 2 2 2
5 5
1 0 1 0
1 1 1 1
3 2 0 1 3 0 1 2
2 3 2 2 2 3
2 4 2 2 2 4
2 2
.001 .999 0.001 0.999
2 2
.002 .998 0.002 0.998
8 8
.95 .94 .29 .001 0.95 0.05 0.94 0.06 0.29 0.71 0.001 0.999
.05 .06 .71 .999
4 4
.9 .05 0.9 0.1 0.05 0.95
.1 .95
4 4
.7 .01 0.7 0.3 0.01 0.99
.3 .99

View File

@ -1,35 +0,0 @@
%
% adapted from Hendrik Blockeel's ILP04 paper.
%
:- use_module(library(clpbn)).
cg(X,1,C):-
father(Y,X),
cg(Y,1,C1),cg(Y,2,C2),
parent_cpt(cg(X,1), C1, C2, C).
cg(X,2,C):-
mother(Y,X),
cg(Y,1,C1),cg(Y,2,C2),
parent_cpt(cg(X,2), C1, C2, C).
cg(f,X,C) :-
prior_cpt(cg(f,X),C).
cg(m,X,C) :-
prior_cpt(cg(m,X),C).
prior_cpt(CKEY, C) :-
{ C = CKEY with p([p,w], [0.5,0.5])}.
parent_cpt(CKEY, C1, C2, C) :-
{ C = CKEY with p([p,w], [ 1,0.5,0.5,0.0,
0.0,0.5,0.5, 1],[C1,C2])}.
father(f,s).
mother(m,s).

View File

@ -1,3 +1,8 @@
/*
Model from the paper "First-order
probabilistic inference"
*/
:- use_module(library(pfl)). :- use_module(library(pfl)).
:- set_solver(hve). :- set_solver(hve).
@ -11,14 +16,14 @@
%:- set_solver(lkc). %:- set_solver(lkc).
%:- set_solver(lbp). %:- set_solver(lbp).
:- multifile people/2. :- multifile person/2.
:- multifile ev/1. :- multifile ev/1.
people(joe,nyc). person(joe,nyc).
people(p2, nyc). person(p2, nyc).
people(p3, nyc). person(p3, nyc).
people(p4, nyc). person(p4, nyc).
people(p5, nyc). person(p5, nyc).
ev(descn(p2, fits)). ev(descn(p2, fits)).
ev(descn(p3, fits)). ev(descn(p3, fits)).
@ -26,81 +31,76 @@ ev(descn(p4, fits)).
ev(descn(p5, fits)). ev(descn(p5, fits)).
bayes city_conservativeness(C)::[high,low] ; bayes city_conservativeness(C)::[high,low] ;
cons_table(C) ; cons_table ;
[people(_,C)]. [person(_,C)].
bayes gender(P)::[male,female] ; bayes gender(P)::[male,female] ;
gender_table(P) ; gender_table ;
[people(P,_)]. [person(P,_)].
bayes hair_color(P)::[dark,bright], city_conservativeness(C) ; bayes hair_color(P)::[dark,bright], city_conservativeness(C) ;
hair_color_table(P) ; hair_color_table ;
[people(P,C)]. [person(P,C)].
bayes car_color(P)::[dark,bright], hair_color(P) ; bayes car_color(P)::[dark,bright], hair_color(P) ;
car_color_table(P) ; car_color_table ;
[people(P,_)]. [person(P,_)].
bayes height(P)::[tall,short], gender(P) ; bayes height(P)::[tall,short], gender(P) ;
height_table(P) ; height_table ;
[people(P,_)]. [person(P,_)].
bayes shoe_size(P)::[big,small], height(P) ; bayes shoe_size(P)::[big,small], height(P) ;
shoe_size_table(P) ; shoe_size_table ;
[people(P,_)]. [person(P,_)].
bayes guilty(P)::[y,n] ; bayes guilty(P)::[y,n] ;
guilty_table(P) ; guilty_table ;
[people(P,_)]. [person(P,_)].
bayes descn(P)::[fits,dont_fit], car_color(P), bayes descn(P)::[fits,dont_fit], car_color(P),
hair_color(P), height(P), guilty(P) ; hair_color(P), height(P), guilty(P) ;
descn_table(P) ; descn_table ;
[people(P,_)]. [person(P,_)].
bayes witness(C), descn(Joe), descn(P2) ; bayes witness(C), descn(Joe), descn(P2) ;
witness_table ; witness_table ;
[people(_,C), Joe=joe, P2=p2]. [person(_,C), Joe=joe, P2=p2].
cons_table(amsterdam, cons_table(
% special case for amsterdam: amsterdam is
% less conservative than other cities (is it?)
/* y */ [ 0.2,
/* n */ 0.8 ]) :- !. % FIXME
cons_table(_,
/* y */ [ 0.8, /* y */ [ 0.8,
/* n */ 0.2 ]). /* n */ 0.2 ]).
gender_table(_, gender_table(
/* male */ [ 0.55, /* male */ [ 0.55,
/* female */ 0.45 ]). /* female */ 0.45 ]).
hair_color_table(_, hair_color_table(
/* high low */ /* high low */
/* dark */ [ 0.05, 0.1, /* dark */ [ 0.05, 0.1,
/* bright */ 0.95, 0.9 ]). /* bright */ 0.95, 0.9 ]).
car_color_table(_, car_color_table(
/* dark bright */ /* dark bright */
/* dark */ [ 0.9, 0.2, /* dark */ [ 0.9, 0.2,
/* bright */ 0.1, 0.8 ]). /* bright */ 0.1, 0.8 ]).
height_table(_, height_table(
/* male female */ /* male female */
/* tall */ [ 0.6, 0.4, /* tall */ [ 0.6, 0.4,
/* short */ 0.4, 0.6 ]). /* short */ 0.4, 0.6 ]).
shoe_size_table(_, shoe_size_table(
/* tall short */ /* tall short */
/* big */ [ 0.9, 0.1, /* big */ [ 0.9, 0.1,
/* small */ 0.1, 0.9 ]). /* small */ 0.1, 0.9 ]).
guilty_table(_, guilty_table(
/* yes */ [ 0.23, /* yes */ [ 0.23,
/* no */ 0.77 ]). /* no */ 0.77 ]).
descn_table(_, descn_table(
/* car_color(P), hair_color(P), height(P), guilty(P) */ /* car_color(P), hair_color(P), height(P), guilty(P) */
/* fits */ [ 0.99, 0.5, 0.23, 0.88, 0.41, 0.3, 0.76, 0.87, /* fits */ [ 0.99, 0.5, 0.23, 0.88, 0.41, 0.3, 0.76, 0.87,
/* fits */ 0.44, 0.43, 0.29, 0.72, 0.23, 0.91, 0.95, 0.92, /* fits */ 0.44, 0.43, 0.29, 0.72, 0.23, 0.91, 0.95, 0.92,

View File

@ -1,3 +1,8 @@
/*
Model from the paper "Lifted Probabilistic
Inference with Counting Formulas"
*/
:- use_module(library(pfl)). :- use_module(library(pfl)).
:- set_solver(hve). :- set_solver(hve).
@ -10,31 +15,31 @@
%:- set_solver(lkc). %:- set_solver(lkc).
%:- set_solver(lbp). %:- set_solver(lbp).
:- multifile c/2. :- multifile reg/2.
c(p1,w1). reg(p1,w1).
c(p1,w2). reg(p1,w2).
c(p1,w3). reg(p1,w3).
c(p2,w1). reg(p2,w1).
c(p2,w2). reg(p2,w2).
c(p2,w3). reg(p2,w3).
c(p3,w1). reg(p3,w1).
c(p3,w2). reg(p3,w2).
c(p3,w3). reg(p3,w3).
c(p4,w1). reg(p4,w1).
c(p4,w2). reg(p4,w2).
c(p4,w3). reg(p4,w3).
c(p5,w1). reg(p5,w1).
c(p5,w2). reg(p5,w2).
c(p5,w3). reg(p5,w3).
markov attends(P), hot(W) ; markov attends(P), hot(W) ;
[0.2, 0.8, 0.8, 0.8] ; [0.2, 0.8, 0.8, 0.8] ;
[c(P,W)]. [reg(P,W)].
markov attends(P), series ; markov attends(P), series ;
[0.501, 0.499, 0.499, 0.499] ; [0.501, 0.499, 0.499, 0.499] ;
[c(P,_)]. [reg(P,_)].
?- series(X). % ?- series(X).

View File

@ -2,16 +2,17 @@
/* We do not consider aggregates yet. */ /* We do not consider aggregates yet. */
:- [pos:train].
:- ['../../examples/School/sch32'].
:- use_module(library(clpbn/learning/em)). :- use_module(library(clpbn/learning/em)).
%:- clpbn:set_clpbn_flag(em_solver,gibbs). :- [pos:train].
%:- clpbn:set_clpbn_flag(em_solver,jt).
:- clpbn:set_clpbn_flag(em_solver,ve). :- ['../../examples/School/parschema.pfl'].
%:- clpbn:set_clpbn_flag(em_solver,bp).
:- set_em_solver(ve).
%:- set_em_solver(hve).
%:- set_em_solver(bdd).
%:- set_em_solver(bp).
%:- set_em_solver(cbp).
debug_school :- debug_school :-
graph(L), graph(L),

View File

@ -4,12 +4,11 @@
:- use_module(library(clpbn/learning/em)). :- use_module(library(clpbn/learning/em)).
%:- clpbn:set_clpbn_flag(em_solver,gibbs). :- set_em_solver(ve).
%:- clpbn:set_clpbn_flag(em_solver,jt). %:- set_em_solver(hve).
%:- clpbn:set_clpbn_flag(em_solver,hve). %:- set_em_solver(bdd).
:- clpbn:set_clpbn_flag(em_solver,ve). %:- set_em_solver(bp).
%:- clpbn:set_clpbn_flag(em_solver,bp). %:- set_em_solver(cbp).
%:- clpbn:set_clpbn_flag(em_solver,bdd).
professor(p0). professor(p0).
professor(p1). professor(p1).

View File

@ -2,16 +2,17 @@
/* We do not consider aggregates yet. */ /* We do not consider aggregates yet. */
:- [pos:train].
:- ['../../examples/School/sch32'].
:- use_module(library(clpbn/learning/em)). :- use_module(library(clpbn/learning/em)).
%:- clpbn:set_clpbn_flag(em_solver,gibbs). :- [pos:train].
%:- clpbn:set_clpbn_flag(em_solver,jt).
:- clpbn:set_clpbn_flag(em_solver,ve). :- ['../../examples/School/school_32'].
%:- clpbn:set_clpbn_flag(em_solver,bp).
:- set_em_solver(ve).
%:- set_em_solver(hve).
%:- set_em_solver(bdd).
%:- set_em_solver(bp).
%:- set_em_solver(cbp).
timed_main :- timed_main :-
statistics(runtime, _), statistics(runtime, _),

View File

@ -4,12 +4,11 @@
:- use_module(library(clpbn/learning/em)). :- use_module(library(clpbn/learning/em)).
%:- set_pfl_flag(em_solver,gibbs). :- set_em_solver(ve).
%:- set_pfl_flag(em_solver,jt). %:- set_em_solver(hve).
%:- set_pfl_flag(em_solver,hve). %:- set_em_solver(bdd).
%:- set_pfl_flag(em_solver,bp). %:- set_em_solver(bp).
%:- set_pfl_flag(em_solver,ve). %:- set_em_solver(cbp).
:- set_pfl_flag(em_solver,bdd).
:- dynamic id/1. :- dynamic id/1.

View File

@ -1,38 +0,0 @@
:- use_module(library(pfl)).
:- set_solver(hve).
%:- set_solver(ve).
%:- set_solver(jt).
%:- set_solver(bdd).
%:- set_solver(bp).
%:- set_solver(cbp).
%:- set_solver(gibbs).
%:- set_solver(lve).
%:- set_solver(lkc).
%:- set_solver(lbp).
:- multifile people/1.
people @ 5.
people(X,Y) :-
people(X),
people(Y),
X \== Y.
markov smokes(X) ; [1.0, 4.0552]; [people(X)].
markov cancer(X) ; [1.0, 9.9742]; [people(X)].
markov friends(X,Y) ; [1.0, 99.48432] ; [people(X,Y)].
markov smokes(X), cancer(X) ;
[4.48169, 4.48169, 1.0, 4.48169] ;
[people(X)].
markov friends(X,Y), smokes(X), smokes(Y) ;
[3.004166, 3.004166, 3.004166, 3.004166, 3.004166, 1.0, 1.0, 3.004166] ;
[people(X,Y)].
% ?- friends(p1,p2,X).

View File

@ -1,38 +0,0 @@
:- use_module(library(pfl)).
:- set_solver(hve).
%:- set_solver(ve).
%:- set_solver(jt).
%:- set_solver(bdd).
%:- set_solver(bp).
%:- set_solver(cbp).
%:- set_solver(gibbs).
%:- set_solver(lve).
%:- set_solver(lkc).
%:- set_solver(lbp).
:- multifile people/1.
people @ 5.
people(X,Y) :-
people(X),
people(Y).
% X \== Y.
markov smokes(X) ; [1.0, 4.0552]; [people(X)].
markov asthma(X) ; [1.0, 9.9742] ; [people(X)].
markov friends(X,Y) ; [1.0, 99.48432] ; [people(X,Y)].
markov asthma(X), smokes(X) ;
[4.48169, 4.48169, 1.0, 4.48169] ;
[people(X)].
markov asthma(X), friends(X,Y), smokes(Y) ;
[3.004166, 3.004166, 3.004166, 3.004166, 3.004166, 1.0, 1.0, 3.004166] ;
[people(X,Y)].
% ?- smokes(p1,t), smokes(p2,t), friends(p1,p2,X).

View File

@ -0,0 +1,44 @@
/*
Model from the paper "Lifted First-Order
Belief Propagation"
*/
:- use_module(library(pfl)).
:- set_solver(hve).
%:- set_solver(ve).
%:- set_solver(jt).
%:- set_solver(bdd).
%:- set_solver(bp).
%:- set_solver(cbp).
%:- set_solver(gibbs).
%:- set_solver(lve).
%:- set_solver(lkc).
%:- set_solver(lbp).
:- multifile person/1.
person @ 5.
person(X,Y) :-
person(X),
person(Y)
% ,X \== Y
.
markov smokes(X) ; [1.0, 4.0552]; [person(X)].
markov cancer(X) ; [1.0, 9.9742]; [person(X)].
markov friends(X,Y) ; [1.0, 99.48432] ; [person(X,Y)].
markov smokes(X), cancer(X) ;
[4.48169, 4.48169, 1.0, 4.48169] ;
[person(X)].
markov friends(X,Y), smokes(X), smokes(Y) ;
[3.004166, 3.004166, 3.004166, 3.004166, 3.004166, 1.0, 1.0, 3.004166] ;
[person(X,Y)].
% ?- friends(p1,p2,X).

View File

@ -0,0 +1,44 @@
/*
Model from the paper "Lifted Inference Seen
from the Other Side: The Tractable Features"
*/
:- use_module(library(pfl)).
:- set_solver(hve).
%:- set_solver(ve).
%:- set_solver(jt).
%:- set_solver(bdd).
%:- set_solver(bp).
%:- set_solver(cbp).
%:- set_solver(gibbs).
%:- set_solver(lve).
%:- set_solver(lkc).
%:- set_solver(lbp).
:- multifile person/1.
person @ 5.
person(X,Y) :-
person(X),
person(Y)
% ,X \== Y
.
markov smokes(X) ; [1.0, 4.0552]; [person(X)].
markov asthma(X) ; [1.0, 9.9742] ; [person(X)].
markov friends(X,Y) ; [1.0, 99.48432] ; [person(X,Y)].
markov asthma(X), smokes(X) ;
[4.48169, 4.48169, 1.0, 4.48169] ;
[person(X)].
markov asthma(X), friends(X,Y), smokes(Y) ;
[3.004166, 3.004166, 3.004166, 3.004166, 3.004166, 1.0, 1.0, 3.004166] ;
[person(X,Y)].
% ?- smokes(p1,t), smokes(p2,t), friends(p1,p2,X).

View File

@ -24,16 +24,16 @@ cloudy_table(
0.5 ]). 0.5 ]).
sprinkler_table( sprinkler_table(
[ 0.5, 0.9, [ 0.1, 0.5,
0.5, 0.1 ]). 0.9, 0.5 ]).
rain_table( rain_table(
[ 0.8, 0.2, [ 0.8, 0.2,
0.2, 0.8 ]). 0.2, 0.8 ]).
wet_grass_table( wet_grass_table(
[ 1.0, 0.1, 0.1, 0.01, [ 0.99, 0.9, 0.9, 0.0,
0.0, 0.9, 0.9, 0.99 ]). 0.01, 0.1, 0.1, 1.0 ]).
% ?- wet_grass(X). % ?- wet_grass(X).

View File

@ -1,3 +1,8 @@
/*
Model from the paper "Lifted Probabilistic
Inference with Counting Formulas"
*/
:- use_module(library(pfl)). :- use_module(library(pfl)).
:- set_solver(hve). :- set_solver(hve).
@ -11,23 +16,23 @@
%:- set_solver(lkc). %:- set_solver(lkc).
%:- set_solver(lbp). %:- set_solver(lbp).
:- multifile people/1. :- multifile person/1.
people @ 5. person @ 5.
markov attends(P), attr1 ; [0.7, 0.3, 0.3, 0.3] ; [people(P)]. markov attends(P), attr1 ; [0.7, 0.3, 0.3, 0.3] ; [person(P)].
markov attends(P), attr2 ; [0.7, 0.3, 0.3, 0.3] ; [people(P)]. markov attends(P), attr2 ; [0.7, 0.3, 0.3, 0.3] ; [person(P)].
markov attends(P), attr3 ; [0.7, 0.3, 0.3, 0.3] ; [people(P)]. markov attends(P), attr3 ; [0.7, 0.3, 0.3, 0.3] ; [person(P)].
markov attends(P), attr4 ; [0.7, 0.3, 0.3, 0.3] ; [people(P)]. markov attends(P), attr4 ; [0.7, 0.3, 0.3, 0.3] ; [person(P)].
markov attends(P), attr5 ; [0.7, 0.3, 0.3, 0.3] ; [people(P)]. markov attends(P), attr5 ; [0.7, 0.3, 0.3, 0.3] ; [person(P)].
markov attends(P), attr6 ; [0.7, 0.3, 0.3, 0.3] ; [people(P)]. markov attends(P), attr6 ; [0.7, 0.3, 0.3, 0.3] ; [person(P)].
markov attends(P), series ; [0.501, 0.499, 0.499, 0.499] ; [people(P)]. markov attends(P), series ; [0.501, 0.499, 0.499, 0.499] ; [person(P)].
% ?- series(X). % ?- series(X).

View File

@ -1,12 +1,6 @@
#include <cstdlib>
#include <cassert> #include <cassert>
#include <iostream>
#include <fstream>
#include <sstream>
#include "BayesBall.h" #include "BayesBall.h"
#include "Util.h"
FactorGraph* FactorGraph*

View File

@ -4,7 +4,6 @@
#include <vector> #include <vector>
#include <queue> #include <queue>
#include <list> #include <list>
#include <map>
#include "FactorGraph.h" #include "FactorGraph.h"
#include "BayesBallGraph.h" #include "BayesBallGraph.h"
@ -15,8 +14,8 @@ using namespace std;
struct ScheduleInfo struct ScheduleInfo
{ {
ScheduleInfo (BBNode* n, bool vfp, bool vfc) : ScheduleInfo (BBNode* n, bool vfp, bool vfc)
node(n), visitedFromParent(vfp), visitedFromChild(vfc) { } : node(n), visitedFromParent(vfp), visitedFromChild(vfc) { }
BBNode* node; BBNode* node;
bool visitedFromParent; bool visitedFromParent;

View File

@ -2,8 +2,8 @@
#include <cassert> #include <cassert>
#include <iostream> #include <iostream>
#include <fstream>
#include <sstream> #include <sstream>
#include <fstream>
#include "BayesBallGraph.h" #include "BayesBallGraph.h"
#include "Util.h" #include "Util.h"
@ -79,9 +79,8 @@ BayesBallGraph::exportToGraphViz (const char* fileName)
{ {
ofstream out (fileName); ofstream out (fileName);
if (!out.is_open()) { if (!out.is_open()) {
cerr << "error: cannot open file to write at " ; cerr << "Error: couldn't open file '" << fileName << "'." ;
cerr << "BayesBallGraph::exportToDotFile()" << endl; return;
abort();
} }
out << "digraph {" << endl; out << "digraph {" << endl;
out << "ranksep=1" << endl; out << "ranksep=1" << endl;

View File

@ -2,9 +2,7 @@
#define HORUS_BAYESBALLGRAPH_H #define HORUS_BAYESBALLGRAPH_H
#include <vector> #include <vector>
#include <queue> #include <unordered_map>
#include <list>
#include <map>
#include "Var.h" #include "Var.h"
#include "Horus.h" #include "Horus.h"

View File

@ -1,17 +1,19 @@
#include <cassert> #include <cassert>
#include <limits>
#include <algorithm> #include <algorithm>
#include <iostream> #include <iostream>
#include "BeliefProp.h" #include "BeliefProp.h"
#include "FactorGraph.h"
#include "Factor.h"
#include "Indexer.h" #include "Indexer.h"
#include "Horus.h" #include "Horus.h"
double BeliefProp::accuracy_ = 0.0001;
unsigned BeliefProp::maxIter_ = 1000;
MsgSchedule BeliefProp::schedule_ = MsgSchedule::SEQ_FIXED;
BeliefProp::BeliefProp (const FactorGraph& fg) : GroundSolver (fg) BeliefProp::BeliefProp (const FactorGraph& fg) : GroundSolver (fg)
{ {
runned_ = false; runned_ = false;
@ -50,16 +52,15 @@ BeliefProp::printSolverFlags (void) const
{ {
stringstream ss; stringstream ss;
ss << "belief propagation [" ; ss << "belief propagation [" ;
ss << "schedule=" ; ss << "bp_msg_schedule=" ;
typedef BpOptions::Schedule Sch; switch (schedule_) {
switch (BpOptions::schedule) { case MsgSchedule::SEQ_FIXED: ss << "seq_fixed"; break;
case Sch::SEQ_FIXED: ss << "seq_fixed"; break; case MsgSchedule::SEQ_RANDOM: ss << "seq_random"; break;
case Sch::SEQ_RANDOM: ss << "seq_random"; break; case MsgSchedule::PARALLEL: ss << "parallel"; break;
case Sch::PARALLEL: ss << "parallel"; break; case MsgSchedule::MAX_RESIDUAL: ss << "max_residual"; break;
case Sch::MAX_RESIDUAL: ss << "max_residual"; break;
} }
ss << ",max_iter=" << Util::toString (BpOptions::maxIter); ss << ",bp_max_iter=" << Util::toString (maxIter_);
ss << ",accuracy=" << Util::toString (BpOptions::accuracy); ss << ",bp_accuracy=" << Util::toString (accuracy_);
ss << ",log_domain=" << Util::toString (Globals::logDomain); ss << ",log_domain=" << Util::toString (Globals::logDomain);
ss << "]" ; ss << "]" ;
cout << ss.str() << endl; cout << ss.str() << endl;
@ -156,21 +157,21 @@ BeliefProp::runSolver (void)
{ {
initializeSolver(); initializeSolver();
nIters_ = 0; nIters_ = 0;
while (!converged() && nIters_ < BpOptions::maxIter) { while (!converged() && nIters_ < maxIter_) {
nIters_ ++; nIters_ ++;
if (Globals::verbosity > 1) { if (Globals::verbosity > 1) {
Util::printHeader (string ("Iteration ") + Util::toString (nIters_)); Util::printHeader (string ("Iteration ") + Util::toString (nIters_));
} }
switch (BpOptions::schedule) { switch (schedule_) {
case BpOptions::Schedule::SEQ_RANDOM: case MsgSchedule::SEQ_RANDOM:
std::random_shuffle (links_.begin(), links_.end()); std::random_shuffle (links_.begin(), links_.end());
// no break // no break
case BpOptions::Schedule::SEQ_FIXED: case MsgSchedule::SEQ_FIXED:
for (size_t i = 0; i < links_.size(); i++) { for (size_t i = 0; i < links_.size(); i++) {
calculateAndUpdateMessage (links_[i]); calculateAndUpdateMessage (links_[i]);
} }
break; break;
case BpOptions::Schedule::PARALLEL: case MsgSchedule::PARALLEL:
for (size_t i = 0; i < links_.size(); i++) { for (size_t i = 0; i < links_.size(); i++) {
calculateMessage (links_[i]); calculateMessage (links_[i]);
} }
@ -178,13 +179,13 @@ BeliefProp::runSolver (void)
updateMessage(links_[i]); updateMessage(links_[i]);
} }
break; break;
case BpOptions::Schedule::MAX_RESIDUAL: case MsgSchedule::MAX_RESIDUAL:
maxResidualSchedule(); maxResidualSchedule();
break; break;
} }
} }
if (Globals::verbosity > 0) { if (Globals::verbosity > 0) {
if (nIters_ < BpOptions::maxIter) { if (nIters_ < maxIter_) {
cout << "Belief propagation converged in " ; cout << "Belief propagation converged in " ;
cout << nIters_ << " iterations" << endl; cout << nIters_ << " iterations" << endl;
} else { } else {
@ -236,7 +237,7 @@ BeliefProp::maxResidualSchedule (void)
SortedOrder::iterator it = sortedOrder_.begin(); SortedOrder::iterator it = sortedOrder_.begin();
BpLink* link = *it; BpLink* link = *it;
if (link->residual() < BpOptions::accuracy) { if (link->residual() < accuracy_) {
return; return;
} }
updateMessage (link); updateMessage (link);
@ -410,7 +411,7 @@ BeliefProp::initializeSolver (void)
bool bool
BeliefProp::converged (void) BeliefProp::converged (void)
{ {
if (links_.size() == 0) { if (links_.empty()) {
return true; return true;
} }
if (nIters_ == 0) { if (nIters_ == 0) {
@ -426,9 +427,9 @@ BeliefProp::converged (void)
return false; return false;
} }
bool converged = true; bool converged = true;
if (BpOptions::schedule == BpOptions::Schedule::MAX_RESIDUAL) { if (schedule_ == MsgSchedule::MAX_RESIDUAL) {
double maxResidual = (*(sortedOrder_.begin()))->residual(); double maxResidual = (*(sortedOrder_.begin()))->residual();
if (maxResidual > BpOptions::accuracy) { if (maxResidual > accuracy_) {
converged = false; converged = false;
} else { } else {
converged = true; converged = true;
@ -439,7 +440,7 @@ BeliefProp::converged (void)
if (Globals::verbosity > 1) { if (Globals::verbosity > 1) {
cout << links_[i]->toString() + " residual = " << residual << endl; cout << links_[i]->toString() + " residual = " << residual << endl;
} }
if (residual > BpOptions::accuracy) { if (residual > accuracy_) {
converged = false; converged = false;
if (Globals::verbosity < 2) { if (Globals::verbosity < 2) {
break; break;

View File

@ -3,16 +3,24 @@
#include <set> #include <set>
#include <vector> #include <vector>
#include <sstream> #include <sstream>
#include "GroundSolver.h" #include "GroundSolver.h"
#include "Factor.h"
#include "FactorGraph.h" #include "FactorGraph.h"
#include "Util.h"
using namespace std; using namespace std;
enum MsgSchedule {
SEQ_FIXED,
SEQ_RANDOM,
PARALLEL,
MAX_RESIDUAL
};
class BpLink class BpLink
{ {
public: public:
@ -68,6 +76,9 @@ class BpLink
Params* currMsg_; Params* currMsg_;
Params* nextMsg_; Params* nextMsg_;
double residual_; double residual_;
private:
DISALLOW_COPY_AND_ASSIGN (BpLink);
}; };
typedef vector<BpLink*> BpLinks; typedef vector<BpLink*> BpLinks;
@ -76,10 +87,12 @@ typedef vector<BpLink*> BpLinks;
class SPNodeInfo class SPNodeInfo
{ {
public: public:
SPNodeInfo (void) { }
void addBpLink (BpLink* link) { links_.push_back (link); } void addBpLink (BpLink* link) { links_.push_back (link); }
const BpLinks& getLinks (void) { return links_; } const BpLinks& getLinks (void) { return links_; }
private: private:
BpLinks links_; BpLinks links_;
DISALLOW_COPY_AND_ASSIGN (SPNodeInfo);
}; };
@ -98,22 +111,20 @@ class BeliefProp : public GroundSolver
virtual Params getJointDistributionOf (const VarIds&); virtual Params getJointDistributionOf (const VarIds&);
protected:
void runSolver (void);
virtual void createLinks (void);
virtual void maxResidualSchedule (void);
virtual void calcFactorToVarMsg (BpLink*);
virtual Params getVarToFactorMsg (const BpLink*) const;
virtual Params getJointByConditioning (const VarIds&) const;
public:
Params getFactorJoint (FacNode* fn, const VarIds&); Params getFactorJoint (FacNode* fn, const VarIds&);
static double accuracy (void) { return accuracy_; }
static void setAccuracy (double acc) { accuracy_ = acc; }
static unsigned maxIterations (void) { return maxIter_; }
static void setMaxIterations (unsigned mi) { maxIter_ = mi; }
static MsgSchedule msgSchedule (void) { return schedule_; }
static void setMsgSchedule (MsgSchedule sch) { schedule_ = sch; }
protected: protected:
SPNodeInfo* ninf (const VarNode* var) const SPNodeInfo* ninf (const VarNode* var) const
{ {
@ -164,6 +175,18 @@ class BeliefProp : public GroundSolver
} }
}; };
void runSolver (void);
virtual void createLinks (void);
virtual void maxResidualSchedule (void);
virtual void calcFactorToVarMsg (BpLink*);
virtual Params getVarToFactorMsg (const BpLink*) const;
virtual Params getJointByConditioning (const VarIds&) const;
BpLinks links_; BpLinks links_;
unsigned nIters_; unsigned nIters_;
vector<SPNodeInfo*> varsI_; vector<SPNodeInfo*> varsI_;
@ -176,12 +199,18 @@ class BeliefProp : public GroundSolver
typedef unordered_map<BpLink*, SortedOrder::iterator> BpLinkMap; typedef unordered_map<BpLink*, SortedOrder::iterator> BpLinkMap;
BpLinkMap linkMap_; BpLinkMap linkMap_;
static double accuracy_;
static unsigned maxIter_;
static MsgSchedule schedule_;
private: private:
void initializeSolver (void); void initializeSolver (void);
bool converged (void); bool converged (void);
virtual void printLinkInformation (void) const; virtual void printLinkInformation (void) const;
DISALLOW_COPY_AND_ASSIGN (BeliefProp);
}; };
#endif // HORUS_BELIEFPROP_H #endif // HORUS_BELIEFPROP_H

View File

@ -120,7 +120,7 @@ CTNode::copySubtree (const CTNode* root1)
chIt != n1->childs().end(); ++ chIt) { chIt != n1->childs().end(); ++ chIt) {
CTNode* chCopy = new CTNode (**chIt); CTNode* chCopy = new CTNode (**chIt);
n2->childs().insert_sorted (chCopy); n2->childs().insert_sorted (chCopy);
if ((*chIt)->nrChilds() != 0) { if ((*chIt)->nrChilds() > 0) {
stack.push_back (StackPair (*chIt, chCopy)); stack.push_back (StackPair (*chIt, chCopy));
} }
} }
@ -521,13 +521,12 @@ ConstraintTree::exportToGraphViz (
{ {
ofstream out (fileName); ofstream out (fileName);
if (!out.is_open()) { if (!out.is_open()) {
cerr << "error: cannot open file to write at " ; cerr << "Error: couldn't open file '" << fileName << "'." ;
cerr << "ConstraintTree::exportToDotFile()" << endl; return;
abort();
} }
out << "digraph {" << endl; out << "digraph {" << endl;
ConstraintTree copy (*this); ConstraintTree copy (*this);
// copy.moveToTop (copy.logVarSet_.elements()); copy.moveToTop (copy.logVarSet_.elements());
CTNodes nodes = getNodesBelow (copy.root_); CTNodes nodes = getNodesBelow (copy.root_);
out << "\"" << copy.root_ << "\"" << " [label=\"R\"]" << endl; out << "\"" << copy.root_ << "\"" << " [label=\"R\"]" << endl;
for (CTNodes::const_iterator it = ++ nodes.begin(); for (CTNodes::const_iterator it = ++ nodes.begin();
@ -814,10 +813,10 @@ ConstraintTree::jointCountNormalize (
cts[i]->join (exclCt); cts[i]->join (exclCt);
} }
if (excl1 != 0) { if (excl1) {
cts.push_back (excl1); cts.push_back (excl1);
} }
if (excl2 != 0) { if (excl2) {
cts.push_back (excl2); cts.push_back (excl2);
} }
@ -883,7 +882,7 @@ ConstraintTree::ground (LogVar X)
void void
ConstraintTree::copyLogVar (LogVar X_1, LogVar X_2) ConstraintTree::cloneLogVar (LogVar X_1, LogVar X_2)
{ {
moveToBottom ({X_1}); moveToBottom ({X_1});
CTNodes leafs = getNodesAtLevel (logVars_.size()); CTNodes leafs = getNodesAtLevel (logVars_.size());
@ -1073,7 +1072,7 @@ ConstraintTree::getTuples (
CTNodes& continuationNodes) const CTNodes& continuationNodes) const
{ {
if (n->isRoot() == false) { if (n->isRoot() == false) {
if (currTuples.size() == 0) { if (currTuples.empty()) {
currTuples.push_back ({ n->symbol()}); currTuples.push_back ({ n->symbol()});
} else { } else {
for (size_t i = 0; i < currTuples.size(); i++) { for (size_t i = 0; i < currTuples.size(); i++) {

View File

@ -23,7 +23,6 @@ typedef vector<ConstraintTree*> ConstraintTrees;
class CTNode class CTNode
{ {
public: public:
struct CompareSymbol struct CompareSymbol
{ {
bool operator() (const CTNode* n1, const CTNode* n2) const bool operator() (const CTNode* n1, const CTNode* n2) const
@ -33,11 +32,9 @@ class CTNode
}; };
private: private:
typedef TinySet<CTNode*, CompareSymbol> CTChilds_; typedef TinySet<CTNode*, CompareSymbol> CTChilds_;
public: public:
CTNode (const CTNode& n, const CTChilds_& chs = CTChilds_()) CTNode (const CTNode& n, const CTChilds_& chs = CTChilds_())
: symbol_(n.symbol()), childs_(chs), level_(n.level()) { } : symbol_(n.symbol()), childs_(chs), level_(n.level()) { }
@ -52,8 +49,6 @@ class CTNode
void setSymbol (const Symbol s) { symbol_ = s; } void setSymbol (const Symbol s) { symbol_ = s; }
public:
CTChilds_& childs (void) { return childs_; } CTChilds_& childs (void) { return childs_; }
const CTChilds_& childs (void) const { return childs_; } const CTChilds_& childs (void) const { return childs_; }
@ -92,6 +87,8 @@ class CTNode
Symbol symbol_; Symbol symbol_;
CTChilds_ childs_; CTChilds_ childs_;
unsigned level_; unsigned level_;
DISALLOW_ASSIGN (CTNode);
}; };
ostream& operator<< (ostream &out, const CTNode&); ostream& operator<< (ostream &out, const CTNode&);
@ -200,7 +197,7 @@ class ConstraintTree
ConstraintTrees ground (LogVar); ConstraintTrees ground (LogVar);
void copyLogVar (LogVar,LogVar); void cloneLogVar (LogVar, LogVar);
ConstraintTree& operator= (const ConstraintTree& ct); ConstraintTree& operator= (const ConstraintTree& ct);

View File

@ -2,7 +2,7 @@
#include "WeightedBp.h" #include "WeightedBp.h"
bool CountingBp::checkForIdenticalFactors = true; bool CountingBp::fif_ = true;
CountingBp::CountingBp (const FactorGraph& fg) CountingBp::CountingBp (const FactorGraph& fg)
@ -36,19 +36,17 @@ CountingBp::printSolverFlags (void) const
{ {
stringstream ss; stringstream ss;
ss << "counting bp [" ; ss << "counting bp [" ;
ss << "schedule=" ; ss << "bp_msg_schedule=" ;
typedef BpOptions::Schedule Sch; switch (WeightedBp::msgSchedule()) {
switch (BpOptions::schedule) { case MsgSchedule::SEQ_FIXED: ss << "seq_fixed"; break;
case Sch::SEQ_FIXED: ss << "seq_fixed"; break; case MsgSchedule::SEQ_RANDOM: ss << "seq_random"; break;
case Sch::SEQ_RANDOM: ss << "seq_random"; break; case MsgSchedule::PARALLEL: ss << "parallel"; break;
case Sch::PARALLEL: ss << "parallel"; break; case MsgSchedule::MAX_RESIDUAL: ss << "max_residual"; break;
case Sch::MAX_RESIDUAL: ss << "max_residual"; break;
} }
ss << ",max_iter=" << BpOptions::maxIter; ss << ",bp_max_iter=" << WeightedBp::maxIterations();
ss << ",accuracy=" << BpOptions::accuracy; ss << ",bp_accuracy=" << WeightedBp::accuracy();
ss << ",log_domain=" << Util::toString (Globals::logDomain); ss << ",log_domain=" << Util::toString (Globals::logDomain);
ss << ",chkif=" << ss << ",fif=" << Util::toString (CountingBp::fif_);
Util::toString (CountingBp::checkForIdenticalFactors);
ss << "]" ; ss << "]" ;
cout << ss.str() << endl; cout << ss.str() << endl;
} }
@ -82,7 +80,7 @@ CountingBp::solveQuery (VarIds queryVids)
reprArgs.push_back (getRepresentative (queryVids[i])); reprArgs.push_back (getRepresentative (queryVids[i]));
} }
FacNode* reprFac = getRepresentative (facNodes[idx]); FacNode* reprFac = getRepresentative (facNodes[idx]);
assert (reprFac != 0); assert (reprFac);
res = solver_->getFactorJoint (reprFac, reprArgs); res = solver_->getFactorJoint (reprFac, reprArgs);
} }
} }
@ -95,8 +93,7 @@ void
CountingBp::findIdenticalFactors() CountingBp::findIdenticalFactors()
{ {
const FacNodes& facNodes = fg.facNodes(); const FacNodes& facNodes = fg.facNodes();
if (checkForIdenticalFactors == false || if (fif_ == false || facNodes.size() == 1) {
facNodes.size() == 1) {
return; return;
} }
for (size_t i = 0; i < facNodes.size(); i++) { for (size_t i = 0; i < facNodes.size(); i++) {

Some files were not shown because too many files have changed in this diff Show More