Merge branch 'master' of github.com:tacgomes/yap6.3

This commit is contained in:
Tiago Gomes 2013-01-09 11:12:41 +00:00
commit 91e8bcd4d7
122 changed files with 5089 additions and 4518 deletions

View File

@ -108,7 +108,7 @@ typedef struct regstore_t
yamop *CP_; /* 28 continuation program counter */
CELL *ENV_; /* 1 current environment */
#ifdef CUT_C
cut_c_str_ptr CUT_C_TOP;
struct cut_c_str *CUT_C_TOP;
#endif
#if defined CUT_C && (defined MYDDAS_ODBC || defined MYDDAS_MYSQL)
MYDDAS_GLOBAL MYDDAS_GLOBAL_POINTER;

View File

@ -50,7 +50,7 @@ DOCSDIR=$(SHAREDIR)/doc/Yap
#
# check also optimisation options in INSTALL file.
#
YAP_EXTRAS=-DCUT_C=1 @YAP_EXTRAS@
YAP_EXTRAS=@YAP_EXTRAS@
YAPSTARTUP=startup.yss

228
configure vendored
View File

@ -1,9 +1,11 @@
#! /bin/sh
# Guess values for system-dependent variables and create Makefiles.
# Generated by GNU Autoconf 2.69.
# Generated by GNU Autoconf 2.68.
#
#
# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
# Foundation, Inc.
#
#
# This configure script is free software; the Free Software Foundation
@ -132,31 +134,6 @@ export LANGUAGE
# CDPATH.
(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
# Use a proper internal environment variable to ensure we don't fall
# into an infinite loop, continuously re-executing ourselves.
if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
_as_can_reexec=no; export _as_can_reexec;
# We cannot yet assume a decent shell, so we have to provide a
# neutralization value for shells without unset; and this also
# works around shells that cannot unset nonexistent variables.
# Preserve -v and -x to the replacement shell.
BASH_ENV=/dev/null
ENV=/dev/null
(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
case $- in # ((((
*v*x* | *x*v* ) as_opts=-vx ;;
*v* ) as_opts=-v ;;
*x* ) as_opts=-x ;;
* ) as_opts= ;;
esac
exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
# Admittedly, this is quite paranoid, since all the known shells bail
# out after a failed `exec'.
$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
as_fn_exit 255
fi
# We don't want this to propagate to other subprocesses.
{ _as_can_reexec=; unset _as_can_reexec;}
if test "x$CONFIG_SHELL" = x; then
as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
emulate sh
@ -190,8 +167,7 @@ if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
else
exitcode=1; echo positional parameters were not saved.
fi
test x\$exitcode = x0 || exit 1
test -x / || exit 1"
test x\$exitcode = x0 || exit 1"
as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
@ -236,25 +212,21 @@ IFS=$as_save_IFS
if test "x$CONFIG_SHELL" != x; then :
export CONFIG_SHELL
# We cannot yet assume a decent shell, so we have to provide a
# neutralization value for shells without unset; and this also
# works around shells that cannot unset nonexistent variables.
# Preserve -v and -x to the replacement shell.
BASH_ENV=/dev/null
ENV=/dev/null
(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
case $- in # ((((
# neutralization value for shells without unset; and this also
# works around shells that cannot unset nonexistent variables.
# Preserve -v and -x to the replacement shell.
BASH_ENV=/dev/null
ENV=/dev/null
(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
export CONFIG_SHELL
case $- in # ((((
*v*x* | *x*v* ) as_opts=-vx ;;
*v* ) as_opts=-v ;;
*x* ) as_opts=-x ;;
* ) as_opts= ;;
esac
exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
# Admittedly, this is quite paranoid, since all the known shells bail
# out after a failed `exec'.
$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
exit 255
esac
exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"}
fi
if test x$as_have_required = xno; then :
@ -356,14 +328,6 @@ $as_echo X"$as_dir" |
} # as_fn_mkdir_p
# as_fn_executable_p FILE
# -----------------------
# Test if FILE is an executable regular file.
as_fn_executable_p ()
{
test -f "$1" && test -x "$1"
} # as_fn_executable_p
# as_fn_append VAR VALUE
# ----------------------
# Append the text in VALUE to the end of the definition contained in VAR. Take
@ -485,10 +449,6 @@ as_cr_alnum=$as_cr_Letters$as_cr_digits
chmod +x "$as_me.lineno" ||
{ $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
# If we had to re-execute with $CONFIG_SHELL, we're ensured to have
# already done that, so ensure we don't try to do so again and fall
# in an infinite loop. This has already happened in practice.
_as_can_reexec=no; export _as_can_reexec
# Don't try to exec as it changes $[0], causing all sort of problems
# (the dirname of $[0] is not the place where we might find the
# original and so on. Autoconf is especially sensitive to this).
@ -523,16 +483,16 @@ if (echo >conf$$.file) 2>/dev/null; then
# ... but there are two gotchas:
# 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
# 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
# In both cases, we have to default to `cp -pR'.
# In both cases, we have to default to `cp -p'.
ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
as_ln_s='cp -pR'
as_ln_s='cp -p'
elif ln conf$$.file conf$$ 2>/dev/null; then
as_ln_s=ln
else
as_ln_s='cp -pR'
as_ln_s='cp -p'
fi
else
as_ln_s='cp -pR'
as_ln_s='cp -p'
fi
rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
rmdir conf$$.dir 2>/dev/null
@ -544,8 +504,28 @@ else
as_mkdir_p=false
fi
as_test_x='test -x'
as_executable_p=as_fn_executable_p
if test -x / >/dev/null 2>&1; then
as_test_x='test -x'
else
if ls -dL / >/dev/null 2>&1; then
as_ls_L_option=L
else
as_ls_L_option=
fi
as_test_x='
eval sh -c '\''
if test -d "$1"; then
test -d "$1/.";
else
case $1 in #(
-*)set "./$1";;
esac;
case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
???[sx]*):;;*)false;;esac;fi
'\'' sh
'
fi
as_executable_p=$as_test_x
# Sed expression to map a string onto a valid CPP name.
as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@ -1335,6 +1315,8 @@ target=$target_alias
if test "x$host_alias" != x; then
if test "x$build_alias" = x; then
cross_compiling=maybe
$as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host.
If a cross compiler is detected then cross compile mode will be used" >&2
elif test "x$build_alias" != "x$host_alias"; then
cross_compiling=yes
fi
@ -1625,9 +1607,9 @@ test -n "$ac_init_help" && exit $ac_status
if $ac_init_version; then
cat <<\_ACEOF
configure
generated by GNU Autoconf 2.69
generated by GNU Autoconf 2.68
Copyright (C) 2012 Free Software Foundation, Inc.
Copyright (C) 2010 Free Software Foundation, Inc.
This configure script is free software; the Free Software Foundation
gives unlimited permission to copy, distribute and modify it.
_ACEOF
@ -1938,7 +1920,7 @@ $as_echo "$ac_try_echo"; } >&5
test ! -s conftest.err
} && test -s conftest$ac_exeext && {
test "$cross_compiling" = yes ||
test -x conftest$ac_exeext
$as_test_x conftest$ac_exeext
}; then :
ac_retval=0
else
@ -2041,8 +2023,7 @@ int
main ()
{
static int test_array [1 - 2 * !(($2) >= 0)];
test_array [0] = 0;
return test_array [0];
test_array [0] = 0
;
return 0;
@ -2058,8 +2039,7 @@ int
main ()
{
static int test_array [1 - 2 * !(($2) <= $ac_mid)];
test_array [0] = 0;
return test_array [0];
test_array [0] = 0
;
return 0;
@ -2085,8 +2065,7 @@ int
main ()
{
static int test_array [1 - 2 * !(($2) < 0)];
test_array [0] = 0;
return test_array [0];
test_array [0] = 0
;
return 0;
@ -2102,8 +2081,7 @@ int
main ()
{
static int test_array [1 - 2 * !(($2) >= $ac_mid)];
test_array [0] = 0;
return test_array [0];
test_array [0] = 0
;
return 0;
@ -2137,8 +2115,7 @@ int
main ()
{
static int test_array [1 - 2 * !(($2) <= $ac_mid)];
test_array [0] = 0;
return test_array [0];
test_array [0] = 0
;
return 0;
@ -2322,7 +2299,7 @@ This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.
It was created by $as_me, which was
generated by GNU Autoconf 2.69. Invocation command line was
generated by GNU Autoconf 2.68. Invocation command line was
$ $0 $@
@ -2698,7 +2675,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_CC="${ac_tool_prefix}gcc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -2738,7 +2715,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_CC="gcc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -2791,7 +2768,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_CC="${ac_tool_prefix}cc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -2832,7 +2809,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
ac_prog_rejected=yes
continue
@ -2890,7 +2867,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -2934,7 +2911,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_CC="$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -3380,7 +3357,8 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
/* end confdefs.h. */
#include <stdarg.h>
#include <stdio.h>
struct stat;
#include <sys/types.h>
#include <sys/stat.h>
/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */
struct buf { int x; };
FILE * (*rcsopen) (struct buf *, struct stat *, int);
@ -3493,7 +3471,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -3537,7 +3515,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_CXX="$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -3740,7 +3718,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_AWK="$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -4090,7 +4068,7 @@ do
for ac_prog in grep ggrep; do
for ac_exec_ext in '' $ac_executable_extensions; do
ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
as_fn_executable_p "$ac_path_GREP" || continue
{ test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue
# Check for GNU ac_path_GREP and select it if it is found.
# Check for GNU $ac_path_GREP
case `"$ac_path_GREP" --version 2>&1` in
@ -4156,7 +4134,7 @@ do
for ac_prog in egrep; do
for ac_exec_ext in '' $ac_executable_extensions; do
ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
as_fn_executable_p "$ac_path_EGREP" || continue
{ test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue
# Check for GNU ac_path_EGREP and select it if it is found.
# Check for GNU $ac_path_EGREP
case `"$ac_path_EGREP" --version 2>&1` in
@ -5278,7 +5256,7 @@ case $as_dir/ in #((
# by default.
for ac_prog in ginstall scoinst install; do
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then
if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then
if test $ac_prog = install &&
grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
# AIX install. It has an incompatible calling convention.
@ -5351,7 +5329,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5391,7 +5369,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_RANLIB="ranlib"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5443,7 +5421,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_INDENT="${ac_tool_prefix}indent"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5483,7 +5461,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_INDENT="indent"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5535,7 +5513,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_AR="${ac_tool_prefix}ar"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5575,7 +5553,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_AR="ar"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5627,7 +5605,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_MPI_CC="${ac_tool_prefix}mpicc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5667,7 +5645,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_ac_ct_MPI_CC="mpicc"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5721,7 +5699,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_path_INSTALL_INFO="$as_dir/$ac_word$ac_exec_ext"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -5762,7 +5740,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_path_SHELL="$as_dir/$ac_word$ac_exec_ext"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -6752,7 +6730,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_REXE="$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -6873,7 +6851,7 @@ do
IFS=$as_save_IFS
test -z "$as_dir" && as_dir=.
for ac_exec_ext in '' $ac_executable_extensions; do
if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
ac_cv_prog_PYTHON="$ac_prog"
$as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
break 2
@ -8459,7 +8437,7 @@ fi
if test "$coroutining" = "yes"
then
YAP_EXTRAS="$YAP_EXTRAS -DCOROUTINING=1"
YAP_EXTRAS="$YAP_EXTRAS -DCOROUTINING=1 -DCUT_C=1"
fi
if test "$rationaltrees" = "yes"
@ -11854,16 +11832,16 @@ if (echo >conf$$.file) 2>/dev/null; then
# ... but there are two gotchas:
# 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
# 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
# In both cases, we have to default to `cp -pR'.
# In both cases, we have to default to `cp -p'.
ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
as_ln_s='cp -pR'
as_ln_s='cp -p'
elif ln conf$$.file conf$$ 2>/dev/null; then
as_ln_s=ln
else
as_ln_s='cp -pR'
as_ln_s='cp -p'
fi
else
as_ln_s='cp -pR'
as_ln_s='cp -p'
fi
rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
rmdir conf$$.dir 2>/dev/null
@ -11923,16 +11901,28 @@ else
as_mkdir_p=false
fi
# as_fn_executable_p FILE
# -----------------------
# Test if FILE is an executable regular file.
as_fn_executable_p ()
{
test -f "$1" && test -x "$1"
} # as_fn_executable_p
as_test_x='test -x'
as_executable_p=as_fn_executable_p
if test -x / >/dev/null 2>&1; then
as_test_x='test -x'
else
if ls -dL / >/dev/null 2>&1; then
as_ls_L_option=L
else
as_ls_L_option=
fi
as_test_x='
eval sh -c '\''
if test -d "$1"; then
test -d "$1/.";
else
case $1 in #(
-*)set "./$1";;
esac;
case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
???[sx]*):;;*)false;;esac;fi
'\'' sh
'
fi
as_executable_p=$as_test_x
# Sed expression to map a string onto a valid CPP name.
as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@ -11954,7 +11944,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
# values after options handling.
ac_log="
This file was extended by $as_me, which was
generated by GNU Autoconf 2.69. Invocation command line was
generated by GNU Autoconf 2.68. Invocation command line was
CONFIG_FILES = $CONFIG_FILES
CONFIG_HEADERS = $CONFIG_HEADERS
@ -12016,10 +12006,10 @@ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
ac_cs_version="\\
config.status
configured by $0, generated by GNU Autoconf 2.69,
configured by $0, generated by GNU Autoconf 2.68,
with options \\"\$ac_cs_config\\"
Copyright (C) 2012 Free Software Foundation, Inc.
Copyright (C) 2010 Free Software Foundation, Inc.
This config.status script is free software; the Free Software Foundation
gives unlimited permission to copy, distribute and modify it."
@ -12109,7 +12099,7 @@ fi
_ACEOF
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
if \$ac_cs_recheck; then
set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
shift
\$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
CONFIG_SHELL='$SHELL'

View File

@ -1487,7 +1487,7 @@ fi
if test "$coroutining" = "yes"
then
YAP_EXTRAS="$YAP_EXTRAS -DCOROUTINING=1"
YAP_EXTRAS="$YAP_EXTRAS -DCOROUTINING=1 -DCUT_C=1"
fi
if test "$rationaltrees" = "yes"

View File

@ -81,10 +81,10 @@ getclauses1(File, Prog, _Opts) :-
'$bpe_process_pred'([], _F, N, Mode, _Delay, _Tabled, []) -->
{ '$init_mode'(N, Mode) }.
'$bpe_process_pred'(Call.Prog0, F,N,Modes,Delay,Tabled, Cls0) -->
'$bpe_process_pred'([Call|Prog0], F,N, Modes, Delay, Tabled, Cls0) -->
{ '$get_pred'(Call, F, N, Modes, Delay, Tabled, Cls0, ClsI) }, !,
'$bpe_process_pred'(Prog0, F,N,Modes,Delay,Tabled, ClsI).
'$bpe_process_pred'(Call.Prog0, F,N,Modes,Delay,Tabled, Cls0) -->
'$bpe_process_pred'(Prog0, F, N, Modes, Delay, Tabled, ClsI).
'$bpe_process_pred'([Call|Prog0], F, N, Modes, Delay, Tabled, Cls0) -->
[ Call ],
'$bpe_process_pred'(Prog0, F,N,Modes,Delay,Tabled, Cls0).
@ -97,21 +97,22 @@ getclauses1(File, Prog, _Opts) :-
'$get_pred'((P :- Q), F, N, _Modes, _Delay, _Tabled) -->
{ functor(P, F, N), ! },
[(P:-Q)].
'$get_pred'((:- mode Q), F, N, _Modes, _Delay, _Tabled) -->
'$get_pred'((:- mode Q), F, N, Modes, _Delay, _Tabled) -->
{ functor(Q, F, N), !, Q =.. [_|Modes0],
'$bpe_cvt_modes'(Modes0,Modes,[])
'$bpe_cvt_modes'(Modes0, Modes, [])
},
[].
%'$get_pred'((:- table _), F, N, Modes, Delay, Tabled) -->
% { functor(Q, F, N), !, Q =.. [_|Modes] },
% [].
'$get_pred'((:- _), _F, _N, _Modes, _Delay, _Tabled) --> !, { fail }.
'$get_pred'((:- Q), '$damon_load', 0, _Modes, _Delay, _Tabled) -->
[ ('$damon_load' :- '$query'( Q ) )].
'$get_pred'((P), F, N, _Modes, _Delay, _Tabled) -->
{ functor(P, F, N), ! },
[(P)].
'$bpe_cvt_modes'(Mode.Modes0) --> [NewMode],
'$bpe_cvt_modes'([Mode|Modes0]) --> [NewMode],
{ '$bpe_cvt_mode'(Mode, NewMode) },
'$bpe_cvt_modes'(Modes0).
'$bpe_cvt_modes'([]) --> [].
@ -127,20 +128,40 @@ preprocess_cl(Cl, Cl, _, _, _, _).
phase_1_process(Prog, Prog).
compileProgToFile(_,_File,[]).
compileProgToFile(_,File,pred(F,N,_,_,Tabled,Clauses).Prog2) :-
compileProgToFile(_, _File, []).
compileProgToFile(_, File, [Pred|Prog2]) :-
consult_pred(Pred),
compileProgToFile(_, File, Prog2).
consult_preds([], L) :- !,
consult_preds(L).
consult_preds(L0, L) :-
writeln(consult_preds(L0,L)).
consult_preds([]).
consult_preds([P|L]) :-
consult_pred(P),
consult_preds(L).
consult_pred(pred(F,N,_Mode,_Delay,Tabled,Clauses)) :-
(nonvar(Tabled) -> table(F/N) ; true),
functor(S,F,N),
assert(b_IS_CONSULTED_c(S)),
'$assert_clauses'(Clauses),
compileProgToFile(_,File,Prog2).
abolish(F/N),
'$assert_clauses'(Clauses).
add_pred(Name, Arity, _Mode, _Delay, Tabled, Clauses) :-
'$assert_clauses'(Clauses).
'$assert_clauses'([]).
'$assert_clauses'(Cl.Clauses) :-
'$assert_clauses'([Cl|Clauses]) :-
assert_static(Cl),
'$assert_clauses'(Clauses).
'$myload'(_F).
'$myload'(_F) :-
'$damon_load'.
'$query'(G) :- call(G).
initialize_table :- abolish_all_tables.

View File

@ -28,9 +28,9 @@ INSTALL=@INSTALL@
INSTALL_DATA=@INSTALL_DATA@
INSTALL_PROGRAM=@INSTALL_PROGRAM@
srcdir=@srcdir@
PDFLATEX=pdflatex
CLPBN_TOP= $(srcdir)/clpbn.yap \
$(srcdir)/pfl.yap
PFL_MANUAL = $(srcdir)/pfl
CLPBN_SRCDIR = $(srcdir)/clpbn
@ -38,6 +38,10 @@ CLPBN_LEARNING_SRCDIR = $(srcdir)/learning
CLPBN_EXDIR = $(srcdir)/examples
CLPBN_TOP= \
$(srcdir)/clpbn.yap \
$(srcdir)/pfl.yap
CLPBN_PROGRAMS= \
$(CLPBN_SRCDIR)/aggregates.yap \
$(CLPBN_SRCDIR)/bdd.yap \
@ -74,12 +78,24 @@ CLPBN_LEARNING_PROGRAMS= \
$(CLPBN_LEARNING_SRCDIR)/learn_utils.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_EXDIR)/School/README \
$(CLPBN_EXDIR)/School/evidence_128.yap \
$(CLPBN_EXDIR)/School/parschema.pfl \
$(CLPBN_EXDIR)/School/school_128.yap \
$(CLPBN_EXDIR)/School/school32.yap \
$(CLPBN_EXDIR)/School/school_32.yap \
$(CLPBN_EXDIR)/School/school_64.yap \
$(CLPBN_EXDIR)/School/tables.yap
@ -99,20 +115,8 @@ CLPBN_LEARNING_EXAMPLES= \
$(CLPBN_EXDIR)/learning/sprinkler_params.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_PROGRAMS)
install: $(CLBN_TOP) $(CLBN_PROGRAMS) $(CLPBN_LEARNING_PROGRAMS) $(CLPBN_SCHOOL_EXAMPLES) $(CLPBN_HMMER_EXAMPLES) $(CLPBN_LEARNING_EXAMPLES)
mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn
mkdir -p $(DESTDIR)$(SHAREDIR)/clpbn/learning
mkdir -p $(DESTDIR)$(EXDIR)
@ -127,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_LEARNING_EXAMPLES); do $(INSTALL_DATA) $$h $(DESTDIR)$(EXDIR)/learning; done
docs: $(MANUAL)
$(PDFLATEX) $(PFL_MANUAL)
$(PDFLATEX) $(PFL_MANUAL)
rm 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,40 +1,36 @@
:- module(clpbn, [{}/1,
:- module(clpbn,
[{}/1,
clpbn_flag/2,
set_clpbn_flag/2,
set_solver/1,
set_em_solver/1,
clpbn_flag/3,
clpbn_key/2,
clpbn_init_graph/1,
clpbn_init_solver/4,
clpbn_run_solver/3,
pfl_init_solver/6,
pfl_run_solver/4,
clpbn_finalize_solver/1,
clpbn_init_solver/5,
clpbn_run_solver/4,
clpbn_init_graph/1,
pfl_init_solver/5,
pfl_run_solver/3,
pfl_end_solver/1,
probability/2,
conditional_probability/3,
use_parfactors/1,
op( 500, xfy, with)]).
op(500, xfy, with)
]).
:- use_module(library(atts)).
:- use_module(library(bhash)).
:- use_module(library(lists)).
:- use_module(library(terms)).
:- 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.
:- use_module('clpbn/ve',
[ve/3,
check_if_ve_done/1,
@ -45,22 +41,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',
[jt/3,
init_jt_solver/4,
@ -76,11 +56,6 @@
call_bdd_ground_solver/6
]).
%% :- use_module('clpbn/bnt',
%% [do_bnt/3,
%% check_if_bnt_done/1
%% ]).
:- use_module('clpbn/gibbs',
[gibbs/3,
check_if_gibbs_done/1,
@ -89,19 +64,34 @@
]).
:- use_module('clpbn/pgrammar',
[init_pcg_solver/4,
run_pcg_solver/3,
pcg_init_graph/0
[pcg_init_graph/0,
init_pcg_solver/4,
run_pcg_solver/3
]).
:- use_module('clpbn/graphs',
[
clpbn2graph/1
:- 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/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',
[
dist/4,
[dist/4,
get_dist/4,
get_evidence_position/3,
get_evidence_from_position/3,
@ -109,82 +99,122 @@
]).
:- use_module('clpbn/evidence',
[
store_evidence/1,
[store_evidence/1,
add_stored_evidence/2,
incorporate_evidence/2,
check_stored_evidence/2,
put_evidence/2
]).
:- use_module('clpbn/ground_factors',
[generate_network/5]).
:- use_module('clpbn/utils',
[
sort_vars_by_key/3
]).
[sort_vars_by_key/3]).
:- use_module('clpbn/graphs',
[clpbn2graph/1]).
:- use_module('clpbn/graphviz',
[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.
solver(ve).
em_solver(bp).
:- dynamic
solver/1,
em_solver/1,
suppress_attribute_display/1,
parameter_softening/1,
use_parfactors/1,
output/1,
use/1.
:- meta_predicate probability(:,-), conditional_probability(:,:,-).
%output(xbif(user_error)).
%output(gviz(user_error)).
output(no).
solver(hve).
em_solver(hve).
suppress_attribute_display(false).
parameter_softening(m_estimate(10)).
use_parfactors(off).
output(no).
%output(xbif(user_error)).
%output(gviz(user_error)).
clpbn_flag(Flag,Option) :-
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, Option).
set_clpbn_flag(Flag,Option) :-
clpbn_flag(Flag, _, Option).
clpbn_flag(output,Before,After) :-
retract(output(Before)),
assert(output(After)).
clpbn_flag(solver,Before,After) :-
retract(solver(Before)),
assert(solver(After)).
clpbn_flag(em_solver,Before,After) :-
retract(em_solver(Before)),
assert(em_solver(After)).
clpbn_flag(bnt_solver,Before,After) :-
retract(bnt:bnt_solver(Before)),
assert(bnt:bnt_solver(After)).
clpbn_flag(bnt_path,Before,After) :-
retract(bnt:bnt_path(Before)),
assert(bnt:bnt_path(After)).
clpbn_flag(bnt_model,Before,After) :-
retract(bnt:bnt_model(Before)),
assert(bnt:bnt_model(After)).
clpbn_flag(suppress_attribute_display,Before,After) :-
retract(suppress_attribute_display(Before)),
assert(suppress_attribute_display(After)).
clpbn_flag(parameter_softening,Before,After) :-
retract(parameter_softening(Before)),
assert(parameter_softening(After)).
clpbn_flag(use_factors,Before,After) :-
retract(use_parfactors(Before)),
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), !.
{Var = Key with Dist} :-
{ Var = Key with Dist } :-
put_atts(El,[key(Key),dist(DistInfo,Parents)]),
dist(Dist, DistInfo, Key, Parents),
add_evidence(Var,Key,DistInfo,El)
% ,writeln({Var = Key with Dist})
.
.
%
% make sure a query variable is reachable by the garbage collector.
@ -203,8 +233,10 @@ init_clpbn_vars(El) :-
create_mutable(El, Mutable),
b_setval(clpbn_qvars, Mutable).
check_constraint(Constraint, _, _, Constraint) :- var(Constraint), !.
check_constraint((A->D), _, _, (A->D)) :- var(A), !.
check_constraint(Constraint, _, _, Constraint) :-
var(Constraint), !.
check_constraint((A->D), _, _, (A->D)) :-
var(A), !.
check_constraint((([A|B].L)->D), Vars, NVars, (([A|B].NL)->D)) :- !,
check_cpt_input_vars(L, Vars, NVars, NL).
check_constraint(Dist, _, _, Dist).
@ -240,11 +272,13 @@ clpbn_marginalise(V, Dist) :-
%
project_attributes(GVars0, _AVars0) :-
use_parfactors(on),
clpbn_flag(solver, Solver), Solver \= fove, !,
clpbn_flag(solver, Solver),
ground_solver(Solver),
generate_network(GVars0, GKeys, Keys, Factors, Evidence),
b_setval(clpbn_query_variables, f(GVars0,Evidence)),
simplify_query(GVars0, GVars),
( GKeys = []
(
GKeys = []
->
GVars0 = [V|_],
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).
% 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(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 a solver with keys, not actual variables
call_ground_solver(ve, GVars, GoalKeys, Keys, Factors, Evidence) :- !,
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) :-
% traditional solver
% fall back to traditional solver
b_hash_new(Hash0),
foldl(gvar_in_hash, GVars, Hash0, HashI),
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, _),
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)
% into CLP(BN) for evaluation
@ -466,14 +530,11 @@ bind_clpbn(T, Var, Key, Dist, Parents, []) :- var(T),
;
fail
).
bind_clpbn(_, Var, _, _, _, _, []) :-
use(bnt),
check_if_bnt_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :-
use(ve),
check_if_ve_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :-
use(bp),
use(hve),
check_if_horus_ground_solver_done(Var), !.
bind_clpbn(_, Var, _, _, _, _, []) :-
use(jt),
@ -481,6 +542,15 @@ bind_clpbn(_, Var, _, _, _, _, []) :-
bind_clpbn(_, Var, _, _, _, _, []) :-
use(bdd),
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, _, _, _, []) :-
get_atts(Var, [key(Key)]), !,
(
@ -495,7 +565,7 @@ fresh_attvar(Var, NVar) :-
put_atts(NVar, LAtts).
% I will now allow two CLPBN variables to be bound together.
%bind_clpbns(Key, Dist, Parents, Key, Dist, Parents).
% bind_clpbns(Key, Dist, Parents, Key, Dist, Parents).
bind_clpbns(Key, Dist, Parents, Key1, Dist1, Parents1) :-
Key == Key1, !,
get_dist(Dist,_Type,_Domain,_Table),
@ -532,6 +602,15 @@ user:term_expansion((A :- {}), ( :- true )) :- !, % evidence
clpbn_key(Var,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).
% 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),
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) :-
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) :-
init_jt_solver(LVs, Vs0, VarsWithUnboundKeys, State).
clpbn_init_solver(bdd, 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) :-
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
% Vs is the full graph
% Ps are the probabilities on LVs.
%
%
clpbn_run_solver(LVs, LPs, State) :-
solver(Solver),
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) :-
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) :-
run_jt_solver(LVs, LPs, State).
clpbn_run_solver(bdd, 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) :-
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).
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).
pfl_run_solver(LVs, LPs, State, bp) :-
run_horus_ground_solver(LVs, LPs, State, bp).
pfl_run_solver(LVs, LPs, State, hve) :-
run_horus_ground_solver(LVs, LPs, State, hve).
pfl_run_solver(LVs, LPs, State, bp) :- !,
run_horus_ground_solver(LVs, LPs, State).
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).
%
% 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) :-
findall(Prob, do_probability(Goal, [], Prob), [Prob]).

View File

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

View File

@ -384,9 +384,9 @@ avg_exp([Val|Vals], PVars, I0, P0, Max, Size, Im, IM, HI, HF, O) :-
(Vals = [] -> O=O1 ; O = Val*O1+not(Val)*O2 ),
Im1 is max(0, Im-I0),
IM1 is IM-I0,
( IM1 < 0 -> O1 = 0, H2 = HI; /* we have exceed maximum */
Im1 > Max -> O1 = 0, H2 = HI; /* we cannot make to minimum */
Im1 = 0, IM1 > Max -> O1 = 1, H2 = HI; /* we cannot exceed maximum */
( IM1 < 0 -> O1 = 0, H2 = HI ; /* we have exceed maximum */
Im1 > Max -> O1 = 0, H2 = HI ; /* we cannot make to minimum */
Im1 = 0, IM1 > Max -> O1 = 1, H2 = HI ; /* we cannot exceed maximum */
P is P0+1,
avg_tree(PVars, P, Max, Im1, IM1, Size, O1, HI, H2)
),
@ -1064,4 +1064,3 @@ build_cnf(CNF, IVs, Indics, AllParms, AllParmValues, Val) :-
set_to_ones(Extra),
ddnnf_is(F, Val).

View File

@ -1,20 +1,23 @@
:- module(bnt, [do_bnt/3,
:- module(bnt,
[do_bnt/3,
create_bnt_graph/2,
check_if_bnt_done/1]).
check_if_bnt_done/1
]).
:- use_module(library('clpbn/display'), [
clpbn_bind_vals/3]).
:- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]).
:- use_module(library('clpbn/dists'), [
get_dist_domain_size/2,
:- use_module(library('clpbn/dists'),
[get_dist_domain_size/2,
get_dist_domain/2,
get_dist_params/2
]).
:- use_module(library('clpbn/discrete_utils'), [
reorder_CPT/5]).
:- use_module(library('clpbn/discrete_utils'),
[reorder_CPT/5]).
:- use_module(library(matlab), [start_matlab/1,
:- use_module(library(matlab),
[start_matlab/1,
close_matlab/0,
matlab_on/0,
matlab_eval_string/1,
@ -27,7 +30,8 @@
matlab_call/2
]).
:- use_module(library(dgraphs), [dgraph_new/1,
:- use_module(library(dgraphs),
[dgraph_new/1,
dgraph_add_vertices/3,
dgraph_add_edges/3,
dgraph_top_sort/2,
@ -35,11 +39,13 @@
dgraph_edges/2
]).
:- use_module(library(lists), [append/3,
member/2,nth/3]).
:- use_module(library(lists),
[append/3,
member/2,nth/3
]).
:- use_module(library(ordsets), [
ord_insert/3]).
:- use_module(library(ordsets),
[ord_insert/3]).
:- 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),
mk_evidence_query(L, T, LN).

View File

@ -3,8 +3,8 @@
[influences/3,
factor_influences/4,
init_influences/3,
influences/4]
).
influences/4
]).
:- use_module(library(maplist)).
@ -14,13 +14,15 @@
dgraph_add_vertex/3,
dgraph_neighbors/3,
dgraph_edge/3,
dgraph_transpose/2]).
dgraph_transpose/2
]).
:- use_module(library(rbtrees),
[rb_new/1,
rb_lookup/3,
rb_insert/4,
rb_visit/2]).
rb_visit/2
]).
factor_influences(Vs, QVars, Ev, LV) :-
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) :-
rb_lookup(Child, [_|B], Vs0), !,
(
B == b ->
B == b
->
Vs0 = Vs1 % been there before
;
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) :-
rb_lookup(Parent, [T|_], Vs0), !,
(
T == t ->
T == t
->
Vs1 = Vs0 % been there before
;
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,
get_dist_size/2]).
get_dist_size/2
]).
:- use_module(library(clpbn/dists), [get_dist_domain_size/2,
get_dist_domain/2]).
:- use_module(library(clpbn/dists),
[get_dist_domain_size/2,
get_dist_domain/2
]).
%
% remove columns from a table
%
@ -143,4 +147,3 @@ get_sizes([V|Deps], [Sz|Sizes]) :-
get_dist_domain_size(Id,Sz),
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),
[
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(atts)).
:- attribute posterior/4.

View File

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

View File

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

View File

@ -11,48 +11,51 @@
[gibbs/3,
check_if_gibbs_done/1,
init_gibbs_solver/4,
run_gibbs_solver/3]).
run_gibbs_solver/3
]).
:- use_module(library(rbtrees),
[rb_new/1,
rb_insert/4,
rb_lookup/3]).
rb_lookup/3
]).
:- use_module(library(lists),
[member/2,
append/3,
delete/3,
max_list/2,
sum_list/2]).
sum_list/2
]).
:- use_module(library(ordsets),
[ord_subtract/3]).
:- use_module(library('clpbn/matrix_cpt_utils'), [
project_from_CPT/3,
:- use_module(library('clpbn/matrix_cpt_utils'),
[project_from_CPT/3,
reorder_CPT/5,
multiply_possibly_deterministic_factors/3,
column_from_possibly_deterministic_CPT/3,
normalise_possibly_deterministic_CPT/2,
list_from_CPT/2]).
list_from_CPT/2
]).
:- use_module(library('clpbn/utils'), [
check_for_hidden_vars/3]).
:- use_module(library('clpbn/utils'),
[check_for_hidden_vars/3]).
:- use_module(library('clpbn/dists'), [
get_possibly_deterministic_dist_matrix/5,
get_dist_domain_size/2]).
:- use_module(library('clpbn/dists'),
[get_possibly_deterministic_dist_matrix/5,
get_dist_domain_size/2
]).
:- use_module(library('clpbn/topsort'), [
topsort/2]).
:- use_module(library('clpbn/topsort'),
[topsort/2]).
:- use_module(library('clpbn/display'), [
clpbn_bind_vals/3]).
:- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]).
:- use_module(library('clpbn/connected'),
[
influences/3
]).
[influences/3]).
:- dynamic gibbs_params/3.
@ -455,7 +458,7 @@ get_estimate_pos([I|Is], Sample, [M|Mult], V0, V) :-
get_estimate_pos(Is, Sample, Mult, VI, V).
update_estimate_for_var(V0,[X|T],[X1|NT]) :-
( V0 == 0 ->
(V0 == 0 ->
X1 is X+1,
NT = T
;
@ -542,5 +545,3 @@ divide_list([C|Add], Sum, [P|Dist]) :-
P is C/Sum,
divide_list(Add, Sum, Dist).

View File

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

View File

@ -1,40 +1,34 @@
%parfactor(
% [ability(P),grade(C,S), satisfaction(C,S,P)],
% \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,
:- module(pfl_ground_factors,
[generate_network/5,
f/3
]).
:- use_module(library(bhash), [
b_hash_new/1,
:- use_module(library(bhash),
[b_hash_new/1,
b_hash_lookup/3,
b_hash_insert/4,
b_hash_to_list/2]).
b_hash_to_list/2
]).
:- use_module(library(lists), [
delete/3,
nth0/3,
member/2]).
:- use_module(library(lists),
[member/2]).
:- use_module(library(maplist)).
:- use_module(library(pfl), [
factor/6,
:- use_module(library(atts)).
:- use_module(library(pfl),
[factor/6,
defined_in_factor/2,
skolem/2]).
skolem/2
]).
:- use_module(library(clpbn/aggregates), [
avg_factors/5]).
:- use_module(library(clpbn/aggregates),
[avg_factors/5]).
:- use_module(library(clpbn/dists), [
dist/4]).
:- use_module(library(clpbn/dists),
[dist/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) :-
% writeln(+Ks),
( Ks = [K,Els], var(Els)
(
Ks = [K,Els], var(Els)
->
% aggregate factor
once(run(Constraints)),

View File

@ -1,8 +1,9 @@
:- module(hmm, [init_hmm/0,
:- module(hmm,
[init_hmm/0,
hmm_state/1,
emission/1]).
emission/1
]).
:- ensure_loaded(library(clpbn)).
@ -46,21 +47,18 @@ hmm_state(N/A,Mod) :-
Key =.. [T|KArgs],
Head =.. [N|LArgs],
asserta_static( (Mod:Head :-
( First > 2 ->
(First > 2 ->
Last = Key, !
;
nb_getval(trie, Trie), trie_check_entry(Trie, Key, _)
->
nb_getval(trie, Trie), trie_check_entry(Trie, Key, _) ->
% leave work for solver!
%
Last = Key, !
;
% first time we saw this entry
nb_getval(trie, Trie), trie_put_entry(Trie, Key, _),
fail
)
)
).
)).
build_args(4,[A,B,C,D],[A,B,C],A,D).
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) :-
arg(Nth,Logs,Log).

View File

@ -5,12 +5,11 @@
********************************************************/
:- module(clpbn_horus,
[set_solver/1,
set_horus_flag/1,
[set_horus_flag/2,
cpp_create_lifted_network/3,
cpp_create_ground_network/4,
cpp_set_parfactors_params/2,
cpp_set_factors_params/2,
cpp_set_parfactors_params/3,
cpp_set_factors_params/3,
cpp_run_lifted_solver/3,
cpp_run_ground_solver/3,
cpp_set_vars_information/2,
@ -19,8 +18,9 @@
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 :-
@ -28,38 +28,29 @@ patch_things_up :-
warning :-
format(user_error,"Horus library not installed: cannot use bp, fove~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)).
format(user_error,"Horus library not installed: cannot use hve, bp, cbp, lve, lkc and lbp~n.",[]).
set_horus_flag(K,V) :- cpp_set_horus_flag(K,V).
:- cpp_set_horus_flag(schedule, seq_fixed).
%:- cpp_set_horus_flag(schedule, seq_random).
%:- cpp_set_horus_flag(schedule, parallel).
%:- cpp_set_horus_flag(schedule, max_residual).
:- cpp_set_horus_flag(verbosity, 0).
:- 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(use_logarithms, true).
:- cpp_set_horus_flag(bp_msg_schedule, seq_fixed).
%:- 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,
check_if_horus_ground_solver_done/1,
init_horus_ground_solver/5,
run_horus_ground_solver/4,
finalize_horus_ground_solver/1
run_horus_ground_solver/3,
end_horus_ground_solver/1
]).
:- use_module(horus,
[cpp_create_ground_network/4,
cpp_set_factors_params/2,
cpp_set_factors_params/3,
cpp_run_ground_solver/3,
cpp_set_vars_information/2,
cpp_free_ground_network/1,
set_solver/1
cpp_set_vars_information/2
]).
:- use_module(library('clpbn/dists'),
[dist/4,
get_dist_domain/2,
get_dist_domain_size/2,
get_dist_params/2
:- use_module(library('clpbn/numbers'),
[lists_of_keys_to_ids/6,
keys_to_numbers/7
]).
:- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]).
:- use_module(library(clpbn/numbers)).
:- use_module(library(pfl),
[get_pfl_parameters/2,
skolem/2
]).
:- use_module(library(charsio),
[term_to_atom/2]).
:- use_module(library(pfl),
[skolem/2]).
:- use_module(library(maplist)).
:- use_module(library(lists)).
:- use_module(library(atts)).
:- use_module(library(bhash)).
call_horus_ground_solver(QueryVars, QueryKeys, AllKeys, Factors, Evidence, Output) :-
call_horus_ground_solver(QueryVars, QueryKeys, AllKeys, Factors, Evidence,
Output) :-
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),
finalize_horus_ground_solver(State).
end_horus_ground_solver(State).
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence, state(Network,Hash4,Id4)) :-
get_factors_type(Factors, Type),
keys_to_numbers(AllKeys, Factors, Evidence, Hash4, Id4, FactorIds, EvidenceIds),
cpp_create_ground_network(Type, FactorIds, EvidenceIds, Network),
%writeln(network:(Type, FactorIds, EvidenceIds, Network)), writeln(''),
maplist(get_var_information, AllKeys, StatesNames),
maplist(term_to_atom, AllKeys, KeysAtoms),
cpp_set_vars_information(KeysAtoms, StatesNames).
init_horus_ground_solver(QueryKeys, AllKeys, Factors, Evidence,
state(Network,Hash,Id,DistIds)) :-
factors_type(Factors, Type),
keys_to_numbers(AllKeys, Factors, Evidence, Hash, Id, FacIds, EvIds),
%writeln(network:(type=Type, factors=FacIds, evidence=EvIds)), nl,
cpp_create_ground_network(Type, FacIds, EvIds, Network),
%maplist(term_to_atom, AllKeys, VarNames),
%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) :-
set_solver(Solver),
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),
run_horus_ground_solver(QueryKeys, Solutions,
state(Network,Hash,Id, DistIds)) :-
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).
get_factors_type([f(bayes, _, _)|_], bayes) :- ! .
get_factors_type([f(markov, _, _)|_], markov) :- ! .
end_horus_ground_solver(state(Network,_Hash,_Id, _DistIds)) :-
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).
get_var_information(Key, Domain) :-
get_domain(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,
init_horus_lifted_solver/4,
run_horus_lifted_solver/3,
finalize_horus_lifted_solver/1
end_horus_lifted_solver/1
]).
:- use_module(horus,
[cpp_create_lifted_network/3,
cpp_set_parfactors_params/2,
cpp_set_parfactors_params/3,
cpp_run_lifted_solver/3,
cpp_free_lifted_network/1
]).
@ -25,83 +25,65 @@
:- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]).
:- use_module(library('clpbn/dists'),
[get_dist_params/2]).
:- use_module(library(pfl),
[factor/6,
skolem/2,
get_pfl_parameters/2
]).
:- use_module(library(maplist)).
call_horus_lifted_solver(QueryVars, AllVars, Output) :-
init_horus_lifted_solver(_, AllVars, _, State),
run_horus_lifted_solver(QueryVars, Solutions, State),
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_dist_ids(Parfactors, DistIds0),
sort(DistIds0, DistIds),
get_observed_vars(AllVars, ObservedVars),
%writeln(parfactors:Parfactors:'\n'),
%writeln(evidence:ObservedVars:'\n'),
cpp_create_lifted_network(Parfactors, ObservedVars, ParfactorList).
get_observed_keys(AllVars, ObservedKeys),
%writeln(network:(parfactors=Parfactors, evidence=ObservedKeys)), nl,
cpp_create_lifted_network(Parfactors, ObservedKeys, Network),
maplist(get_dist_id, Parfactors, DistIds0),
sort(DistIds0, DistIds).
run_horus_lifted_solver(QueryVars, Solutions, state(ParfactorList, DistIds)) :-
get_query_keys(QueryVars, QueryKeys),
get_dists_parameters(DistIds, DistsParams),
%writeln(dists:DistsParams), writeln(''),
cpp_set_parfactors_params(ParfactorList, DistsParams),
cpp_run_lifted_solver(ParfactorList, QueryKeys, Solutions).
run_horus_lifted_solver(QueryVars, Solutions, state(Network, DistIds)) :-
maplist(get_query_keys, QueryVars, QueryKeys),
%maplist(get_pfl_parameters, DistIds,DistsParams),
%cpp_set_parfactors_params(Network, DistIds, DistsParams),
cpp_run_lifted_solver(Network, QueryKeys, Solutions).
finalize_horus_lifted_solver(state(ParfactorList, _)) :-
cpp_free_lifted_network(ParfactorList).
end_horus_lifted_solver(state(Network, _)) :-
cpp_free_lifted_network(Network).
%
% Enumerate all parfactors and enumerate their domain as tuples.
%
:- 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) :-
findall(F, is_factor(F), Factors).
is_factor(pf(Id, Ks, Rs, Phi, Tuples)) :-
factor(_Type, Id, Ks, Vs, Table, Constraints),
get_ranges(Ks,Rs),
maplist(get_range, Ks, Rs),
Table \= avg,
gen_table(Table, Phi),
all_tuples(Constraints, Vs, Tuples).
get_ranges([],[]).
get_ranges(K.Ks, Range.Rs) :- !,
skolem(K,Domain),
length(Domain,Range),
get_ranges(Ks, Rs).
get_range(K, Range) :-
skolem(K, Domain),
length(Domain, Range).
gen_table(Table, Phi) :-
( is_list(Table)
->
Phi = Table
;
call(user:Table, Phi)
).
( is_list(Table) -> Phi = Table ; call(user:Table, Phi) ).
all_tuples(Constraints, Tuple, Tuples) :-
@ -114,35 +96,20 @@ run(Goal.Constraints) :-
run(Constraints).
get_dist_ids([], []).
get_dist_ids(pf(Id, _, _, _, _).Parfactors, Id.DistIds) :-
get_dist_ids(Parfactors, DistIds).
get_dist_id(pf(DistId, _, _, _, _), DistId).
get_observed_vars([], []).
get_observed_vars(V.AllAttVars, [K:E|ObservedVars]) :-
get_observed_keys([], []).
get_observed_keys(V.AllAttVars, [K:E|ObservedKeys]) :-
clpbn:get_atts(V,[key(K)]),
( clpbn:get_atts(V,[evidence(E)]) ; pfl:evidence(K,E) ), !,
get_observed_vars(AllAttVars, ObservedVars).
get_observed_vars(V.AllAttVars, ObservedVars) :-
clpbn:get_atts(V,[key(_K)]), !,
get_observed_vars(AllAttVars, ObservedVars).
get_observed_keys(AllAttVars, ObservedKeys).
get_observed_keys(_V.AllAttVars, ObservedKeys) :-
get_observed_keys(AllAttVars, ObservedKeys).
get_query_keys([], []).
get_query_keys(E1.L1, E2.L2) :-
get_query_keys_2(E1,E2),
get_query_keys(L1, L2).
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).
get_query_keys(V.AttVars, K.Ks) :-
clpbn:get_atts(V,[key(K)]), !,
get_query_keys(AttVars, Ks).

View File

@ -1,8 +1,9 @@
:- module(jt, [jt/3,
:- module(jt,
[jt/3,
init_jt_solver/4,
run_jt_solver/3]).
run_jt_solver/3
]).
:- use_module(library(dgraphs),
[dgraph_new/1,
@ -41,14 +42,16 @@
:- use_module(library(rbtrees),
[rb_new/1,
rb_insert/4,
rb_lookup/3]).
rb_lookup/3
]).
:- use_module(library(ordsets),
[ord_subset/2,
ord_insert/3,
ord_intersection/3,
ord_del_element/3,
ord_memberchk/2]).
ord_memberchk/2
]).
:- use_module(library(lists),
[reverse/2]).
@ -61,7 +64,8 @@
:- use_module(library('clpbn/dists'),
[get_dist_domain_size/2,
get_dist_domain/2,
get_dist_matrix/5]).
get_dist_matrix/5
]).
:- use_module(library('clpbn/matrix_cpt_utils'),
[project_from_CPT/3,
@ -74,14 +78,14 @@
get_CPT_sizes/2,
reset_CPT_that_disagrees/5,
sum_out_from_CPT/4,
list_from_CPT/2]).
list_from_CPT/2
]).
:- use_module(library('clpbn/display'), [
clpbn_bind_vals/3]).
:- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]).
:- use_module(library('clpbn/connected'),
[
init_influences/3,
[init_influences/3,
influences/4
]).
@ -290,8 +294,7 @@ add_clique_edges([], _, _, Edges, Edges).
add_clique_edges([Clique1|Cliques], Clique, Sz, Edges0, EdgesF) :-
ord_intersection(Clique1, Clique, Int),
Int \== Clique,
(
Int = [] ->
(Int = [] ->
add_clique_edges(Cliques, Clique, Sz, Edges0, EdgesF)
;
% we connect
@ -358,7 +361,7 @@ get_cpts([], _, [], []).
get_cpts([CPT|CPts], [], [], [CPT|CPts]) :- !.
get_cpts([[I|MCPT]-Info|CPTs], [J|Clique], MyCPTs, MoreCPTs) :-
compare(C,I,J),
( C == < ->
(C == < ->
% our CPT cannot be a part of the clique.
MoreCPTs = [[I|MCPT]-Info|LeftoverCPTs],
get_cpts(CPTs, [J|Clique], MyCPTs, LeftoverCPTs)

View File

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

View File

@ -1,13 +1,13 @@
:- module(clpbn_numbers,
[
keys_to_numbers/7,
[keys_to_numbers/7,
keys_to_numbers/9,
lists_of_keys_to_ids/6
]).
:- use_module(library(bhash)).
:- use_module(library(maplist)).
:- use_module(library(pfl),
[skolem/2,
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),
I is I0+1.

View File

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

View File

@ -29,7 +29,8 @@
:- use_module(library(bhash),
[b_hash_new/4,
b_hash_lookup/3,
b_hash_insert/4]).
b_hash_insert/4
]).
:- meta_predicate clpbn_table(:),
clpbn_tabled_clause(:.?),
@ -43,14 +44,13 @@
clpbn_tabled_number_of_clauses(:,-),
clpbn_is_tabled(:).
:- use_module(library(terms), [
instantiated_term_hash/4,
:- use_module(library(terms),
[instantiated_term_hash/4,
variant/2
]).
:- use_module(evidence, [
put_evidence/2
]).
:- use_module(evidence,
[put_evidence/2]).
:- dynamic clpbn_table/3.
@ -108,30 +108,28 @@ clpbn_table(F/N,M) :-
L0 = [_|Args0],
IGoal =.. [NF|Args0],
asserta(clpbn_table(S, M, IGoal)),
assert(
(M:S :-
assert((M:S :-
!,
% write(S: ' ' ),
b_getval(clpbn_tables, Tab),
% V2 is unbound.
( b_hash_lookup(Key, V2, Tab) ->
(b_hash_lookup(Key, V2, Tab) ->
% (attvar(V2) -> writeln(ok:A0:V2) ; writeln(error(V2:should_be_attvar(S)))),
( var(A0) -> A0 = V2 ; put_evidence(A0, V2) )
(var(A0) -> A0 = V2 ; put_evidence(A0, V2))
;
% writeln(new),
b_hash_insert(Tab, Key, V2, NewTab),
b_setval(clpbn_tables,NewTab),
once(M:Goal), !,
% enter evidence after binding.
( var(A0) -> A0 = V2 ; put_evidence(A0, V2) )
(var(A0) -> A0 = V2 ; put_evidence(A0, V2))
;
clpbn:clpbn_flag(solver,none) ->
true
;
throw(error(tabled_clpbn_predicate_should_never_fail,S))
)
)
).
)).
take_tail([V], V, [], V1, [V1]) :- !.
take_tail([A|L0], V, [A|L1], V1, [A|L2]) :-
@ -154,19 +152,17 @@ clpbn_tableallargs(F/N,M) :-
atom_concat(F, '___tabled', NF),
NKey =.. [NF|Args],
asserta(clpbn_table(Key, M, NKey)),
assert(
(M:Key :-
assert((M:Key :-
!,
b_getval(clpbn_tables, Tab),
( b_hash_lookup(Key, Out, Tab) ->
(b_hash_lookup(Key, Out, Tab) ->
true
;
b_hash_insert(Tab, Key, Out, NewTab),
b_setval(clpbn_tables, NewTab),
once(M:NKey)
)
)
).
)).
clpbn_table_nondet(M:X) :- !,
clpbn_table_nondet(X,M).
@ -185,18 +181,17 @@ clpbn_table_nondet(F/N,M) :-
atom_concat(F, '___tabled', NF),
NKey =.. [NF|Args],
asserta(clpbn_table(Key, M, NKey)),
assert(
(M:Key :- % writeln(in:Key),
assert((M:Key :-
% writeln(in:Key),
b_getval(clpbn_tables, Tab),
( b_hash_lookup(Key, Out, Tab) ->
(b_hash_lookup(Key, Out, Tab) ->
fail
;
b_hash_insert(Tab, Key, Out, NewTab),
b_setval(clpbn_tables, NewTab),
M:NKey
)
)
).
)).
user:term_expansion((P :- Gs), NC) :-
clpbn_table(P, M, NP),
@ -364,4 +359,3 @@ clpbn_is_tabled(M:Clause, _) :- !,
clpbn_is_tabled(Head, M) :-
clpbn_table(Head, M, _).

View File

@ -1,11 +1,13 @@
:- module(topsort, [topsort/2]).
:- module(topsort,
[topsort/2]).
:- use_module(library(dgraphs),
[dgraph_new/1,
dgraph_add_edges/3,
dgraph_add_vertices/3,
dgraph_top_sort/2]).
dgraph_top_sort/2
]).
/* simple implementation of a topological sorting algorithm */
/* graph is as Node-[Parents] */
@ -31,4 +33,3 @@ add_edges([], _V) --> [].
add_edges([P|Parents], V) --> [P-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,
check_for_hidden_vars/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.
@ -52,12 +54,10 @@ get_keys([_|AVars], KeysVars) :- % may be non-CLPBN vars.
merge_same_key([], [], _, []).
merge_same_key([K1-V1,K2-V2|Vs], SortedAVars, Ks, UnifiableVars) :-
K1 == K2, !,
(clpbn:get_atts(V1, [evidence(E)])
->
(clpbn:get_atts(V1, [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)])
;
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(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,
init_ve_solver/4,
run_ve_solver/3,
init_ve_ground_solver/5,
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),
[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'),
[
dist/4,
[dist/4,
get_dist_domain_size/2,
get_dist_params/2,
get_dist_domain_size/2,
get_dist_matrix/5]).
get_dist_matrix/5
]).
:- use_module(library('clpbn/utils'), [
clpbn_not_var_member/2]).
:- use_module(library('clpbn/utils'),
[clpbn_not_var_member/2]).
:- use_module(library('clpbn/display'), [
clpbn_bind_vals/3]).
:- use_module(library('clpbn/display'),
[clpbn_bind_vals/3]).
:- use_module(library('clpbn/connected'),
[
init_influences/3,
[init_influences/3,
influences/4,
factor_influences/4
]).
@ -58,8 +62,7 @@
:- use_module(library(clpbn/numbers)).
:- use_module(library(lists),
[
member/2,
[member/2,
append/3,
delete/3
]).
@ -73,6 +76,8 @@
:- use_module(library('clpbn/aggregates'),
[check_for_agg_vars/2]).
:- attribute size/1, all_diffs/1.
%
% uses a bipartite graph where bigraph(Vs, NFs, Fs)
% 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_CPTs(T1, Vs1, T0, Vs0, T, Vs).

View File

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

View File

@ -1,7 +1,6 @@
:- 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)
get_from_vmap/3, % add_to_vmap(+V,-I,+VMap0)
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) :-
rb_visit(Map, L).

View File

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

View File

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

View File

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

View File

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

View File

@ -18,9 +18,6 @@ total_students(4096).
:- ensure_loaded('parschema.pfl').
:- set_solver(hve).
professor(p0).
professor(p1).
professor(p2).

View File

@ -18,9 +18,6 @@ total_students(256).
:- ensure_loaded('parschema.pfl').
:- set_solver(hve).
professor(p0).
professor(p1).
professor(p2).

View File

@ -18,9 +18,6 @@ total_students(1024).
:- ensure_loaded('parschema.pfl').
:- set_solver(hve).
professor(p0).
professor(p1).
professor(p2).

View File

@ -1,28 +1,26 @@
MARKOV
BAYES
5
2 2 2 2 2
5
1 0
1 1
3 2 0 1
2 3 2
2 4 2
3 0 1 2
2 2 3
2 2 4
2
.001 .999
0.001 0.999
2
.002 .998
0.002 0.998
8
.95 .94 .29 .001
.05 .06 .71 .999
0.95 0.05 0.94 0.06 0.29 0.71 0.001 0.999
4
.9 .05
.1 .95
0.9 0.1 0.05 0.95
4
.7 .01
.3 .99
0.7 0.3 0.01 0.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)).
:- set_solver(hve).
@ -11,14 +16,14 @@
%:- set_solver(lkc).
%:- set_solver(lbp).
:- multifile people/2.
:- multifile person/2.
:- multifile ev/1.
people(joe,nyc).
people(p2, nyc).
people(p3, nyc).
people(p4, nyc).
people(p5, nyc).
person(joe,nyc).
person(p2, nyc).
person(p3, nyc).
person(p4, nyc).
person(p5, nyc).
ev(descn(p2, fits)).
ev(descn(p3, fits)).
@ -27,40 +32,40 @@ ev(descn(p5, fits)).
bayes city_conservativeness(C)::[high,low] ;
cons_table ;
[people(_,C)].
[person(_,C)].
bayes gender(P)::[male,female] ;
gender_table ;
[people(P,_)].
[person(P,_)].
bayes hair_color(P)::[dark,bright], city_conservativeness(C) ;
hair_color_table ;
[people(P,C)].
[person(P,C)].
bayes car_color(P)::[dark,bright], hair_color(P) ;
car_color_table ;
[people(P,_)].
[person(P,_)].
bayes height(P)::[tall,short], gender(P) ;
height_table ;
[people(P,_)].
[person(P,_)].
bayes shoe_size(P)::[big,small], height(P) ;
shoe_size_table ;
[people(P,_)].
[person(P,_)].
bayes guilty(P)::[y,n] ;
guilty_table ;
[people(P,_)].
[person(P,_)].
bayes descn(P)::[fits,dont_fit], car_color(P),
hair_color(P), height(P), guilty(P) ;
descn_table ;
[people(P,_)].
[person(P,_)].
bayes witness(C), descn(Joe), descn(P2) ;
witness_table ;
[people(_,C), Joe=joe, P2=p2].
[person(_,C), Joe=joe, P2=p2].
cons_table(

View File

@ -1,3 +1,8 @@
/*
Model from the paper "Lifted Probabilistic
Inference with Counting Formulas"
*/
:- use_module(library(pfl)).
:- set_solver(hve).
@ -10,31 +15,31 @@
%:- set_solver(lkc).
%:- set_solver(lbp).
:- multifile c/2.
:- multifile reg/2.
c(p1,w1).
c(p1,w2).
c(p1,w3).
c(p2,w1).
c(p2,w2).
c(p2,w3).
c(p3,w1).
c(p3,w2).
c(p3,w3).
c(p4,w1).
c(p4,w2).
c(p4,w3).
c(p5,w1).
c(p5,w2).
c(p5,w3).
reg(p1,w1).
reg(p1,w2).
reg(p1,w3).
reg(p2,w1).
reg(p2,w2).
reg(p2,w3).
reg(p3,w1).
reg(p3,w2).
reg(p3,w3).
reg(p4,w1).
reg(p4,w2).
reg(p4,w3).
reg(p5,w1).
reg(p5,w2).
reg(p5,w3).
markov attends(P), hot(W) ;
[0.2, 0.8, 0.8, 0.8] ;
[c(P,W)].
[reg(P,W)].
markov attends(P), series ;
[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. */
:- use_module(library(clpbn/learning/em)).
:- [pos:train].
:- ['../../examples/School/parschema.pfl'].
:- use_module(library(clpbn/learning/em)).
%:- clpbn:set_clpbn_flag(em_solver,gibbs).
%:- clpbn:set_clpbn_flag(em_solver,jt).
:- clpbn:set_clpbn_flag(em_solver,ve).
%:- 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 :-
graph(L),

View File

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

View File

@ -2,16 +2,17 @@
/* We do not consider aggregates yet. */
:- use_module(library(clpbn/learning/em)).
:- [pos:train].
:- ['../../examples/School/school_32'].
:- use_module(library(clpbn/learning/em)).
%:- clpbn:set_clpbn_flag(em_solver,gibbs).
%:- clpbn:set_clpbn_flag(em_solver,jt).
% :- clpbn:set_clpbn_flag(em_solver,ve).
:- 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 :-
statistics(runtime, _),

View File

@ -4,12 +4,11 @@
:- use_module(library(clpbn/learning/em)).
%:- set_pfl_flag(em_solver,gibbs).
%:- set_pfl_flag(em_solver,jt).
%:- set_pfl_flag(em_solver,hve).
%:- set_pfl_flag(em_solver,bp).
%:- set_pfl_flag(em_solver,ve).
:- set_pfl_flag(em_solver,bdd).
:- set_em_solver(ve).
%:- set_em_solver(hve).
%:- set_em_solver(bdd).
%:- set_em_solver(bp).
%:- set_em_solver(cbp).
:- 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 ]).
sprinkler_table(
[ 0.5, 0.9,
0.5, 0.1 ]).
[ 0.1, 0.5,
0.9, 0.5 ]).
rain_table(
[ 0.8, 0.2,
0.2, 0.8 ]).
wet_grass_table(
[ 1.0, 0.1, 0.1, 0.01,
0.0, 0.9, 0.9, 0.99 ]).
[ 0.99, 0.9, 0.9, 0.0,
0.01, 0.1, 0.1, 1.0 ]).
% ?- wet_grass(X).

View File

@ -1,3 +1,8 @@
/*
Model from the paper "Lifted Probabilistic
Inference with Counting Formulas"
*/
:- use_module(library(pfl)).
:- set_solver(hve).
@ -11,23 +16,23 @@
%:- set_solver(lkc).
%:- 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).

View File

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

View File

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

View File

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

View File

@ -2,9 +2,7 @@
#define HORUS_BAYESBALLGRAPH_H
#include <vector>
#include <queue>
#include <list>
#include <map>
#include <unordered_map>
#include "Var.h"
#include "Horus.h"
@ -14,7 +12,7 @@ using namespace std;
class BBNode : public Var
{
public:
BBNode (Var* v) : Var (v) , visited_(false),
BBNode (Var* v) : Var (v), visited_(false),
markedOnTop_(false), markedOnBottom_(false) { }
const vector<BBNode*>& childs (void) const { return childs_; }

View File

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

View File

@ -3,16 +3,24 @@
#include <set>
#include <vector>
#include <sstream>
#include "GroundSolver.h"
#include "Factor.h"
#include "FactorGraph.h"
#include "Util.h"
using namespace std;
enum MsgSchedule {
SEQ_FIXED,
SEQ_RANDOM,
PARALLEL,
MAX_RESIDUAL
};
class BpLink
{
public:
@ -43,7 +51,7 @@ class BpLink
void updateResidual (void)
{
residual_ = LogAware::getMaxNorm (v1_,v2_);
residual_ = LogAware::getMaxNorm (v1_, v2_);
}
virtual void updateMessage (void)
@ -68,6 +76,9 @@ class BpLink
Params* currMsg_;
Params* nextMsg_;
double residual_;
private:
DISALLOW_COPY_AND_ASSIGN (BpLink);
};
typedef vector<BpLink*> BpLinks;
@ -76,10 +87,12 @@ typedef vector<BpLink*> BpLinks;
class SPNodeInfo
{
public:
SPNodeInfo (void) { }
void addBpLink (BpLink* link) { links_.push_back (link); }
const BpLinks& getLinks (void) { return links_; }
private:
BpLinks links_;
DISALLOW_COPY_AND_ASSIGN (SPNodeInfo);
};
@ -98,22 +111,20 @@ class BeliefProp : public GroundSolver
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&);
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:
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_;
unsigned nIters_;
vector<SPNodeInfo*> varsI_;
@ -176,12 +199,18 @@ class BeliefProp : public GroundSolver
typedef unordered_map<BpLink*, SortedOrder::iterator> BpLinkMap;
BpLinkMap linkMap_;
static double accuracy_;
static unsigned maxIter_;
static MsgSchedule schedule_;
private:
void initializeSolver (void);
bool converged (void);
virtual void printLinkInformation (void) const;
DISALLOW_COPY_AND_ASSIGN (BeliefProp);
};
#endif // HORUS_BELIEFPROP_H

View File

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

View File

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

View File

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

View File

@ -5,7 +5,6 @@
#include "GroundSolver.h"
#include "FactorGraph.h"
#include "Util.h"
#include "Horus.h"
class VarCluster;
@ -76,6 +75,8 @@ class VarCluster
private:
VarNodes members_;
VarNode* repr_;
DISALLOW_COPY_AND_ASSIGN (VarCluster);
};
@ -99,6 +100,8 @@ class FacCluster
FacNodes members_;
FacNode* repr_;
VarClusters varClusters_;
DISALLOW_COPY_AND_ASSIGN (FacCluster);
};
@ -113,7 +116,7 @@ class CountingBp : public GroundSolver
Params solveQuery (VarIds);
static bool checkForIdenticalFactors;
static void setFindIdenticalFactorsFlag (bool fif) { fif_ = fif; }
private:
Color getNewColor (void)
@ -167,7 +170,6 @@ class CountingBp : public GroundSolver
unsigned getWeight (const FacCluster*,
const VarCluster*, size_t index) const;
Color freeColor_;
Colors varColors_;
Colors facColors_;
@ -176,6 +178,10 @@ class CountingBp : public GroundSolver
VarClusterMap varClusterMap_;
const FactorGraph* compressedFg_;
WeightedBp* solver_;
static bool fif_;
DISALLOW_COPY_AND_ASSIGN (CountingBp);
};
#endif // HORUS_COUNTINGBP_H

View File

@ -1,39 +1,34 @@
#include <limits>
#include <fstream>
#include "ElimGraph.h"
ElimHeuristic ElimGraph::elimHeuristic = MIN_NEIGHBORS;
ElimHeuristic ElimGraph::elimHeuristic_ = MIN_NEIGHBORS;
ElimGraph::ElimGraph (const vector<Factor*>& factors)
{
for (size_t i = 0; i < factors.size(); i++) {
if (factors[i] == 0) { // if contained just one var with evidence
continue;
}
const VarIds& vids = factors[i]->arguments();
for (size_t j = 0; j < vids.size() - 1; j++) {
EgNode* n1 = getEgNode (vids[j]);
if (n1 == 0) {
n1 = new EgNode (vids[j], factors[i]->range (j));
if (factors[i]) {
const VarIds& args = factors[i]->arguments();
for (size_t j = 0; j < args.size() - 1; j++) {
EgNode* n1 = getEgNode (args[j]);
if (!n1) {
n1 = new EgNode (args[j], factors[i]->range (j));
addNode (n1);
}
for (size_t k = j + 1; k < vids.size(); k++) {
EgNode* n2 = getEgNode (vids[k]);
if (n2 == 0) {
n2 = new EgNode (vids[k], factors[i]->range (k));
for (size_t k = j + 1; k < args.size(); k++) {
EgNode* n2 = getEgNode (args[k]);
if (!n2) {
n2 = new EgNode (args[k], factors[i]->range (k));
addNode (n2);
}
if (neighbors (n1, n2) == false) {
if (!neighbors (n1, n2)) {
addEdge (n1, n2);
}
}
}
if (vids.size() == 1) {
if (getEgNode (vids[0]) == 0) {
addNode (new EgNode (vids[0], factors[i]->range (0)));
if (args.size() == 1 && !getEgNode (args[0])) {
addNode (new EgNode (args[0], factors[i]->range (0)));
}
}
}
@ -51,16 +46,16 @@ ElimGraph::~ElimGraph (void)
VarIds
ElimGraph::getEliminatingOrder (const VarIds& exclude)
ElimGraph::getEliminatingOrder (const VarIds& excludedVids)
{
VarIds elimOrder;
unmarked_.reserve (nodes_.size());
for (size_t i = 0; i < nodes_.size(); i++) {
if (Util::contains (exclude, nodes_[i]->varId()) == false) {
if (Util::contains (excludedVids, nodes_[i]->varId()) == false) {
unmarked_.insert (nodes_[i]);
}
}
size_t nrVarsToEliminate = nodes_.size() - exclude.size();
size_t nrVarsToEliminate = nodes_.size() - excludedVids.size();
for (size_t i = 0; i < nrVarsToEliminate; i++) {
EgNode* node = getLowestCostNode();
unmarked_.remove (node);
@ -99,30 +94,26 @@ ElimGraph::exportToGraphViz (
{
ofstream out (fileName);
if (!out.is_open()) {
cerr << "error: cannot open file to write at " ;
cerr << "Markov::exportToDotFile()" << endl;
abort();
cerr << "Error: couldn't open file '" << fileName << "'." ;
return;
}
out << "strict graph {" << endl;
for (size_t i = 0; i < nodes_.size(); i++) {
if (showNeighborless || nodes_[i]->neighbors().size() != 0) {
if (showNeighborless || nodes_[i]->neighbors().empty() == false) {
out << '"' << nodes_[i]->label() << '"' << endl;
}
}
for (size_t i = 0; i < highlightVarIds.size(); i++) {
EgNode* node =getEgNode (highlightVarIds[i]);
if (node) {
out << '"' << node->label() << '"' ;
out << " [shape=box3d]" << endl;
} else {
cout << "error: invalid variable id: " << highlightVarIds[i] << endl;
abort();
cerr << "Error: invalid variable id: " << highlightVarIds[i] << "." ;
cerr << endl;
exit (EXIT_FAILURE);
}
}
for (size_t i = 0; i < nodes_.size(); i++) {
EGNeighs neighs = nodes_[i]->neighbors();
for (size_t j = 0; j < neighs.size(); j++) {
@ -130,7 +121,6 @@ ElimGraph::exportToGraphViz (
out << '"' << neighs[j]->label() << '"' << endl;
}
}
out << "}" << endl;
out.close();
}
@ -142,7 +132,7 @@ ElimGraph::getEliminationOrder (
const Factors& factors,
VarIds excludedVids)
{
if (elimHeuristic == ElimHeuristic::SEQUENTIAL) {
if (elimHeuristic_ == ElimHeuristic::SEQUENTIAL) {
VarIds allVids;
Factors::const_iterator first = factors.begin();
Factors::const_iterator end = factors.end();
@ -183,9 +173,9 @@ EgNode*
ElimGraph::getLowestCostNode (void) const
{
EgNode* bestNode = 0;
unsigned minCost = std::numeric_limits<unsigned>::max();
unsigned minCost = Util::maxUnsigned();
EGNeighs::const_iterator it;
switch (elimHeuristic) {
switch (elimHeuristic_) {
case MIN_NEIGHBORS: {
for (it = unmarked_.begin(); it != unmarked_.end(); ++ it) {
unsigned cost = getNeighborsCost (*it);
@ -238,7 +228,7 @@ ElimGraph::connectAllNeighbors (const EgNode* n)
if (neighs.size() > 0) {
for (size_t i = 0; i < neighs.size() - 1; i++) {
for (size_t j = i + 1; j < neighs.size(); j++) {
if ( ! neighbors (neighs[i], neighs[j])) {
if (!neighbors (neighs[i], neighs[j])) {
addEdge (neighs[i], neighs[j]);
}
}

View File

@ -7,7 +7,6 @@
#include "TinySet.h"
#include "Horus.h"
using namespace std;
enum ElimHeuristic
@ -59,10 +58,11 @@ class ElimGraph
static VarIds getEliminationOrder (const Factors&, VarIds);
static ElimHeuristic elimHeuristic;
static ElimHeuristic elimHeuristic (void) { return elimHeuristic_; }
static void setElimHeuristic (ElimHeuristic eh) { elimHeuristic_ = eh; }
private:
void addEdge (EgNode* n1, EgNode* n2)
{
assert (n1 != n2);
@ -133,6 +133,10 @@ class ElimGraph
vector<EgNode*> nodes_;
TinySet<EgNode*> unmarked_;
unordered_map<VarId, EgNode*> varMap_;
static ElimHeuristic elimHeuristic_;
DISALLOW_COPY_AND_ASSIGN (ElimGraph);
};
#endif // HORUS_ELIMGRAPH_H

View File

@ -7,7 +7,7 @@
#include <sstream>
#include "Factor.h"
#include "Indexer.h"
#include "Var.h"
Factor::Factor (const Factor& g)
@ -100,11 +100,11 @@ Factor::sumOutAllExceptIndex (size_t idx)
void
Factor::multiply (Factor& g)
{
if (args_.size() == 0) {
if (args_.empty()) {
clone (g);
return;
}
} else {
TFactor<VarId>::multiply (g);
}
}

View File

@ -3,7 +3,6 @@
#include <vector>
#include "Var.h"
#include "Indexer.h"
#include "Util.h"
@ -288,6 +287,7 @@ class Factor : public TFactor<VarId>
void clone (const Factor& f);
DISALLOW_ASSIGN (Factor);
};
#endif // HORUS_FACTOR_H

View File

@ -1,17 +1,23 @@
#include <set>
#include <vector>
#include <algorithm>
#include <set>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <fstream>
#include "FactorGraph.h"
#include "Factor.h"
#include "BayesBall.h"
#include "Util.h"
bool FactorGraph::exportLd_ = false;
bool FactorGraph::exportUai_ = false;
bool FactorGraph::exportGv_ = false;
bool FactorGraph::printFg_ = false;
FactorGraph::FactorGraph (const FactorGraph& fg)
{
const VarNodes& varNodes = fg.varNodes();
@ -32,20 +38,36 @@ FactorGraph::FactorGraph (const FactorGraph& fg)
FactorGraph::~FactorGraph (void)
{
for (size_t i = 0; i < varNodes_.size(); i++) {
delete varNodes_[i];
}
for (size_t i = 0; i < facNodes_.size(); i++) {
delete facNodes_[i];
}
}
void
FactorGraph::readFromUaiFormat (const char* fileName)
{
std::ifstream is (fileName);
if (!is.is_open()) {
cerr << "error: cannot read from file " << fileName << endl;
abort();
cerr << "Error: couldn't open file '" << fileName << "'." ;
exit (EXIT_FAILURE);
}
ignoreLines (is);
string line;
getline (is, line);
if (line != "MARKOV") {
cerr << "error: the network must be a MARKOV network " << endl;
abort();
if (line == "BAYES") {
bayesFactors_ = true;
} else if (line == "MARKOV") {
bayesFactors_ = false;
} else {
cerr << "Error: the type of network is missing." << endl;
exit (EXIT_FAILURE);
}
// read the number of vars
ignoreLines (is);
@ -61,23 +83,23 @@ FactorGraph::readFromUaiFormat (const char* fileName)
unsigned nrArgs;
unsigned vid;
is >> nrFactors;
vector<VarIds> factorVarIds;
vector<Ranges> factorRanges;
vector<VarIds> allVarIds;
vector<Ranges> allRanges;
for (unsigned i = 0; i < nrFactors; i++) {
ignoreLines (is);
is >> nrArgs;
factorVarIds.push_back ({ });
factorRanges.push_back ({ });
allVarIds.push_back ({ });
allRanges.push_back ({ });
for (unsigned j = 0; j < nrArgs; j++) {
is >> vid;
if (vid >= ranges.size()) {
cerr << "error: invalid variable identifier `" << vid << "'" << endl;
cerr << "identifiers must be between 0 and " << ranges.size() - 1 ;
cerr << endl;
abort();
cerr << "Error: invalid variable identifier `" << vid << "'. " ;
cerr << "Identifiers must be between 0 and " << ranges.size() - 1 ;
cerr << "." << endl;
exit (EXIT_FAILURE);
}
factorVarIds.back().push_back (vid);
factorRanges.back().push_back (ranges[vid]);
allVarIds.back().push_back (vid);
allRanges.back().push_back (ranges[vid]);
}
}
// read the parameters
@ -85,11 +107,11 @@ FactorGraph::readFromUaiFormat (const char* fileName)
for (unsigned i = 0; i < nrFactors; i++) {
ignoreLines (is);
is >> nrParams;
if (nrParams != Util::sizeExpected (factorRanges[i])) {
cerr << "error: invalid number of parameters for factor nº " << i ;
cerr << ", expected: " << Util::sizeExpected (factorRanges[i]);
cerr << ", given: " << nrParams << endl;
abort();
if (nrParams != Util::sizeExpected (allRanges[i])) {
cerr << "Error: invalid number of parameters for factor nº " << i ;
cerr << ", " << Util::sizeExpected (allRanges[i]);
cerr << " expected, " << nrParams << " given." << endl;
exit (EXIT_FAILURE);
}
Params params (nrParams);
for (unsigned j = 0; j < nrParams; j++) {
@ -98,7 +120,14 @@ FactorGraph::readFromUaiFormat (const char* fileName)
if (Globals::logDomain) {
Util::log (params);
}
addFactor (Factor (factorVarIds[i], factorRanges[i], params));
Factor f (allVarIds[i], allRanges[i], params);
if (bayesFactors_ && allVarIds[i].size() > 1) {
// In this format the child is the last variable,
// move it to be the first
std::swap (allVarIds[i].front(), allVarIds[i].back());
f.reorderArguments (allVarIds[i]);
}
addFactor (f);
}
is.close();
}
@ -110,8 +139,8 @@ FactorGraph::readFromLibDaiFormat (const char* fileName)
{
std::ifstream is (fileName);
if (!is.is_open()) {
cerr << "error: cannot read from file " << fileName << endl;
abort();
cerr << "Error: couldn't open file '" << fileName << "'." ;
exit (EXIT_FAILURE);
}
ignoreLines (is);
unsigned nrFactors;
@ -134,9 +163,9 @@ FactorGraph::readFromLibDaiFormat (const char* fileName)
ignoreLines (is);
is >> ranges[j];
VarNode* var = getVarNode (vids[j]);
if (var != 0 && ranges[j] != var->range()) {
cerr << "error: variable `" << vids[j] << "' appears in two or " ;
cerr << "more factors with a different range" << endl;
if (var && ranges[j] != var->range()) {
cerr << "Error: variable `" << vids[j] << "' appears in two or " ;
cerr << "more factors with a different range." << endl;
}
}
// read parameters
@ -167,18 +196,6 @@ FactorGraph::readFromLibDaiFormat (const char* fileName)
FactorGraph::~FactorGraph (void)
{
for (size_t i = 0; i < varNodes_.size(); i++) {
delete varNodes_[i];
}
for (size_t i = 0; i < facNodes_.size(); i++) {
delete facNodes_[i];
}
}
void
FactorGraph::addFactor (const Factor& factor)
{
@ -276,14 +293,88 @@ FactorGraph::print (void) const
void
FactorGraph::exportToLibDai (const char* fileName) const
{
ofstream out (fileName);
if (!out.is_open()) {
cerr << "Error: couldn't open file '" << fileName << "'." ;
return;
}
out << facNodes_.size() << endl << endl;
for (size_t i = 0; i < facNodes_.size(); i++) {
Factor f (facNodes_[i]->factor());
out << f.nrArguments() << endl;
out << Util::elementsToString (f.arguments()) << endl;
out << Util::elementsToString (f.ranges()) << endl;
VarIds args = f.arguments();
std::reverse (args.begin(), args.end());
f.reorderArguments (args);
if (Globals::logDomain) {
Util::exp (f.params());
}
out << f.size() << endl;
for (size_t j = 0; j < f.size(); j++) {
out << j << " " << f[j] << endl;
}
out << endl;
}
out.close();
}
void
FactorGraph::exportToUai (const char* fileName) const
{
ofstream out (fileName);
if (!out.is_open()) {
cerr << "Error: couldn't open file '" << fileName << "'." ;
return;
}
out << (bayesFactors_ ? "BAYES" : "MARKOV") ;
out << endl << endl;
out << varNodes_.size() << endl;
VarNodes sortedVns = varNodes_;
std::sort (sortedVns.begin(), sortedVns.end(), sortByVarId());
for (size_t i = 0; i < sortedVns.size(); i++) {
out << ((i != 0) ? " " : "") << sortedVns[i]->range();
}
out << endl << facNodes_.size() << endl;
for (size_t i = 0; i < facNodes_.size(); i++) {
VarIds args = facNodes_[i]->factor().arguments();
if (bayesFactors_) {
std::swap (args.front(), args.back());
}
out << args.size() << " " << Util::elementsToString (args) << endl;
}
out << endl;
for (size_t i = 0; i < facNodes_.size(); i++) {
Factor f = facNodes_[i]->factor();
if (bayesFactors_) {
VarIds args = f.arguments();
std::swap (args.front(), args.back());
f.reorderArguments (args);
}
Params params = f.params();
if (Globals::logDomain) {
Util::exp (params);
}
out << params.size() << endl << " " ;
out << Util::elementsToString (params) << endl << endl;
}
out.close();
}
void
FactorGraph::exportToGraphViz (const char* fileName) const
{
ofstream out (fileName);
if (!out.is_open()) {
cerr << "error: cannot open file to write at " ;
cerr << "FactorGraph::exportToDotFile()" << endl;
abort();
cerr << "Error: couldn't open file '" << fileName << "'." ;
return;
}
out << "graph \"" << fileName << "\" {" << endl;
for (size_t i = 0; i < varNodes_.size(); i++) {
@ -311,71 +402,6 @@ FactorGraph::exportToGraphViz (const char* fileName) const
void
FactorGraph::exportToUaiFormat (const char* fileName) const
{
ofstream out (fileName);
if (!out.is_open()) {
cerr << "error: cannot open file " << fileName << endl;
abort();
}
out << "MARKOV" << endl;
out << varNodes_.size() << endl;
VarNodes sortedVns = varNodes_;
std::sort (sortedVns.begin(), sortedVns.end(), sortByVarId());
for (size_t i = 0; i < sortedVns.size(); i++) {
out << ((i != 0) ? " " : "") << sortedVns[i]->range();
}
out << endl << facNodes_.size() << endl;
for (size_t i = 0; i < facNodes_.size(); i++) {
VarIds args = facNodes_[i]->factor().arguments();
out << args.size() << " " << Util::elementsToString (args) << endl;
}
out << endl;
for (size_t i = 0; i < facNodes_.size(); i++) {
Params params = facNodes_[i]->factor().params();
if (Globals::logDomain) {
Util::exp (params);
}
out << params.size() << endl << " " ;
out << Util::elementsToString (params) << endl << endl;
}
out.close();
}
void
FactorGraph::exportToLibDaiFormat (const char* fileName) const
{
ofstream out (fileName);
if (!out.is_open()) {
cerr << "error: cannot open file " << fileName << endl;
abort();
}
out << facNodes_.size() << endl << endl;
for (size_t i = 0; i < facNodes_.size(); i++) {
Factor f (facNodes_[i]->factor());
out << f.nrArguments() << endl;
out << Util::elementsToString (f.arguments()) << endl;
out << Util::elementsToString (f.ranges()) << endl;
VarIds args = f.arguments();
std::reverse (args.begin(), args.end());
f.reorderArguments (args);
if (Globals::logDomain) {
Util::exp (f.params());
}
out << f.size() << endl;
for (size_t j = 0; j < f.size(); j++) {
out << j << " " << f[j] << endl;
}
out << endl;
}
out.close();
}
void
FactorGraph::ignoreLines (std::ifstream& is) const
{

View File

@ -9,7 +9,6 @@
using namespace std;
class FacNode;
class VarNode : public Var
@ -26,9 +25,9 @@ class VarNode : public Var
const FacNodes& neighbors (void) const { return neighs_; }
private:
DISALLOW_COPY_AND_ASSIGN (VarNode);
FacNodes neighs_;
DISALLOW_COPY_AND_ASSIGN (VarNode);
};
@ -53,11 +52,11 @@ class FacNode
string getLabel (void) { return factor_.getLabel(); }
private:
DISALLOW_COPY_AND_ASSIGN (FacNode);
VarNodes neighs_;
Factor factor_;
size_t index_;
DISALLOW_COPY_AND_ASSIGN (FacNode);
};
@ -77,7 +76,7 @@ class FactorGraph
void setFactorsAsBayesian (void) { bayesFactors_ = true; }
bool bayesianFactors (void) const { return bayesFactors_ ; }
bool bayesianFactors (void) const { return bayesFactors_; }
size_t nrVarNodes (void) const { return varNodes_.size(); }
@ -107,15 +106,37 @@ class FactorGraph
void print (void) const;
void exportToLibDai (const char*) const;
void exportToUai (const char*) const;
void exportToGraphViz (const char*) const;
void exportToUaiFormat (const char*) const;
static bool exportToLibDai (void) { return exportLd_; }
void exportToLibDaiFormat (const char*) const;
static bool exportToUai (void) { return exportUai_; }
static bool exportGraphViz (void) { return exportGv_; }
static bool printFactorGraph (void) { return printFg_; }
static void enableExportToLibDai (void) { exportLd_ = true; }
static void disableExportToLibDai (void) { exportLd_ = false; }
static void enableExportToUai (void) { exportUai_ = true; }
static void disableExportToUai (void) { exportUai_ = false; }
static void enableExportToGraphViz (void) { exportGv_ = true; }
static void disableExportToGraphViz (void) { exportGv_ = false; }
static void enablePrintFactorGraph (void) { printFg_ = true; }
static void disablePrintFactorGraph (void) { printFg_ = false; }
private:
// DISALLOW_COPY_AND_ASSIGN (FactorGraph);
void ignoreLines (std::ifstream&) const;
bool containsCycle (void) const;
@ -134,6 +155,13 @@ class FactorGraph
typedef unordered_map<unsigned, VarNode*> VarMap;
VarMap varMap_;
static bool exportLd_;
static bool exportUai_;
static bool exportGv_;
static bool printFg_;
DISALLOW_ASSIGN (FactorGraph);
};

View File

@ -1,8 +1,8 @@
#include "GroundSolver.h"
#include "Util.h"
#include "VarElim.h"
#include "BeliefProp.h"
#include "CountingBp.h"
#include "VarElim.h"
#include "Util.h"
void
@ -47,7 +47,7 @@ Params
GroundSolver::getJointByConditioning (
GroundSolverType solverType,
FactorGraph fg,
const VarIds& jointVarIds) const
const VarIds& jointVarIds)
{
VarNodes jointVars;
for (size_t i = 0; i < jointVarIds.size(); i++) {

View File

@ -4,7 +4,6 @@
#include <iomanip>
#include "FactorGraph.h"
#include "Var.h"
#include "Horus.h"
@ -25,11 +24,13 @@ class GroundSolver
void printAllPosterioris (void);
Params getJointByConditioning (GroundSolverType,
FactorGraph, const VarIds& jointVarIds) const;
static Params getJointByConditioning (GroundSolverType,
FactorGraph, const VarIds& jointVarIds);
protected:
const FactorGraph& fg;
DISALLOW_COPY_AND_ASSIGN (GroundSolver);
};
#endif // HORUS_GROUNDSOLVER_H

View File

@ -2,8 +2,11 @@
#define HORUS_HISTOGRAM_H
#include <vector>
#include <ostream>
#include "Horus.h"
using namespace std;
typedef vector<unsigned> Histogram;
@ -21,7 +24,7 @@ class HistogramSet
void reset (void);
static vector<Histogram> getHistograms (unsigned ,unsigned);
static vector<Histogram> getHistograms (unsigned, unsigned);
static unsigned nrHistograms (unsigned, unsigned);
@ -39,6 +42,8 @@ class HistogramSet
unsigned size_;
Histogram hist_;
DISALLOW_COPY_AND_ASSIGN (HistogramSet);
};
#endif // HORUS_HISTOGRAM_H

View File

@ -1,30 +1,33 @@
#ifndef HORUS_HORUS_H
#define HORUS_HORUS_H
#include <limits>
#include <vector>
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
using namespace std;
#define DISALLOW_COPY(TypeName) \
TypeName(const TypeName&)
#define DISALLOW_ASSIGN(TypeName) \
void operator=(const TypeName&)
#include <vector>
#include <string>
class Var;
class Factor;
class VarNode;
class FacNode;
typedef vector<double> Params;
typedef std::vector<double> Params;
typedef unsigned VarId;
typedef vector<VarId> VarIds;
typedef vector<Var*> Vars;
typedef vector<VarNode*> VarNodes;
typedef vector<FacNode*> FacNodes;
typedef vector<Factor*> Factors;
typedef vector<string> States;
typedef vector<unsigned> Ranges;
typedef std::vector<VarId> VarIds;
typedef std::vector<Var*> Vars;
typedef std::vector<VarNode*> VarNodes;
typedef std::vector<FacNode*> FacNodes;
typedef std::vector<Factor*> Factors;
typedef std::vector<std::string> States;
typedef std::vector<unsigned> Ranges;
typedef unsigned long long ullong;
@ -69,19 +72,5 @@ const unsigned PRECISION = 6;
};
namespace BpOptions
{
enum Schedule {
SEQ_FIXED,
SEQ_RANDOM,
PARALLEL,
MAX_RESIDUAL
};
extern Schedule schedule;
extern double accuracy;
extern unsigned maxIter;
}
#endif // HORUS_HORUS_H

View File

@ -16,22 +16,39 @@ VarIds readQueryAndEvidence (FactorGraph&, int, const char* [], int);
void runSolver (const FactorGraph&, const VarIds&);
const string USAGE = "usage: ./hcli [HORUS_FLAG=VALUE] \
NETWORK_FILE [VARIABLE | OBSERVED_VARIABLE=EVIDENCE] ..." ;
const string USAGE = "usage: ./hcli [solver=hve|bp|cbp] \
[<HORUS_KEY>=<VALUE>]... <FILE> [<VAR>|<VAR>=<EVIDENCE>]... " ;
int
main (int argc, const char* argv[])
{
if (argc <= 1) {
cerr << "error: no graphical model specified" << endl;
cerr << "Error: no probabilistic graphical model was given." << endl;
cerr << USAGE << endl;
exit (0);
exit (EXIT_FAILURE);
}
int idx = readHorusFlags (argc, argv);
FactorGraph fg;
readFactorGraph (fg, argv[idx]);
VarIds queryIds = readQueryAndEvidence (fg, argc, argv, idx + 1);
if (FactorGraph::exportToLibDai()) {
fg.exportToLibDai ("model.fg");
}
if (FactorGraph::exportToUai()) {
fg.exportToUai ("model.uai");
}
if (FactorGraph::exportGraphViz()) {
fg.exportToGraphViz ("model.dot");
}
if (FactorGraph::printFactorGraph()) {
fg.print();
}
if (Globals::verbosity > 0) {
cout << "factor graph contains " ;
cout << fg.nrVarNodes() << " variables and " ;
cout << fg.nrFacNodes() << " factors " << endl;
}
runSolver (fg, queryIds);
return 0;
}
@ -51,14 +68,14 @@ readHorusFlags (int argc, const char* argv[])
string leftArg = arg.substr (0, pos);
string rightArg = arg.substr (pos + 1);
if (leftArg.empty()) {
cerr << "error: missing left argument" << endl;
cerr << "Error: missing left argument." << endl;
cerr << USAGE << endl;
exit (0);
exit (EXIT_FAILURE);
}
if (rightArg.empty()) {
cerr << "error: missing right argument" << endl;
cerr << "Error: missing right argument." << endl;
cerr << USAGE << endl;
exit (0);
exit (EXIT_FAILURE);
}
Util::setHorusFlag (leftArg, rightArg);
}
@ -77,9 +94,9 @@ readFactorGraph (FactorGraph& fg, const char* s)
} else if (extension == "fg") {
fg.readFromLibDaiFormat (fileName.c_str());
} else {
cerr << "error: the graphical model must be defined either " ;
cerr << "in a UAI or libDAI file" << endl;
exit (0);
cerr << "Error: the probabilistic graphical model must be " ;
cerr << "defined either in a UAI or libDAI file." << endl;
exit (EXIT_FAILURE);
}
}
@ -97,17 +114,17 @@ readQueryAndEvidence (
const string& arg = argv[i];
if (arg.find ('=') == std::string::npos) {
if (Util::isInteger (arg) == false) {
cerr << "error: `" << arg << "' " ;
cerr << "is not a variable id" ;
cerr << "Error: `" << arg << "' " ;
cerr << "is not a variable id." ;
cerr << endl;
exit (0);
exit (EXIT_FAILURE);
}
VarId vid = Util::stringToUnsigned (arg);
VarNode* queryVar = fg.getVarNode (vid);
if (queryVar == false) {
cerr << "error: unknow variable with id " ;
cerr << "`" << vid << "'" << endl;
exit (0);
cerr << "Error: unknow variable with id " ;
cerr << "`" << vid << "'." << endl;
exit (EXIT_FAILURE);
}
queryIds.push_back (vid);
} else {
@ -115,39 +132,38 @@ readQueryAndEvidence (
string leftArg = arg.substr (0, pos);
string rightArg = arg.substr (pos + 1);
if (leftArg.empty()) {
cerr << "error: missing left argument" << endl;
cerr << "Error: missing left argument." << endl;
cerr << USAGE << endl;
exit (0);
exit (EXIT_FAILURE);
}
if (Util::isInteger (leftArg) == false) {
cerr << "error: `" << leftArg << "' " ;
cerr << "is not a variable id" << endl ;
exit (0);
continue;
cerr << "Error: `" << leftArg << "' " ;
cerr << "is not a variable id." << endl ;
exit (EXIT_FAILURE);
}
VarId vid = Util::stringToUnsigned (leftArg);
VarNode* observedVar = fg.getVarNode (vid);
if (observedVar == false) {
cerr << "error: unknow variable with id " ;
cerr << "`" << vid << "'" << endl;
exit (0);
cerr << "Error: unknow variable with id " ;
cerr << "`" << vid << "'." << endl;
exit (EXIT_FAILURE);
}
if (rightArg.empty()) {
cerr << "error: missing right argument" << endl;
cerr << "Error: missing right argument." << endl;
cerr << USAGE << endl;
exit (0);
exit (EXIT_FAILURE);
}
if (Util::isInteger (rightArg) == false) {
cerr << "error: `" << rightArg << "' " ;
cerr << "is not a state index" << endl ;
exit (0);
cerr << "Error: `" << rightArg << "' " ;
cerr << "is not a state index." << endl ;
exit (EXIT_FAILURE);
}
unsigned stateIdx = Util::stringToUnsigned (rightArg);
if (observedVar->isValidState (stateIdx) == false) {
cerr << "error: `" << stateIdx << "' " ;
cerr << "Error: `" << stateIdx << "' " ;
cerr << "is not a valid state index for variable with id " ;
cerr << "`" << vid << "'" << endl;
exit (0);
cerr << "`" << vid << "'." << endl;
exit (EXIT_FAILURE);
}
observedVar->setEvidence (stateIdx);
}

View File

@ -108,10 +108,21 @@ createGroundNetwork (void)
evidenceList = YAP_TailOfTerm (evidenceList);
nrObservedVars ++;
}
if (FactorGraph::exportToLibDai()) {
fg->exportToLibDai ("model.fg");
}
if (FactorGraph::exportToUai()) {
fg->exportToUai ("model.uai");
}
if (FactorGraph::exportGraphViz()) {
fg->exportToGraphViz ("model.dot");
}
if (FactorGraph::printFactorGraph()) {
fg->print();
}
if (Globals::verbosity > 0) {
cout << "factor graph contains " ;
cout << fg->nrVarNodes() << " variables " ;
cout << "(" << nrObservedVars << " observed) and " ;
cout << fg->nrVarNodes() << " variables and " ;
cout << fg->nrFacNodes() << " factors " << endl;
}
YAP_Int p = (YAP_Int) (fg);
@ -200,7 +211,7 @@ runGroundSolver (void)
}
GroundSolver* solver = 0;
CountingBp::checkForIdenticalFactors = false;
CountingBp::setFindIdenticalFactorsFlag (false);
switch (Globals::groundSolver) {
case GroundSolverType::VE: solver = new VarElim (*mfg); break;
case GroundSolverType::BP: solver = new BeliefProp (*mfg); break;
@ -233,19 +244,21 @@ setParfactorsParams (void)
{
LiftedNetwork* network = (LiftedNetwork*) YAP_IntOfTerm (YAP_ARG1);
ParfactorList* pfList = network->first;
YAP_Term distList = YAP_ARG2;
YAP_Term distIdsList = YAP_ARG2;
YAP_Term paramsList = YAP_ARG3;
unordered_map<unsigned, Params> paramsMap;
while (distList != YAP_TermNil()) {
YAP_Term dist = YAP_HeadOfTerm (distList);
unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (1, dist));
while (distIdsList != YAP_TermNil()) {
unsigned distId = (unsigned) YAP_IntOfTerm (
YAP_HeadOfTerm (distIdsList));
assert (Util::contains (paramsMap, distId) == false);
paramsMap[distId] = readParameters (YAP_ArgOfTerm (2, dist));
distList = YAP_TailOfTerm (distList);
paramsMap[distId] = readParameters (YAP_HeadOfTerm (paramsList));
distIdsList = YAP_TailOfTerm (distIdsList);
paramsList = YAP_TailOfTerm (paramsList);
}
ParfactorList::iterator it = pfList->begin();
while (it != pfList->end()) {
assert (Util::contains (paramsMap, (*it)->distId()));
// (*it)->setParams (paramsMap[(*it)->distId()]);
(*it)->setParams (paramsMap[(*it)->distId()]);
++ it;
}
return TRUE;
@ -256,16 +269,17 @@ setParfactorsParams (void)
int
setFactorsParams (void)
{
return TRUE; // TODO
FactorGraph* fg = (FactorGraph*) YAP_IntOfTerm (YAP_ARG1);
YAP_Term distList = YAP_ARG2;
YAP_Term distIdsList = YAP_ARG2;
YAP_Term paramsList = YAP_ARG3;
unordered_map<unsigned, Params> paramsMap;
while (distList != YAP_TermNil()) {
YAP_Term dist = YAP_HeadOfTerm (distList);
unsigned distId = (unsigned) YAP_IntOfTerm (YAP_ArgOfTerm (1, dist));
while (distIdsList != YAP_TermNil()) {
unsigned distId = (unsigned) YAP_IntOfTerm (
YAP_HeadOfTerm (distIdsList));
assert (Util::contains (paramsMap, distId) == false);
paramsMap[distId] = readParameters (YAP_ArgOfTerm (2, dist));
distList = YAP_TailOfTerm (distList);
paramsMap[distId] = readParameters (YAP_HeadOfTerm (paramsList));
distIdsList = YAP_TailOfTerm (distIdsList);
paramsList = YAP_TailOfTerm (paramsList);
}
const FacNodes& facNodes = fg->facNodes();
for (size_t i = 0; i < facNodes.size(); i++) {
@ -317,11 +331,11 @@ setHorusFlag (void)
stringstream ss;
ss << (int) YAP_IntOfTerm (YAP_ARG2);
ss >> value;
} else if (key == "accuracy") {
} else if (key == "bp_accuracy") {
stringstream ss;
ss << (float) YAP_FloatOfTerm (YAP_ARG2);
ss >> value;
} else if (key == "max_iter") {
} else if (key == "bp_max_iter") {
stringstream ss;
ss << (int) YAP_IntOfTerm (YAP_ARG2);
ss >> value;
@ -420,8 +434,8 @@ readParfactor (YAP_Term pfTerm)
for (unsigned i = 1; i <= arity; i++) {
YAP_Term ti = YAP_ArgOfTerm (i, term);
if (YAP_IsAtomTerm (ti) == false) {
cerr << "error: constraint has free variables" << endl;
abort();
cerr << "Error: the constraint contains free variables." << endl;
exit (EXIT_FAILURE);
}
string name ((char*) YAP_AtomName (YAP_AtomOfTerm (ti)));
tuple[i - 1] = LiftedUtils::getSymbol (name);
@ -534,15 +548,34 @@ fillAnswersPrologList (vector<Params>& results)
extern "C" void
init_predicates (void)
{
YAP_UserCPredicate ("cpp_create_lifted_network", createLiftedNetwork, 3);
YAP_UserCPredicate ("cpp_create_ground_network", createGroundNetwork, 4);
YAP_UserCPredicate ("cpp_run_lifted_solver", runLiftedSolver, 3);
YAP_UserCPredicate ("cpp_run_ground_solver", runGroundSolver, 3);
YAP_UserCPredicate ("cpp_set_parfactors_params", setParfactorsParams, 2);
YAP_UserCPredicate ("cpp_cpp_set_factors_params", setFactorsParams, 2);
YAP_UserCPredicate ("cpp_set_vars_information", setVarsInformation, 2);
YAP_UserCPredicate ("cpp_set_horus_flag", setHorusFlag, 2);
YAP_UserCPredicate ("cpp_free_lifted_network", freeLiftedNetwork, 1);
YAP_UserCPredicate ("cpp_free_ground_network", freeGroundNetwork, 1);
YAP_UserCPredicate ("cpp_create_lifted_network",
createLiftedNetwork, 3);
YAP_UserCPredicate ("cpp_create_ground_network",
createGroundNetwork, 4);
YAP_UserCPredicate ("cpp_run_lifted_solver",
runLiftedSolver, 3);
YAP_UserCPredicate ("cpp_run_ground_solver",
runGroundSolver, 3);
YAP_UserCPredicate ("cpp_set_parfactors_params",
setParfactorsParams, 3);
YAP_UserCPredicate ("cpp_set_factors_params",
setFactorsParams, 3);
YAP_UserCPredicate ("cpp_set_vars_information",
setVarsInformation, 2);
YAP_UserCPredicate ("cpp_set_horus_flag",
setHorusFlag, 2);
YAP_UserCPredicate ("cpp_free_lifted_network",
freeLiftedNetwork, 1);
YAP_UserCPredicate ("cpp_free_ground_network",
freeGroundNetwork, 1);
}

View File

@ -120,6 +120,8 @@ class Indexer
const Ranges& ranges_;
size_t size_;
vector<size_t> offsets_;
DISALLOW_COPY_AND_ASSIGN (Indexer);
};
@ -239,6 +241,8 @@ class MapIndexer
const Ranges& ranges_;
bool valid_;
vector<size_t> offsets_;
DISALLOW_COPY_AND_ASSIGN (MapIndexer);
};

View File

@ -1,7 +1,7 @@
#include "LiftedBp.h"
#include "LiftedOperations.h"
#include "WeightedBp.h"
#include "FactorGraph.h"
#include "LiftedOperations.h"
LiftedBp::LiftedBp (const ParfactorList& parfactorList)
@ -62,16 +62,15 @@ LiftedBp::printSolverFlags (void) const
{
stringstream ss;
ss << "lifted bp [" ;
ss << "schedule=" ;
typedef BpOptions::Schedule Sch;
switch (BpOptions::schedule) {
case Sch::SEQ_FIXED: ss << "seq_fixed"; break;
case Sch::SEQ_RANDOM: ss << "seq_random"; break;
case Sch::PARALLEL: ss << "parallel"; break;
case Sch::MAX_RESIDUAL: ss << "max_residual"; break;
ss << "bp_msg_schedule=" ;
switch (WeightedBp::msgSchedule()) {
case MsgSchedule::SEQ_FIXED: ss << "seq_fixed"; break;
case MsgSchedule::SEQ_RANDOM: ss << "seq_random"; break;
case MsgSchedule::PARALLEL: ss << "parallel"; break;
case MsgSchedule::MAX_RESIDUAL: ss << "max_residual"; break;
}
ss << ",max_iter=" << BpOptions::maxIter;
ss << ",accuracy=" << BpOptions::accuracy;
ss << ",bp_max_iter=" << WeightedBp::maxIterations();
ss << ",bp_accuracy=" << WeightedBp::accuracy();
ss << ",log_domain=" << Util::toString (Globals::logDomain);
ss << "]" ;
cout << ss.str() << endl;
@ -182,7 +181,7 @@ LiftedBp::rangeOfGround (const Ground& gr)
}
++ it;
}
return std::numeric_limits<unsigned>::max();
return Util::maxUnsigned();
}

View File

@ -37,6 +37,8 @@ class LiftedBp : public LiftedSolver
WeightedBp* solver_;
FactorGraph* fg_;
DISALLOW_COPY_AND_ASSIGN (LiftedBp);
};
#endif // HORUS_LIFTEDBP_H

File diff suppressed because it is too large Load Diff

View File

@ -1,262 +0,0 @@
#ifndef HORUS_LIFTEDCIRCUIT_H
#define HORUS_LIFTEDCIRCUIT_H
#include <stack>
#include "LiftedWCNF.h"
enum CircuitNodeType {
OR_NODE,
AND_NODE,
SET_OR_NODE,
SET_AND_NODE,
INC_EXC_NODE,
LEAF_NODE,
SMOOTH_NODE,
TRUE_NODE,
COMPILATION_FAILED_NODE
};
class CircuitNode
{
public:
CircuitNode (void) { }
virtual double weight (void) const = 0;
};
class OrNode : public CircuitNode
{
public:
OrNode (void) : CircuitNode(), leftBranch_(0), rightBranch_(0) { }
CircuitNode** leftBranch (void) { return &leftBranch_; }
CircuitNode** rightBranch (void) { return &rightBranch_; }
double weight (void) const;
private:
CircuitNode* leftBranch_;
CircuitNode* rightBranch_;
};
class AndNode : public CircuitNode
{
public:
AndNode (void) : CircuitNode(), leftBranch_(0), rightBranch_(0) { }
AndNode (CircuitNode* leftBranch, CircuitNode* rightBranch)
: CircuitNode(), leftBranch_(leftBranch), rightBranch_(rightBranch) { }
CircuitNode** leftBranch (void) { return &leftBranch_; }
CircuitNode** rightBranch (void) { return &rightBranch_; }
double weight (void) const;
private:
CircuitNode* leftBranch_;
CircuitNode* rightBranch_;
};
class SetOrNode : public CircuitNode
{
public:
SetOrNode (unsigned nrGroundings)
: CircuitNode(), follow_(0), nrGroundings_(nrGroundings) { }
CircuitNode** follow (void) { return &follow_; }
static unsigned nrPositives (void) { return nrPos_; }
static unsigned nrNegatives (void) { return nrNeg_; }
static bool isSet (void) { return nrPos_ >= 0; }
double weight (void) const;
private:
CircuitNode* follow_;
unsigned nrGroundings_;
static int nrPos_;
static int nrNeg_;
};
class SetAndNode : public CircuitNode
{
public:
SetAndNode (unsigned nrGroundings)
: CircuitNode(), follow_(0), nrGroundings_(nrGroundings) { }
CircuitNode** follow (void) { return &follow_; }
double weight (void) const;
private:
CircuitNode* follow_;
unsigned nrGroundings_;
};
class IncExcNode : public CircuitNode
{
public:
IncExcNode (void)
: CircuitNode(), plus1Branch_(0), plus2Branch_(0), minusBranch_(0) { }
CircuitNode** plus1Branch (void) { return &plus1Branch_; }
CircuitNode** plus2Branch (void) { return &plus2Branch_; }
CircuitNode** minusBranch (void) { return &minusBranch_; }
double weight (void) const;
private:
CircuitNode* plus1Branch_;
CircuitNode* plus2Branch_;
CircuitNode* minusBranch_;
};
class LeafNode : public CircuitNode
{
public:
LeafNode (Clause* clause, const LiftedWCNF& lwcnf)
: CircuitNode(), clause_(clause), lwcnf_(lwcnf) { }
const Clause* clause (void) const { return clause_; }
Clause* clause (void) { return clause_; }
double weight (void) const;
private:
Clause* clause_;
const LiftedWCNF& lwcnf_;
};
class SmoothNode : public CircuitNode
{
public:
SmoothNode (const Clauses& clauses, const LiftedWCNF& lwcnf)
: CircuitNode(), clauses_(clauses), lwcnf_(lwcnf) { }
const Clauses& clauses (void) const { return clauses_; }
Clauses clauses (void) { return clauses_; }
double weight (void) const;
private:
Clauses clauses_;
const LiftedWCNF& lwcnf_;
};
class TrueNode : public CircuitNode
{
public:
TrueNode (void) : CircuitNode() { }
double weight (void) const;
};
class CompilationFailedNode : public CircuitNode
{
public:
CompilationFailedNode (void) : CircuitNode() { }
double weight (void) const;
};
class LiftedCircuit
{
public:
LiftedCircuit (const LiftedWCNF* lwcnf);
bool isCompilationSucceeded (void) const;
double getWeightedModelCount (void) const;
void exportToGraphViz (const char*);
private:
void compile (CircuitNode** follow, Clauses& clauses);
bool tryUnitPropagation (CircuitNode** follow, Clauses& clauses);
bool tryIndependence (CircuitNode** follow, Clauses& clauses);
bool tryShannonDecomp (CircuitNode** follow, Clauses& clauses);
bool tryInclusionExclusion (CircuitNode** follow, Clauses& clauses);
bool tryIndepPartialGrounding (CircuitNode** follow, Clauses& clauses);
bool tryIndepPartialGroundingAux (Clauses& clauses, ConstraintTree& ct,
LogVars& rootLogVars);
bool tryAtomCounting (CircuitNode** follow, Clauses& clauses);
void shatterCountedLogVars (Clauses& clauses);
bool shatterCountedLogVarsAux (Clauses& clauses);
bool shatterCountedLogVarsAux (Clauses& clauses, size_t idx1, size_t idx2);
bool independentClause (Clause& clause, Clauses& otherClauses) const;
bool independentLiteral (const Literal& lit,
const Literals& otherLits) const;
LitLvTypesSet smoothCircuit (CircuitNode* node);
void createSmoothNode (const LitLvTypesSet& lids,
CircuitNode** prev);
vector<LogVarTypes> getAllPossibleTypes (unsigned nrLogVars) const;
bool containsTypes (const LogVarTypes& typesA,
const LogVarTypes& typesB) const;
CircuitNodeType getCircuitNodeType (const CircuitNode* node) const;
void exportToGraphViz (CircuitNode* node, ofstream&);
void printClauses (CircuitNode* node, ofstream&,
string extraOptions = "");
string escapeNode (const CircuitNode* node) const;
string getExplanationString (CircuitNode* node);
CircuitNode* root_;
const LiftedWCNF* lwcnf_;
Clauses backupClauses_;
unordered_map<CircuitNode*, Clauses> originClausesMap_;
unordered_map<CircuitNode*, string> explanationMap_;
bool compilationSucceeded_;
};
#endif // HORUS_LIFTEDCIRCUIT_H

File diff suppressed because it is too large Load Diff

View File

@ -2,10 +2,280 @@
#define HORUS_LIFTEDKC_H
#include "LiftedSolver.h"
#include "LiftedWCNF.h"
#include "ParfactorList.h"
class LiftedWCNF;
class LiftedCircuit;
enum CircuitNodeType {
OR_NODE,
AND_NODE,
SET_OR_NODE,
SET_AND_NODE,
INC_EXC_NODE,
LEAF_NODE,
SMOOTH_NODE,
TRUE_NODE,
COMPILATION_FAILED_NODE
};
class CircuitNode
{
public:
CircuitNode (void) { }
virtual ~CircuitNode (void) { }
virtual double weight (void) const = 0;
};
class OrNode : public CircuitNode
{
public:
OrNode (void) : CircuitNode(), leftBranch_(0), rightBranch_(0) { }
~OrNode (void);
CircuitNode** leftBranch (void) { return &leftBranch_; }
CircuitNode** rightBranch (void) { return &rightBranch_; }
double weight (void) const;
private:
CircuitNode* leftBranch_;
CircuitNode* rightBranch_;
};
class AndNode : public CircuitNode
{
public:
AndNode (void) : CircuitNode(), leftBranch_(0), rightBranch_(0) { }
AndNode (CircuitNode* leftBranch, CircuitNode* rightBranch)
: CircuitNode(), leftBranch_(leftBranch), rightBranch_(rightBranch) { }
~AndNode (void);
CircuitNode** leftBranch (void) { return &leftBranch_; }
CircuitNode** rightBranch (void) { return &rightBranch_; }
double weight (void) const;
private:
CircuitNode* leftBranch_;
CircuitNode* rightBranch_;
};
class SetOrNode : public CircuitNode
{
public:
SetOrNode (unsigned nrGroundings)
: CircuitNode(), follow_(0), nrGroundings_(nrGroundings) { }
~SetOrNode (void);
CircuitNode** follow (void) { return &follow_; }
static unsigned nrPositives (void) { return nrPos_; }
static unsigned nrNegatives (void) { return nrNeg_; }
static bool isSet (void) { return nrPos_ >= 0; }
double weight (void) const;
private:
CircuitNode* follow_;
unsigned nrGroundings_;
static int nrPos_;
static int nrNeg_;
};
class SetAndNode : public CircuitNode
{
public:
SetAndNode (unsigned nrGroundings)
: CircuitNode(), follow_(0), nrGroundings_(nrGroundings) { }
~SetAndNode (void);
CircuitNode** follow (void) { return &follow_; }
double weight (void) const;
private:
CircuitNode* follow_;
unsigned nrGroundings_;
};
class IncExcNode : public CircuitNode
{
public:
IncExcNode (void)
: CircuitNode(), plus1Branch_(0), plus2Branch_(0), minusBranch_(0) { }
~IncExcNode (void);
CircuitNode** plus1Branch (void) { return &plus1Branch_; }
CircuitNode** plus2Branch (void) { return &plus2Branch_; }
CircuitNode** minusBranch (void) { return &minusBranch_; }
double weight (void) const;
private:
CircuitNode* plus1Branch_;
CircuitNode* plus2Branch_;
CircuitNode* minusBranch_;
};
class LeafNode : public CircuitNode
{
public:
LeafNode (Clause* clause, const LiftedWCNF& lwcnf)
: CircuitNode(), clause_(clause), lwcnf_(lwcnf) { }
~LeafNode (void);
const Clause* clause (void) const { return clause_; }
Clause* clause (void) { return clause_; }
double weight (void) const;
private:
Clause* clause_;
const LiftedWCNF& lwcnf_;
};
class SmoothNode : public CircuitNode
{
public:
SmoothNode (const Clauses& clauses, const LiftedWCNF& lwcnf)
: CircuitNode(), clauses_(clauses), lwcnf_(lwcnf) { }
~SmoothNode (void);
const Clauses& clauses (void) const { return clauses_; }
Clauses clauses (void) { return clauses_; }
double weight (void) const;
private:
Clauses clauses_;
const LiftedWCNF& lwcnf_;
};
class TrueNode : public CircuitNode
{
public:
TrueNode (void) : CircuitNode() { }
double weight (void) const;
};
class CompilationFailedNode : public CircuitNode
{
public:
CompilationFailedNode (void) : CircuitNode() { }
double weight (void) const;
};
class LiftedCircuit
{
public:
LiftedCircuit (const LiftedWCNF* lwcnf);
~LiftedCircuit (void);
bool isCompilationSucceeded (void) const;
double getWeightedModelCount (void) const;
void exportToGraphViz (const char*);
private:
void compile (CircuitNode** follow, Clauses& clauses);
bool tryUnitPropagation (CircuitNode** follow, Clauses& clauses);
bool tryIndependence (CircuitNode** follow, Clauses& clauses);
bool tryShannonDecomp (CircuitNode** follow, Clauses& clauses);
bool tryInclusionExclusion (CircuitNode** follow, Clauses& clauses);
bool tryIndepPartialGrounding (CircuitNode** follow, Clauses& clauses);
bool tryIndepPartialGroundingAux (Clauses& clauses, ConstraintTree& ct,
LogVars& rootLogVars);
bool tryAtomCounting (CircuitNode** follow, Clauses& clauses);
void shatterCountedLogVars (Clauses& clauses);
bool shatterCountedLogVarsAux (Clauses& clauses);
bool shatterCountedLogVarsAux (Clauses& clauses, size_t idx1, size_t idx2);
bool independentClause (Clause& clause, Clauses& otherClauses) const;
bool independentLiteral (const Literal& lit,
const Literals& otherLits) const;
LitLvTypesSet smoothCircuit (CircuitNode* node);
void createSmoothNode (const LitLvTypesSet& lids,
CircuitNode** prev);
vector<LogVarTypes> getAllPossibleTypes (unsigned nrLogVars) const;
bool containsTypes (const LogVarTypes& typesA,
const LogVarTypes& typesB) const;
CircuitNodeType getCircuitNodeType (const CircuitNode* node) const;
void exportToGraphViz (CircuitNode* node, ofstream&);
void printClauses (CircuitNode* node, ofstream&,
string extraOptions = "");
string escapeNode (const CircuitNode* node) const;
string getExplanationString (CircuitNode* node);
CircuitNode* root_;
const LiftedWCNF* lwcnf_;
bool compilationSucceeded_;
Clauses backupClauses_;
unordered_map<CircuitNode*, Clauses> originClausesMap_;
unordered_map<CircuitNode*, string> explanationMap_;
DISALLOW_COPY_AND_ASSIGN (LiftedCircuit);
};
class LiftedKc : public LiftedSolver
@ -24,6 +294,8 @@ class LiftedKc : public LiftedSolver
LiftedWCNF* lwcnf_;
LiftedCircuit* circuit_;
ParfactorList pfList_;
DISALLOW_COPY_AND_ASSIGN (LiftedKc);
};
#endif // HORUS_LIFTEDKC_H

View File

@ -35,9 +35,9 @@ LiftedOperations::shatterAgainstQuery (
}
}
if (found == false) {
cerr << "error: could not find a parfactor with ground " ;
cerr << "`" << query[i] << "'" << endl;
exit (0);
cerr << "Error: could not find a parfactor with ground " ;
cerr << "`" << query[i] << "'." << endl;
exit (EXIT_FAILURE);
}
pfList.add (newPfs);
}
@ -65,7 +65,7 @@ LiftedOperations::runWeakBayesBall (
ParfactorList::iterator it = pfList.begin();
while (it != pfList.end()) {
PrvGroup group = (*it)->findGroup (query[i]);
if (group != numeric_limits<PrvGroup>::max()) {
if (group != std::numeric_limits<PrvGroup>::max()) {
todo.push (group);
done.insert (group);
break;
@ -128,7 +128,7 @@ LiftedOperations::absorveEvidence (
it = pfList.remove (it);
Parfactors absorvedPfs = absorve (obsFormulas[i], pf);
if (absorvedPfs.empty() == false) {
if (absorvedPfs.size() == 1 && absorvedPfs[0] == 0) {
if (absorvedPfs.size() == 1 && !absorvedPfs[0]) {
// just remove pf;
} else {
Util::addToVector (newPfs, absorvedPfs);

View File

@ -21,6 +21,9 @@ class LiftedOperations
private:
static Parfactors absorve (ObservedFormula&, Parfactor*);
DISALLOW_COPY_AND_ASSIGN (LiftedOperations);
};
#endif // HORUS_LIFTEDOPERATIONS_H

View File

@ -21,6 +21,9 @@ class LiftedSolver
protected:
const ParfactorList& parfactorList;
private:
DISALLOW_COPY_AND_ASSIGN (LiftedSolver);
};
#endif // HORUS_LIFTEDSOLVER_H

View File

@ -1,6 +1,5 @@
#include <cassert>
#include <algorithm>
#include <iostream>
#include <sstream>

View File

@ -1,12 +1,11 @@
#ifndef HORUS_LIFTEDUTILS_H
#define HORUS_LIFTEDUTILS_H
#include <limits>
#include <string>
#include <vector>
#include <unordered_map>
#include "TinySet.h"
#include "Util.h"
@ -107,7 +106,7 @@ class Ground
size_t arity (void) const { return args_.size(); }
bool isAtom (void) const { return args_.size() == 0; }
bool isAtom (void) const { return args_.empty(); }
friend ostream& operator<< (ostream &os, const Ground& gr);
@ -161,6 +160,5 @@ class Substitution
};
#endif // HORUS_LIFTEDUTILS_H

View File

@ -1,4 +1,5 @@
#include <algorithm>
#include <set>
#include "LiftedVe.h"
@ -710,7 +711,7 @@ LiftedVe::getBestOperation (const Grounds& query)
validOps = LiftedOperator::getValidOps (pfList_, query);
for (size_t i = 0; i < validOps.size(); i++) {
double cost = validOps[i]->getLogCost();
if ((bestOp == 0) || (cost < bestCost)) {
if (!bestOp || cost < bestCost) {
bestOp = validOps[i];
bestCost = cost;
}

View File

@ -23,6 +23,9 @@ class LiftedOperator
static vector<ParfactorList::iterator> getParfactorsWithGroup (
ParfactorList&, PrvGroup group);
private:
DISALLOW_ASSIGN (LiftedOperator);
};
@ -48,6 +51,8 @@ class ProductOperator : public LiftedOperator
ParfactorList::iterator g1_;
ParfactorList::iterator g2_;
ParfactorList& pfList_;
DISALLOW_COPY_AND_ASSIGN (ProductOperator);
};
@ -74,6 +79,8 @@ class SumOutOperator : public LiftedOperator
PrvGroup group_;
ParfactorList& pfList_;
DISALLOW_COPY_AND_ASSIGN (SumOutOperator);
};
@ -101,6 +108,8 @@ class CountingOperator : public LiftedOperator
ParfactorList::iterator pfIter_;
LogVar X_;
ParfactorList& pfList_;
DISALLOW_COPY_AND_ASSIGN (CountingOperator);
};
@ -128,6 +137,8 @@ class GroundOperator : public LiftedOperator
PrvGroup group_;
unsigned lvIndex_;
ParfactorList& pfList_;
DISALLOW_COPY_AND_ASSIGN (GroundOperator);
};
@ -149,6 +160,8 @@ class LiftedVe : public LiftedSolver
ParfactorList pfList_;
double largestCost_;
DISALLOW_COPY_AND_ASSIGN (LiftedVe);
};
#endif // HORUS_LIFTEDVE_H

View File

@ -3,11 +3,10 @@
#include "Indexer.h"
bool
Literal::isGround (ConstraintTree constr, LogVarSet ipgLogVars) const
{
if (logVars_.size() == 0) {
if (logVars_.empty()) {
return true;
}
LogVarSet lvs (logVars_);
@ -327,6 +326,16 @@ Clause::printClauses (const Clauses& clauses)
void
Clause::deleteClauses (Clauses& clauses)
{
for (size_t i = 0; i < clauses.size(); i++) {
delete clauses[i];
}
}
std::ostream&
operator<< (ostream &os, const Clause& clause)
{
@ -445,7 +454,7 @@ LiftedWCNF::LiftedWCNF (const ParfactorList& pfList)
LiftedWCNF::~LiftedWCNF (void)
{
Clause::deleteClauses (clauses_);
}

View File

@ -1,15 +1,14 @@
#ifndef HORUS_LIFTEDWCNF_H
#define HORUS_LIFTEDWCNF_H
#include <unordered_map>
#include "ParfactorList.h"
using namespace std;
typedef long LiteralId;
class ConstraintTree;
enum LogVarType
{
FULL_LV,
@ -17,10 +16,10 @@ enum LogVarType
NEG_LV
};
typedef long LiteralId;
typedef vector<LogVarType> LogVarTypes;
class Literal
{
public:
@ -137,6 +136,8 @@ class Clause
static void printClauses (const vector<Clause*>& clauses);
static void deleteClauses (vector<Clause*>& clauses);
friend std::ostream& operator<< (ostream &os, const Clause& clause);
private:
@ -147,6 +148,8 @@ class Clause
LogVarSet posCountedLvs_;
LogVarSet negCountedLvs_;
ConstraintTree constr_;
DISALLOW_ASSIGN (Clause);
};
typedef vector<Clause*> Clauses;
@ -219,7 +222,6 @@ class LiftedWCNF
void printClauses (void) const;
private:
LiteralId getLiteralId (PrvGroup prvGroup, unsigned range);
void addIndicatorClauses (const ParfactorList& pfList);
@ -231,6 +233,8 @@ class LiftedWCNF
const ParfactorList& pfList_;
unordered_map<PrvGroup, vector<LiteralId>> map_;
unordered_map<LiteralId, std::pair<double,double>> weights_;
DISALLOW_COPY_AND_ASSIGN (LiftedWCNF);
};
#endif // HORUS_LIFTEDWCNF_H

View File

@ -23,10 +23,10 @@ CC=@CC@
CXX=@CXX@
# normal
#CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../.. -I$(srcdir)/../../../include @CPPFLAGS@ -DNDEBUG
CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../.. -I$(srcdir)/../../../include @CPPFLAGS@ -DNDEBUG
# debug
CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../.. -I$(srcdir)/../../../include @CPPFLAGS@ -g -O0 -Wextra
#CXXFLAGS= -std=c++0x @SHLIB_CXXFLAGS@ $(YAP_EXTRAS) $(DEFS) -D_YAP_NOT_INSTALLED_=1 -I$(srcdir) -I../../.. -I$(srcdir)/../../../include @CPPFLAGS@ -g -O0 -Wextra
#
@ -43,6 +43,7 @@ SO=@SO@
#4.1VPATH=@srcdir@:@srcdir@/OPTYap
CWD=$(PWD)
HCLI = $(srcdir)/hcli
HEADERS = \
$(srcdir)/BayesBall.h \
@ -57,7 +58,6 @@ HEADERS = \
$(srcdir)/Horus.h \
$(srcdir)/Indexer.h \
$(srcdir)/LiftedBp.h \
$(srcdir)/LiftedCircuit.h \
$(srcdir)/LiftedKc.h \
$(srcdir)/LiftedOperations.h \
$(srcdir)/LiftedSolver.h \
@ -87,7 +87,6 @@ CPP_SOURCES = \
$(srcdir)/HorusCli.cpp \
$(srcdir)/HorusYap.cpp \
$(srcdir)/LiftedBp.cpp \
$(srcdir)/LiftedCircuit.cpp \
$(srcdir)/LiftedKc.cpp \
$(srcdir)/LiftedOperations.cpp \
$(srcdir)/LiftedUtils.cpp \
@ -114,7 +113,6 @@ OBJS = \
Histogram.o \
HorusYap.o \
LiftedBp.o \
LiftedCircuit.o \
LiftedKc.o \
LiftedOperations.o \
LiftedUtils.o \
@ -159,15 +157,16 @@ all: $(SOBJS) hcli
hcli: $(HCLI_OBJS)
$(CXX) -o hcli $(HCLI_OBJS)
$(CXX) -o $(HCLI) $(HCLI_OBJS)
install: all
$(INSTALL_PROGRAM) $(SOBJS) $(DESTDIR)$(YAPLIBDIR)
$(INSTALL_PROGRAM) $(HCLI) $(DESTDIR)$(BINDIR)
clean:
rm -f *.o *~ $(OBJS) $(SOBJS) *.BAK hcli
rm -f *.o *~ $(OBJS) $(SOBJS) $(HCLI) *.BAK
erase_dots:

View File

@ -1,4 +1,3 @@
#include "Parfactor.h"
#include "Histogram.h"
#include "Indexer.h"
@ -26,7 +25,24 @@ Parfactor::Parfactor (
}
}
}
LogVar newLv = logVars.size();
constr_ = new ConstraintTree (logVars, tuples);
// Change formulas like f(X,X), X in {(p1),(p2),...}
// to be like f(X,Y), (X,Y) in {(p1,p1),(p2,p2),...}.
// This will simplify shattering on the constraint tree.
for (size_t i = 0; i < args_.size(); i++) {
LogVarSet lvSet;
LogVars& lvs = args_[i].logVars();
for (size_t j = 0; j < lvs.size(); j++) {
if (lvSet.contains (lvs[j]) == false) {
lvSet |= lvs[j];
} else {
constr_->cloneLogVar (lvs[j], newLv);
lvs[j] = newLv;
++ newLv;
}
}
}
assert (params_.size() == Util::sizeExpected (ranges_));
}
@ -426,7 +442,7 @@ Parfactor::findGroup (const Ground& ground) const
{
size_t idx = indexOfGround (ground);
return idx == args_.size()
? numeric_limits<PrvGroup>::max()
? std::numeric_limits<PrvGroup>::max()
: args_[idx].group();
}
@ -435,7 +451,7 @@ Parfactor::findGroup (const Ground& ground) const
bool
Parfactor::containsGround (const Ground& ground) const
{
return findGroup (ground) != numeric_limits<PrvGroup>::max();
return findGroup (ground) != std::numeric_limits<PrvGroup>::max();
}
@ -672,9 +688,9 @@ Parfactor::expandPotential (
{
ullong newSize = (params_.size() / ranges_[fIdx]) * newRange;
if (newSize > params_.max_size()) {
cerr << "error: an overflow occurred when performing expansion" ;
cerr << "Error: an overflow occurred when performing expansion." ;
cerr << endl;
abort();
exit (EXIT_FAILURE);
}
Params backup = params_;

View File

@ -1,15 +1,12 @@
#ifndef HORUS_PARFACTOR_H
#define HORUS_PARFACTOR_H
#include <list>
#include <unordered_map>
#include "Factor.h"
#include "ProbFormula.h"
#include "ConstraintTree.h"
#include "LiftedUtils.h"
#include "Horus.h"
#include "Factor.h"
class Parfactor : public TFactor<ProbFormula>
{
@ -99,7 +96,6 @@ class Parfactor : public TFactor<ProbFormula>
static bool canMultiply (Parfactor*, Parfactor*);
private:
void simplifyCountingFormulas (size_t fIdx);
void simplifyParfactor (size_t fIdx1, size_t fIdx2);
@ -116,9 +112,9 @@ class Parfactor : public TFactor<ProbFormula>
ConstraintTree* constr_;
DISALLOW_ASSIGN (Parfactor);
};
typedef vector<Parfactor*> Parfactors;
#endif // HORUS_PARFACTOR_H

View File

@ -1,5 +1,7 @@
#include <cassert>
#include <queue>
#include "ParfactorList.h"
@ -334,9 +336,9 @@ ParfactorList::shatterAgainstMySelf (
ProbFormula& f1 = g->argument (fIdx1);
ProbFormula& f2 = g->argument (fIdx2);
if (f1.isAtom()) {
cerr << "error: a ground occurs twice in a parfactor" << endl;
cerr << "Error: a ground occurs twice in the same parfactor." << endl;
cerr << endl;
abort();
exit (EXIT_FAILURE);
}
assert (g->constr()->empty() == false);
ConstraintTree ctCopy (*g->constr());
@ -412,7 +414,7 @@ ParfactorList::shatter (Parfactor* g1, Parfactor* g2)
{
ProbFormulas& formulas1 = g1->arguments();
ProbFormulas& formulas2 = g2->arguments();
assert (g1 != 0 && g2 != 0 && g1 != g2);
assert (g1 && g2 && g1 != g2);
for (size_t i = 0; i < formulas1.size(); i++) {
for (size_t j = 0; j < formulas2.size(); j++) {
if (formulas1[i].sameSkeletonAs (formulas2[j])) {

View File

@ -2,7 +2,6 @@
#define HORUS_PARFACTORLIST_H
#include <list>
#include <queue>
#include "Parfactor.h"
#include "ProbFormula.h"
@ -11,6 +10,8 @@
using namespace std;
class Parfactor;
class ParfactorList
{
public:
@ -60,7 +61,6 @@ class ParfactorList
ParfactorList& operator= (const ParfactorList& pfList);
private:
bool isShattered (const Parfactor*) const;
bool isShattered (const Parfactor*, const Parfactor*) const;

View File

@ -40,7 +40,7 @@ ProbFormula::indexOf (LogVar X) const
bool
ProbFormula::isAtom (void) const
{
return logVars_.size() == 0;
return logVars_.empty();
}
@ -92,6 +92,7 @@ ProbFormula::rename (LogVar oldName, LogVar newName)
}
bool operator== (const ProbFormula& f1, const ProbFormula& f2)
{
return f1.group_ == f2.group_ &&
@ -124,7 +125,7 @@ PrvGroup
ProbFormula::getNewGroup (void)
{
freeGroup_ ++;
assert (freeGroup_ != numeric_limits<PrvGroup>::max());
assert (freeGroup_ != std::numeric_limits<PrvGroup>::max());
return freeGroup_;
}

View File

@ -14,10 +14,11 @@ class ProbFormula
public:
ProbFormula (Symbol f, const LogVars& lvs, unsigned range)
: functor_(f), logVars_(lvs), range_(range),
countedLogVar_(), group_(numeric_limits<PrvGroup>::max()) { }
countedLogVar_(), group_(std::numeric_limits<PrvGroup>::max()) { }
ProbFormula (Symbol f, unsigned r)
: functor_(f), range_(r), group_(numeric_limits<PrvGroup>::max()) { }
: functor_(f), range_(r),
group_(std::numeric_limits<PrvGroup>::max()) { }
Symbol functor (void) const { return functor_; }

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