:wMerge ssh://ssh.dcc.fc.up.pt:31064/home/vsc/yap

This commit is contained in:
Vitor Santos Costa 2018-12-14 10:43:24 +00:00
commit e66c3ab7cc
29 changed files with 875 additions and 4130 deletions

View File

@ -2106,45 +2106,42 @@ X_API void YAP_ClearExceptions(void) {
X_API int YAP_InitConsult(int mode, const char *fname, char **full,
int *osnop) {
CACHE_REGS
int sno;
BACKUP_MACHINE_REGS();
const char *fl = NULL;
int lvl = push_text_stack();
if (mode == YAP_BOOT_MODE) {
mode = YAP_CONSULT_MODE;
}
if (fname == NULL || fname[0] == '\0') {
fl = Yap_BOOTFILE;
}
if (fname) {
fl = Yap_AbsoluteFile(fname, true);
if (!fl || !fl[0]) {
pop_text_stack(lvl);
*full = NULL;
return -1;
} else {
*full = pop_output_text_stack(lvl, fl);
CACHE_REGS
int sno;
BACKUP_MACHINE_REGS();
const char *fl = NULL;
if (mode == YAP_BOOT_MODE) {
mode = YAP_CONSULT_MODE;
}
} else {
pop_text_stack(lvl);
if (fname == NULL || fname[0] == '\0') {
fl = Yap_BOOTFILE;
}
if (!fname || !(fl = Yap_AbsoluteFile(fname, true)) || !fl[0]) {
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "failed ABSOLUTEFN %s ", fl);
*full = NULL;
return -1;
}
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "done init_ consult %s ",fl);
lvl = push_text_stack();
int lvl = push_text_stack();
char *d = Malloc(strlen(fl) + 1);
strcpy(d, fl);
bool consulted = (mode == YAP_CONSULT_MODE);
Term tat = MkAtomTerm(Yap_LookupAtom(d));
sno = Yap_OpenStream(tat, "r", MkAtomTerm(Yap_LookupAtom(fname)),
LOCAL_encoding);
if (sno < 0 || !Yap_ChDir(dirname((char *)d))) {
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "OpenStream got %d ",sno);
pop_text_stack(lvl);
if (sno < 0 || !Yap_ChDir(dirname((char *)d))) {
*full = NULL;
return -1;
}
LOCAL_PrologMode = UserMode;
Yap_init_consult(consulted, pop_output_text_stack__(lvl, fl));
*full = pop_output_text_stack__(lvl, fl);
Yap_init_consult(consulted,*full);
RECOVER_MACHINE_REGS();
UNLOCK(GLOBAL_Stream[sno].streamlock);
return sno;

View File

@ -153,22 +153,25 @@ const char *Yap_BINDIR, *Yap_ROOTDIR, *Yap_SHAREDIR, *Yap_LIBDIR, *Yap_DLLDIR,
* recursive consulting.
*
* */
static bool consult(const char *b_file USES_REGS) {
static bool load_file(const char *b_file USES_REGS) {
Term t;
int c_stream, osno, oactive;
Functor functor_query = Yap_MkFunctor(Yap_LookupAtom("?-"), 1);
Functor functor_query = Yap_MkFunctor(Yap_LookupAtom("?-"), 1);
Functor functor_command1 = Yap_MkFunctor(Yap_LookupAtom(":-"), 1);
Functor functor_compile2 = Yap_MkFunctor(Yap_LookupAtom("c_compile"), 1);
/* consult in C */
int lvl = push_text_stack();
char *full;
/* the consult mode does not matter here, really */
/* the consult mode does not matter here, really */
if ((osno = Yap_CheckAlias(AtomLoopStream)) < 0) {
osno = 0;
}
c_stream = YAP_InitConsult(YAP_BOOT_MODE, b_file, &full, &oactive);
if (c_stream < 0) {
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "done init_ consult %s ",b_file);
if (c_stream < 0) {
fprintf(stderr, "[ FATAL ERROR: could not open file %s ]\n", b_file);
pop_text_stack(lvl);
exit(1);
@ -177,6 +180,8 @@ static bool consult(const char *b_file USES_REGS) {
pop_text_stack(lvl);
return false;
}
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "do reset %s ",b_file);
do {
CACHE_REGS
@ -197,7 +202,7 @@ static bool consult(const char *b_file USES_REGS) {
FunctorOfTerm(t) == functor_command1)) {
t = ArgOfTerm(1, t);
if (IsApplTerm(t) && FunctorOfTerm(t) == functor_compile2) {
consult(RepAtom(AtomOfTerm(ArgOfTerm(1, t)))->StrOfAE);
load_file(RepAtom(AtomOfTerm(ArgOfTerm(1, t)))->StrOfAE);
Yap_ResetException(LOCAL_ActiveError);
} else {
YAP_RunGoalOnce(t);
@ -221,16 +226,82 @@ static bool consult(const char *b_file USES_REGS) {
return true;
}
static const char * EOLIST ="EOLINE";
static bool is_dir( const char *path, const void *info) {
if (Yap_isDirectory( path ))
return true;
char s[YAP_FILENAME_MAX + 1];
Int i = strlen(path);
strncpy(s, path, YAP_FILENAME_MAX);
while (--i) {
if (Yap_dir_separator((int)path[i]))
break;
}
if (i == 0) {
s[0] = '.';
i = 1;
}
s[i] = '\0';
return
strcmp(info,s) == 0 ||
Yap_isDirectory( s );
}
static bool is_file( const char *path, const void *info) {
return Yap_Exists( path );
}
static bool is_wfile( const char *path, const void *info) {
return true;
}
typedef bool testf(const char *s, const void *info);
///
///
static const char *sel(bool dir, bool ok1, const char *s1, bool ok2,
const char *s2, ...) {
if (ok1 && s1)
return s1;
if (ok2)
return s2;
return NULL;
}
static const char *sel(
testf test, const void *info, const char *s1, ...) {
const char *fmt = s1;
va_list ap;
char *buf = malloc(FILENAME_MAX + 1);
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "try %s", s1);
va_start(ap, s1);
while (fmt != EOLIST) {
__android_log_print( ANDROID_LOG_INFO, "YAPDroid", "loop %s", fmt);
if (fmt == NULL || fmt[0]=='\0') {
fmt = va_arg(ap, const char *);
continue;
}
strncpy(buf, fmt, FILENAME_MAX); // Yap_AbsoluteFile(fmt,true), FILENAME_MAX);
__android_log_print( ANDROID_LOG_INFO, "YAPDroid", "triyimh %s", buf);
if (test(buf,info)) {
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "got %s", buf);
buf = realloc(buf, strlen(buf) + 1);
va_end(ap);
return buf;
}
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "tried %s, failed", buf);
fmt = va_arg(ap, const char *);
}
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "failed search ");
va_end(ap);
free(buf);
return NULL;
}
static const char *join(const char *s0, const char *s1) {
CACHE_REGS
@ -256,103 +327,130 @@ static void Yap_set_locations(YAP_init_args *iap) {
// --_not useful in Android, WIN32;
/// -- DESTDIR/ in Anaconda
/// -- /usr/locall in most Unix style systems
Yap_ROOTDIR = sel(true, iap->ROOTDIR != NULL, iap->ROOTDIR, true,
#if 0
Yap_ROOTDIR = sel( is_dir, NULL,
iap->ROOTDIR,
getenv("YAPROOTDIR"),
#if __ANDROID__
NULL,
"/",
#else
join(getenv("DESTDIR"), YAP_ROOTDIR),
join(getenv("DESTDIR"), YAP_ROOTDIR),
join(getenv("DESTDIR"), join(getenv("ḦOME"),".local")),
join(getenv("DESTDIR"), "/usr/local"),
join(getenv("DESTDIR"), "/usr"),
join(getenv("DESTDIR"), "/opt"),
#endif
false);
/// BINDIR: where the OS stores header files, namely libYap...
Yap_BINDIR = sel(true, iap->BINDIR != NULL, iap->BINDIR, true,
#if __ANDROID__
NULL,
#else
EOLIST
);
/// BINDIR: where the OS stores header files, namely libYap...
Yap_BINDIR = sel( is_dir, Yap_ROOTDIR, iap->BINDIR,
getenv("YAPBINDIR"),
#if !defined(__ANDROID__)
join(getenv("DESTDIR"), YAP_BINDIR),
#endif
false);
join(Yap_ROOTDIR, "/bin"),
EOLIST);
/// LIBDIR: where the OS stores dynamic libraries, namely libYap...
Yap_LIBDIR = sel(true, iap->LIBDIR != NULL, iap->LIBDIR, true,
#if __ANDROID__
NULL,
#else
Yap_LIBDIR = sel( is_dir, Yap_ROOTDIR, iap->LIBDIR,
#if !defined(__ANDROID__)
join(getenv("DESTDIR"), YAP_LIBDIR),
#endif
false);
join(Yap_ROOTDIR, "/lib"),
EOLIST);
/// DLLDIR: where libraries can find expicitely loaded DLLs
Yap_DLLDIR = sel(true, iap->DLLDIR != NULL, iap->DLLDIR, true,
#if __ANDROID__
NULL,
#else
join(getenv("DESTDIR"), YAP_DLLDIR),
Yap_DLLDIR = sel(is_dir, Yap_LIBDIR, iap->DLLDIR,
getenv("YAPLIBDIR"),
#if !defined(__ANDROID__)
join(getenv("DESTDIR"), YAP_DLLDIR),
join(Yap_LIBDIR, "/yap"),
#endif
false);
EOLIST);
/// INCLUDEDIR: where the OS stores header files, namely libYap...
Yap_INCLUDEDIR = sel(true, iap->INCLUDEDIR != NULL, iap->INCLUDEDIR, true,
#if __ANDROID__
NULL,
#else
join(getenv("DESTDIR"), YAP_INCLUDEDIR),
Yap_INCLUDEDIR = sel(is_dir, Yap_ROOTDIR, iap->INCLUDEDIR,
#if !defined(__ANDROID__)
join(getenv("DESTDIR"), YAP_INCLUDEDIR),
#endif
false);
join(Yap_ROOTDIR, "/include"),
EOLIST);
/// SHAREDIR: where OS & ARCH independent files live
Yap_SHAREDIR = sel(true, iap->SHAREDIR != NULL, iap->SHAREDIR, true,
#if __ANDROID__
"/assets",
#else
join(getenv("DESTDIR"), YAP_SHAREDIR),
Yap_SHAREDIR = sel( is_dir, Yap_ROOTDIR, iap->SHAREDIR,
getenv("YAPSHAREDIR"),
#if !defined(__ANDROID__)
join(getenv("DESTDIR"), YAP_SHAREDIR),
join(Yap_ROOTDIR, "/share"),
"/assets",
#endif
false);
join(Yap_ROOTDIR, "/files"),
EOLIST);
/// PLDIR: where we can find Prolog files
Yap_PLDIR = sel(true, iap->PLDIR != NULL, iap->PLDIR, true,
Yap_PLDIR = sel( is_dir, Yap_SHAREDIR, iap->PLDIR,
#if __ANDROID__
YAP_PLDIR,
"/assets/Yap",
#else
join(getenv("DESTDIR"), YAP_PLDIR),
join(Yap_SHAREDIR, "/Yap"),
#endif
false);
EOLIST);
/// ``COMMONSDIR: Prolog Commons
Yap_COMMONSDIR = sel(true, iap->COMMONSDIR != NULL, iap->COMMONSDIR, true,
Yap_COMMONSDIR = sel(is_dir, Yap_SHAREDIR, iap->COMMONSDIR,
#if __ANDROID__
"/assets/PrologCommons",
#else
join(getenv("DESTDIR"), YAP_SHAREDIR "/PrologCommons"),
join(Yap_SHAREDIR, "PrologCommons"),
#endif
false);
EOLIST);
/// BOOTPLDIR: where we can find Prolog bootstrap files
Yap_BOOTSTRAP = sel(true, iap->BOOTSTRAP != NULL, iap->BOOTSTRAP, true,
#if __ANDROID__
"/assets/Yap/pl/boot.yap",
#else
join(getenv("DESTDIR"), YAP_BOOTSTRAP),
#endif
false);
Yap_BOOTSTRAP = sel( is_file, NULL, iap->BOOTSTRAP,
YAP_BOOTSTRAP,
EOLIST);
/// BOOTFILE: where we can find the core Prolog boot file
Yap_BOOTFILE = sel(false, iap->BOOTFILE != NULL, iap->BOOTFILE, true,
const char * Yap_PLBOOTDIR = sel( is_dir, Yap_PLDIR,
#if __ANDROID__
"/assets/Yap/pl/boot.yap",
"/assets/Yap/pl",
#else
join(getenv("DESTDIR"), YAP_BOOTFILE),
join(Yap_PLDIR, "/pl"),
#endif
EOLIST);
Yap_BOOTFILE = sel( is_wfile, Yap_PLBOOTDIR, iap->BOOTFILE,
#if __ANDROID__
"/assets/Yap/pl/boot.yap",
#else
join(Yap_PLBOOTDIR, "/boot.yap"),
#endif
EOLIST);
#endif
false);
/// STARTUP: where we can find the core Prolog bootstrap file
Yap_OUTPUT_STARTUP =
sel(false, iap->OUTPUT_STARTUP != NULL, iap->OUTPUT_STARTUP, true,
#if __ANDROID__
NULL,
sel( is_wfile, Yap_AbsoluteFile(".",false), iap->OUTPUT_STARTUP,
#if defined(__ANDROID__)
EOLIST,
#else
join(getenv("DESTDIR"), YAP_OUTPUT_STARTUP),
YAP_OUTPUT_STARTUP,
#endif
false);
"startup.yss",
EOLIST);
Yap_INPUT_STARTUP =
sel(false, iap->INPUT_STARTUP != NULL, iap->INPUT_STARTUP, true,
sel( is_wfile, Yap_DLLDIR, iap->INPUT_STARTUP,
#if __ANDROID__
NULL,
EOLIST,
#else
join(getenv("DESTDIR"), YAP_INPUT_STARTUP),
join(getenv("DESTDIR"), YAP_INPUT_STARTUP),
#endif
false);
if (Yap_ROOTDIR)
"startup.yss",
join(Yap_DLLDIR, "/startup.yss"),
EOLIST);
if (Yap_ROOTDIR)
setAtomicGlobalPrologFlag(HOME_FLAG,
MkAtomTerm(Yap_LookupAtom(Yap_ROOTDIR)));
if (Yap_PLDIR)
@ -461,14 +559,16 @@ X_API YAP_file_type_t Yap_InitDefaults(void *x, char *saved_state, int argc,
LOCAL_TextBuffer = Yap_InitTextAllocator();
YAP_init_args *iap = x;
memset(iap, 0, sizeof(YAP_init_args));
iap->Argc = argc;
iap->Argv = argv;
#if __ANDROID__
iap->boot_file_type = YAP_BOOT_PL;
return YAP_B
iap->INPUT_STARTUP = NULL;
iap->assetManager = NULL;
return YAP_BOOT_PL;
#else
iap->boot_file_type = YAP_QLY;
iap->INPUT_STARTUP = saved_state;
iap->Argc = argc;
iap->Argv = argv;
return YAP_QLY;
#endif
}
@ -1005,7 +1105,8 @@ X_API void YAP_Init(YAP_init_args *yap_init) {
bool try_restore = yap_init->boot_file_type == YAP_QLY;
bool do_bootstrap = yap_init->boot_file_type == YAP_BOOT_PL;
struct ssz_t minfo;
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "start init ");
if (YAP_initialized)
/* ignore repeated calls to YAP_Init */
return;
@ -1038,16 +1139,20 @@ X_API void YAP_Init(YAP_init_args *yap_init) {
Yap_ExecutionMode = yap_init->ExecutionMode;
Yap_set_locations(yap_init);
if (do_bootstrap || !try_restore ||
if (Yap_INPUT_STARTUP==NULL)
try_restore = false;
if (do_bootstrap || !try_restore ||
!Yap_SavedInfo(Yap_INPUT_STARTUP, &minfo.Trail, &minfo.Stack,
&minfo.Heap)) {
init_globals(yap_init);
start_modules();
CurrentModule = PROLOG_MODULE;
TermEof = MkAtomTerm(Yap_LookupAtom("end_of_file"));
TermEof = MkAtomTerm(Yap_LookupAtom("end_of_file"));
LOCAL_consult_level = -1;
consult(Yap_BOOTSTRAP PASS_REGS);
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "init %s ", Yap_BOOTSTRAP);
load_file(Yap_BOOTSTRAP PASS_REGS);
setAtomicGlobalPrologFlag(RESOURCE_DATABASE_FLAG,
MkAtomTerm(Yap_LookupAtom(Yap_BOOTFILE)));
setBooleanGlobalPrologFlag(SAVED_PROGRAM_FLAG, false);
@ -1055,6 +1160,8 @@ X_API void YAP_Init(YAP_init_args *yap_init) {
if (yap_init->QuietMode) {
setVerbosity(TermSilent);
}
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "restore %s ",Yap_INPUT_STARTUP );
Yap_Restore(Yap_INPUT_STARTUP);
init_globals(yap_init);

View File

@ -320,6 +320,7 @@ set(YAP_ROOTDIR ${prefix})
# libdir defined above
set(YAP_DATADIR ${CMAKE_INSTALL_FULL_DATADIR})
set(YAP_INCLUDEDIR ${CMAKE_INSTALL_FULL_INCLUDEDIR}/Yap)
set(YAP_BINDIR ${CMAKE_INSTALL_FULL_BINDIR})
set(YAP_LIBDIR ${CMAKE_INSTALL_FULL_LIBDIR})
set(YAP_DLLDIR ${CMAKE_INSTALL_FULL_LIBDIR}/Yap)
set(YAP_PLDIR ${CMAKE_INSTALL_FULL_DATADIR}/Yap)
@ -532,8 +533,16 @@ include_directories(utf8proc packages/myddas packages/myddas/sqlite3/src )
set_property(SOURCE ${LIBYAP_SOURCES} APPEND PROPERTY COMPILE_DEFINITIONS YAP_KERNEL=1)
IF (WITH_SWIG)
find_host_package(SWIG)
# macro_log_feature (SWIG_FOUND "Swig"
# "Use SWIG Interface Generator "
# "http://www.swig.org" ON)
ENDIF (WITH_SWIG)
IF (WITH_MYDDAS)
if (ANDROID)
include_directories (packages/swig/android)
else()
add_definitions(-DUSE_MYDDAS=1 -DMYDDAS_SQLITE3=1)
@ -553,14 +562,6 @@ IF (WITH_MYDDAS)
endif(WITH_MYDDAS)
IF (WITH_SWIG)
find_host_package(SWIG)
# macro_log_feature (SWIG_FOUND "Swig"
# "Use SWIG Interface Generator "
# "http://www.swig.org" ON)
ENDIF (WITH_SWIG)
IF (WITH_PYTHON)
include(python )

View File

@ -270,6 +270,8 @@ public:
inline void setArgv(char **fl) { Argv = fl; };
inline char **getArgv() { return Argv; };
inline void setROOTDIR(char *fl) { ROOTDIR = fl; };
};
/**
@ -293,7 +295,14 @@ public:
YAPEngine(YAPEngineArgs *cargs) {
engine_args = cargs;
// doInit(cargs->boot_file_type);
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "start engine ");
#ifdef __ANDROID__
doInit(YAP_BOOT_PL, cargs);
#else
doInit(YAP_QLY, cargs);
#endif
}; /// construct a new engine, including aaccess to callbacks
/// construct a new engine using argc/argv list of arguments
YAPEngine(int argc, char *argv[],

View File

@ -2030,7 +2030,7 @@ significant byte first (like Motorola and SPARC, unlike Intel). */
/* name of Commons library */
#ifndef YAP_COMMONSDIR
#define YAP COMMONSDIR "${YAP_DATADIR}/PrologCommmons"
#define YAP_COMMONSDIR "${YAP_DATADIR}/PrologCommmons"
#endif

View File

@ -31,14 +31,18 @@ SET( EXT
string(APPEND CMAKE_HTML_EXTRA ${i} " ")
endforeach(i ${CMAKE_HTML_EXTRA_})
set(DOCS_EXCLUDE_
set(DOC_DIRS_EXCLUDE_
${CMAKE_SOURCE_DIR}/build
${CMAKE_SOURCE_DIR}/Debug
${CMAKE_SOURCE_DIR}/packages/jpl
${CMAKE_SOURCE_DIR}/packages/swig
${CMAKE_SOURCE_DIR}/packages/Problog/problog_examples/output
${CMAKE_SOURCE_DIR}/packages/Problog/problog_examples/queries
${CMAKE_SOURCE_DIR}/packages/swi
${CMAKE_SOURCE_DIR}/packages/Problog/problog_examples
${CMAKE_SOURCE_DIR}/packages/myddas/sqlite3/src
${CMAKE_SOURCE_DIR}/packages/gecode/6.0.1
${CMAKE_SOURCE_DIR}/packages/gecode/6.0.0
${CMAKE_SOURCE_DIR}/packages/gecode/5.1.0
${CMAKE_SOURCE_DIR}/packages/gecode/5.0.0
${CMAKE_SOURCE_DIR}/packages/gecode/4.4.0
${CMAKE_SOURCE_DIR}/packages/gecode/4.2.1
${CMAKE_SOURCE_DIR}/packages/gecode/4.2.0
@ -48,22 +52,30 @@ ${CMAKE_SOURCE_DIR}/packages/gecode/3.7.2
${CMAKE_SOURCE_DIR}/packages/gecode/3.7.1
${CMAKE_SOURCE_DIR}/packages/gecode/3.7.0
${CMAKE_SOURCE_DIR}/packages/gecode/3.6.0
${CMAKE_SOURCE_DIR}/packages/problog
${CMAKE_SOURCE_DIR}/packages/gecode/dev
${CMAKE_SOURCE_DIR}/C/traced_absmi_insts.h
${CMAKE_SOURCE_DIR}/H/globals.h
${CMAKE_SOURCE_DIR}/packages/cplint
${CMAKE_SOURCE_DIR}/packages/CLPBN/examples
${CMAKE_SOURCE_DIR}/packages/CLPBN/horus
${CMAKE_SOURCE_DIR}/packages/cuda
${CMAKE_SOURCE_DIR}/packages/prosqlite
${CMAKE_SOURCE_DIR}/packages/pyswip
${CMAKE_SOURCE_DIR}/packages/python/yap_kernel
${CMAKE_SOURCE_DIR}/packages/python/swig
${CMAKE_SOURCE_DIR}/packages/yap-lbfgs/liblbfgs-1.10
${CMAKE_SOURCE_DIR}/packages/swi-minisat2
${CMAKE_SOURCE_DIR}/library/dialect/swi/os
)
set(DOCS_EXCLUDE_
${CMAKE_SOURCE_DIR}/C/traced_absmi_insts.h
${CMAKE_SOURCE_DIR}/H/globals.h
${CMAKE_SOURCE_DIR}/OPTYap/locks_alpha_funcs.h
${CMAKE_SOURCE_DIR}/OPTYap/locks_mips_funcs.h
${CMAKE_SOURCE_DIR}/OPTYap/locks_sparc.h
${CMAKE_SOURCE_DIR}/*/bprolog/*
${CMAKE_SOURCE_DIR}/*/prism/*
${CMAKE_SOURCE_DIR}/*/gecodde/[345]*
${CMAKE_SOURCE_DIR}/*/gecode/[345]*
${CMAKE_SOURCE_DIR}/packages/gecode/gecode3_yap.cc
${CMAKE_SOURCE_DIR}/packages/gecode/gecode4_yap.cc
${CMAKE_SOURCE_DIR}/packages/gecode/gecode5_yap.cc
@ -73,15 +85,21 @@ ${CMAKE_SOURCE_DIR}/*/bprolog/*
${CMAKE_SOURCE_DIR}/packages/gecode/gecode3_yap_hand_written.yap
${CMAKE_SOURCE_DIR}/packages/gecode/gecode4_yap_hand_written.yap
${CMAKE_SOURCE_DIR}/packages/gecode/gecode5_yap_hand_written.yap
*/CMakeFiles/* *~ */#*
*/CMakeFiles/*
)
foreach(i ${DOCS_EXCLUDE_})
string(APPEND DOCS_EXCLUDE ${i} " ")
endforeach(i ${DOCS_EXCLUDE_})
foreach(i ${DOCS_DIR_EXCLUDE_})
string(APPEND DOCS_DIR_EXCLUDE ${i} " ")
endforeach(i ${DOCS_DIR_EXCLUDE_})
# add a target to generate API documentation with Doxygen
@ -92,6 +110,7 @@ endforeach(i ${DOCS_EXCLUDE_})
SET(DOC_INPUT_FILES_
${CMAKE_SOURCE_DIR}/docs/md
${CMAKE_SOURCE_DIR}/pl
${CMAKE_SOURCE_DIR}/packages/ProbLog
${CMAKE_SOURCE_DIR}/CXX
${CMAKE_SOURCE_DIR}/OPTYap
${CMAKE_SOURCE_DIR}/C
@ -100,7 +119,8 @@ endforeach(i ${DOCS_EXCLUDE_})
${CMAKE_SOURCE_DIR}/os
${CMAKE_SOURCE_DIR}/library
${CMAKE_SOURCE_DIR}/swi/library
${CMAKE_SOURCE_DIR}/packages
#${CMAKE_SOURCE_DIR}/packages
${CMAKE_SOURCE_DIR}/BEAM
)
foreach(i ${DOC_INPUT_FILES_})

View File

@ -296,10 +296,7 @@ OPTIMIZE_OUTPUT_FOR_PROLOG = YES
# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
# the files are not read by doxygen.
EXTENSION_MAPPING = md \
pl=Prolog \
yap=Prolog \
ypp=Prolog
EXTENSION_MAPPING =
# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
# according to the Markdown format, which allows for more readable
@ -798,7 +795,7 @@ WARN_LOGFILE =
# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING
# Note: If this tag is empty the current directory is searched.
INPUT = @DOC_INPUT_FILES@
INPUT = @CMAKE_SOURCE_DIR@
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
@ -884,7 +881,7 @@ RECURSIVE = YES
# Note that relative paths are relative to the directory from which doxygen is
# run.
EXCLUDE =
EXCLUDE = @DOCS_DIR_EXCLUDE@
# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
# directories that are symbolic links (a Unix file system feature) are excluded
@ -1090,7 +1087,7 @@ VERBATIM_HEADERS = YES
# classes, structs, unions or interfaces.
# The default value is: YES.
ALPHABETICAL_INDEX = NO
ALPHABETICAL_INDEX = YES
# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
# which the alphabetical index list will be split.

View File

@ -1,10 +1,14 @@
@defgroup builtins Core Built-ins
@{
[TOC]
@brief This chapter describes the core built-in predicates that control the execution of
This chapter describes the core built-in predicates that control the execution of
Prolog programs, provide fundamental functionality such as termm manipulation or arithmetic, and support interaction with external
resources,
resources.
@{
Many of the predicates described here have been standardised by the International Standard Organization.
The corresponding standartised subset of Prolog also known as ISO-Prolog.
@ -20,6 +24,8 @@ notation will be used:
+ an argument with no preceding symbol can be used in both ways.
[TOC]
@}

View File

@ -1,6 +1,8 @@
YAP packages {#packages}
============
[TOC]
+ @ref real
+ @subpage BDDs
@ -11,7 +13,7 @@ YAP packages {#packages}
+ @ref PFL
+ @subpage ProbLog1
+ @subpage problog
+ @ref python

View File

@ -21,7 +21,7 @@ The manual is organised as follows:
+ @ref run
+ @ref builtins
+ @subpage builtins
+ @ref extensions

View File

@ -5,10 +5,7 @@ markdown_extensions:
- toc:
permalink: True
- sane_lists
use_directory_urls: false
plugins:
- search
- awesome-pages:
filename: .index
disable_auto_arrange_index: false
collapse_single_pages: true

View File

@ -77,18 +77,20 @@ open_asset(VFS_t *me, const char *fname, const char *io_mode, int sno) {
// AAssetDir *dp = AAssetManager_openDir( Yap_assetManager(), dirname(dir) );
// strcpy(dir, fname);
// char *d = basename(dir);
am = AAssetManager_open(Yap_assetManager(), fname, mode);
am = AAssetManager_open(Yap_assetManager(), fname, io_mode);
//if (am==NULL)
// __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "failed open %s <%s>", fname, strerror(errno) );
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "open %s <%s>", fname, io_mode);
// while (dp) {
// char *f = AAssetDir_getNextFileName(dp);
// __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "open %s <%s>", f, d);
// __android_log_print(ANDROID_LOG_INFO, "YAPDroid", "open %s <%s>", fname, mode);
// if (f && strcasecmp(d,f) == 0) {
//
// }
// }
if (!am) {
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "failed %s <%s>", fname, io_mode);
return NULL;
}
// try not to use it as an asset
@ -111,7 +113,7 @@ open_asset(VFS_t *me, const char *fname, const char *io_mode, int sno) {
st->vfs = NULL;
st->vfs_handle = NULL;
st->status = Seekable_Stream_f|Input_Stream_f;
return st;
return st->file;
} else {
// should be done, but if not
GLOBAL_Stream[sno].vfs_handle = am;

View File

@ -1135,7 +1135,7 @@ bool Yap_initStream(int sno, FILE *fd, Atom name, const char *io_mode,
ANDROID_LOG_INFO, "YAPDroid", "init %s %s:%s stream <%d>", io_mode,
CurrentModule == 0 ? "prolog"
: RepAtom(AtomOfTerm(CurrentModule))->StrOfAE,
name, sno);
RepAtom(name)->StrOfAE, sno);
if (io_mode == NULL)
Yap_Error(PERMISSION_ERROR_NEW_ALIAS_FOR_STREAM, MkIntegerTerm(sno),
"File opened with NULL Permissions");
@ -1242,74 +1242,80 @@ static bool fill_stream(int sno, StreamDesc *st, Term tin, const char *io_mode,
st->file = NULL;
if (fname) {
if ((vfsp = vfs_owner(fname)) != NULL &&
vfsp->open(vfsp, fname, io_mode, sno)) {
// read, write, append
user_name = st->user_name;
st->vfs = vfsp;
UNLOCK(st->streamlock);
} else {
st->file = fopen(fname, io_mode);
if (st->file == NULL) {
UNLOCK(st->streamlock);
if (errno == ENOENT && !strchr(io_mode, 'r')) {
PlIOError(EXISTENCE_ERROR_SOURCE_SINK, tin, "%s: %s", fname,
strerror(errno));
} else {
PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, tin, "%s: %s", fname,
strerror(errno));
}
}
st->vfs = NULL;
}
if (!st->file && !st->vfs) {
PlIOError(EXISTENCE_ERROR_SOURCE_SINK, tin, "%s", fname);
/* extract BACK info passed through the stream descriptor */
return false;
}
} else if (IsApplTerm(tin)) {
Functor f = FunctorOfTerm(tin);
if (f == FunctorAtom || f == FunctorString || f == FunctorCodes1 ||
f == FunctorCodes || f == FunctorChars1 || f == FunctorChars) {
if (strchr(io_mode, 'r')) {
return Yap_OpenBufWriteStream(PASS_REGS1);
} else {
int j = push_text_stack();
const char *buf;
if ((vfsp = vfs_owner(fname)) != NULL) {
if (vfsp->open(vfsp, fname, io_mode, sno)) {
// read, write, append
user_name = st->user_name;
st->vfs = vfsp;
UNLOCK(st->streamlock);
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "got %d ", sno);
} else {
UNLOCK(st->streamlock);
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "failed %s ",fname);
return false;
}
} else {
st->file = fopen(fname, io_mode);
if (st->file == NULL) {
__android_log_print(
ANDROID_LOG_INFO, "YAPDroid", "failed %s ",fname);
UNLOCK(st->streamlock);
if (errno == ENOENT && !strchr(io_mode, 'r')) {
PlIOError(EXISTENCE_ERROR_SOURCE_SINK, tin, "%s: %s", fname,
strerror(errno));
} else {
PlIOError(PERMISSION_ERROR_OPEN_SOURCE_SINK, tin, "%s: %s", fname,
strerror(errno));
}
return false;
}
buf = Yap_TextTermToText(tin PASS_REGS);
if (!buf) {
pop_text_stack(j);
return false;
}
buf = pop_output_text_stack(j, buf);
Atom nat = Yap_LookupAtom(Yap_StrPrefix(buf, 32));
sno = Yap_open_buf_read_stream(buf, strlen(buf) + 1, &LOCAL_encoding,
MEM_BUF_MALLOC, nat,
MkAtomTerm(NameOfFunctor(f)));
pop_text_stack(j);
return Yap_OpenBufWriteStream(PASS_REGS1);
}
} else if (!strcmp(RepAtom(NameOfFunctor(f))->StrOfAE, "popen")) {
const char *buf;
int i = push_text_stack();
buf = Yap_TextTermToText(ArgOfTerm(1, tin) PASS_REGS);
if (buf == NULL) {
return false;
}
} else if (IsApplTerm(tin)) {
Functor f = FunctorOfTerm(tin);
if (f == FunctorAtom || f == FunctorString || f == FunctorCodes1 ||
f == FunctorCodes || f == FunctorChars1 || f == FunctorChars) {
if (strchr(io_mode, 'r')) {
return Yap_OpenBufWriteStream(PASS_REGS1);
} else {
int j = push_text_stack();
const char *buf;
buf = Yap_TextTermToText(tin PASS_REGS);
if (!buf) {
pop_text_stack(j);
return false;
}
buf = pop_output_text_stack(j, buf);
Atom nat = Yap_LookupAtom(Yap_StrPrefix(buf, 32));
sno = Yap_open_buf_read_stream(buf, strlen(buf) + 1, &LOCAL_encoding,
MEM_BUF_MALLOC, nat,
MkAtomTerm(NameOfFunctor(f)));
pop_text_stack(j);
return Yap_OpenBufWriteStream(PASS_REGS1);
}
} else if (!strcmp(RepAtom(NameOfFunctor(f))->StrOfAE, "popen")) {
const char *buf;
int i = push_text_stack();
buf = Yap_TextTermToText(ArgOfTerm(1, tin) PASS_REGS);
if (buf == NULL) {
return false;
}
#if _WIN32
st->file = _popen(buf, io_mode);
st->file = _popen(buf, io_mode);
#else
st->file = popen(buf, io_mode);
st->file = popen(buf, io_mode);
#endif
fname = "popen";
user_name = tin;
st->status |= Popen_Stream_f;
pop_text_stack(i);
} else {
Yap_ThrowError(DOMAIN_ERROR_SOURCE_SINK, tin, "open");
}
}
fname = "popen";
user_name = tin;
st->status |= Popen_Stream_f;
pop_text_stack(i);
} else {
Yap_ThrowError(DOMAIN_ERROR_SOURCE_SINK, tin, "open");
}
}
if (!strchr(io_mode, 'b') && binary_file(fname)) {
st->status |= Binary_Stream_f;
}

View File

@ -355,7 +355,7 @@ bool Yap_ChDir(const char *path) {
int lvl = push_text_stack();
const char *qpath = Yap_AbsoluteFile(path, true);
//__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "chdir %s", path);
__android_log_print(ANDROID_LOG_INFO, "YAPDroid", "chdir %s", path);
VFS_t *v;
if ((v = vfs_owner(qpath))) {
rc = v->chdir(v, (qpath));

View File

@ -0,0 +1,66 @@
The Problog-I Language and Learning System {#problog}
=====================================
[TOC]
This document is intended as a user guide for the users of ProbLog-I.
ProbLog is a probabilistic Prolog, a probabilistic logic programming
language, which is integrated in YAP-Prolog. Most of the work in ProbLog is now based on(Prolog-II), but we still maintain ProbLog-I in order to experiment with close integration of probabilistic nd logical systems.
@section InstallingProbLog Installing ProbLog
You will need the CUDD binary decision daagram generator. CUDD is available in Fedora Linux, MacPorts and other Linux distributions. If it is not available in your system, please fetch it from:
- [git@github.com:vscosta/cudd.git]
To compile CUDD you will need to run:
- `./configure --enable-dynamic=true`
- `make`
- `make -j install`
@section RunningProbLog Running ProbLog
To run ProbLog, go your ProbLog folder (eg. $\sim$/problog), and start
YAP (eg. $\sim$/yap/yap). This will start YAP with ProbLog
functionality.
To use ProbLog, the ProbLog module has to be loaded at the top of your
Prolog programs. This is done with the following statement:
> *:- use_module('../path/to/problog').*
where '../path/to/problog' represents the path to the problog.yap module
(ie. without the extension) from the current folder from where YAP was
started.
Similarly, to use the ProbLog learning module, use:
> *:- use_module('../path/to/problog_learning').*
@section EncodingProbs Encoding Probabilistic Facts
A probabilistic fact is encoded in ProbLog by preceding a predicate with
a probability value. For example:
> *0.5::heads(_).*
encodes the fact that there's 50% chance of getting heads when tossing
an unbiassed coin.
@subsection EncodingPars Encoding Parameter Learning Facts
Instead of probabilities every fact has a t( ) prefix. The t stands for
tunable and indicate that ProbLog should learn the probability. The
number between the parentheses indicates the ground truth probability.
It is ignored by the learning algorithm and if you do not know the
ground truth, you can write t(_). The ground truth is used after
learning to estimate the distance of the learned model parameters to the
ground truth model parameters. For example:
> t(0.5)::heads(1).

View File

@ -1,518 +0,0 @@
\documentclass[a4paper,12pt]{article}
\usepackage{indentfirst}
\usepackage{hyperref}
\author{}
\title{ProbLog User Manual}
\begin{document}
\maketitle
\newpage
\tableofcontents
\newpage
\section{Introduction}
This document is intended as a user guide for the users of ProbLog. ProbLog is a probabilistic Prolog, a probabilistic logic programming language, which is integrated in YAP-Prolog.
\section{Installing ProbLog}
\subsection{Requirements}
For installing and running ProbLog, the following are required:
\begin{itemize}
\item a reasonable up-to-date computer, running Linux or Mac OS
\item YAP Prolog 5.1.3 (for Mac OS the more recent version 5.1.4 is needed) or YAP-6
\end{itemize}
\subsection{Download}
To install ProbLog, it is first necessary to download the ProbLog source files as well as SimpleCUDD. YAP Prolog also needs to be downloaded if it is not already installed on the machine.
\paragraph{}
For downloading ProbLog, go to:
\begin{itemize}
\item http://dtai.cs.kuleuven.be/problog/download.html
\end{itemize}
\paragraph{}
For downloading SimpleCUDD, go to:
\begin{itemize}
\item http://www.cs.kuleuven.be/$\sim$theo/tools/SimpleCUDD.tar.gz
\end{itemize}
\subsection{Compiling YAP Prolog}
ProbLog heavily depends on YAP Prolog. If YAP Prolog is already installed on your machine, proceed to the next section.
Download and unpack YAP Prolog to $\sim$/yap, and install YAP in your home directory by typing:
\begin{quotation}
cd $\sim$/yap
./configure --prefix="$\sim$/yap" --exec-prefix="$\sim$/yap"
make
make install
\end{quotation}
Some useful extra packages to install before configuring yap:
\begin{quotation}
sudo apt-get install libreadline6-dev
sudo apt-get install libgmp3-dev
sudo apt-get install g++
\end{quotation}
Afterwards, you can run YAP by calling $\sim$/yap/yap. Note: This will configure YAP with standard settings - which work fine in combination with ProbLog. In case you want to install YAP somewhere else or use different settings, please consult the YAP documentation.
\subsection{Compiling ProbLog}
Download the latest version of ProbLog and SimpleCUDD, as described in a previous section. Unpack ProbLog - for instance - to $\sim$/problog. Unpack SimpleCUDD in a subfolder - for instance - to $\sim$/problog/simlpecudd. Afterwards compile ProbLog by typing:
\begin{quotation}
cd $\sim$/problog
make
\end{quotation}
This will compile CUDD and SimpleCUDD which are used by ProbLog for BDD operations.
\section{Running ProbLog}
To run ProbLog, go your ProbLog folder (eg. $\sim$/problog), and start YAP (eg. $\sim$/yap/yap). This will start YAP with ProbLog functionality.
\section{Loading the ProbLog modules}
To use ProbLog, the ProbLog module has to be loaded at the top of your Prolog programs. This is done with the following statement:
\begin{quotation}
\textit{:- use\_module('../path/to/problog').}
\end{quotation}
where '../path/to/problog' represents the path to the problog.yap module (ie. without the extension) from the current folder from where YAP was started.
\paragraph{}
Similarly, to use the ProbLog learning module, use:
\begin{quotation}
\textit{:- use\_module('../path/to/problog\_learning').}
\end{quotation}
\section{Encoding Probabilistic Facts}
A probabilistic fact is encoded in ProbLog by preceding a predicate with a probability value. For example:
\begin{quotation}
\textit{0.5::heads(\_).}
\end{quotation}
encodes the fact that there's 50\% chance of getting heads when tossing an unbiassed coin.
\subsection{Encoding Parameter Learning Facts}
Instead of probabilities every fact has a t( ) prefix. The t stands for tunable and indicate that ProbLog should learn the probability. The number between the parentheses indicates the ground truth probability. It is ignored by the learning algorithm and if you do not know the ground truth, you can write t(\_). The ground truth is used after learning to estimate the distance of the learned model parameters to the ground truth model parameters. For example:
\begin{quotation}
t(0.5)::heads(1).
\end{quotation}
\section{ProbLog Predicates}
This chapter describes the predicates defined by ProbLog for evaluating the probability of queries.
In the description of the arguments of functors the following notation will be used:
\begin{itemize}
\item a preceding plus sign will denote an argument as an "input argument" - it cannot be a free variable at the time of the call
\item a preceding minus sign will denote an "output argument"
\item an argument with no preceding symbol can be used in both ways
\end{itemize}
\subsection{problog\_max}
\textit{problog\_max(+G, -Prob, -FactsUsed)}
\paragraph{}
This predicate returns the most likely explanation of proving the goal G and the facts used in achieving this explanation.
\subsection{problog\_exact}
\textit{problog\_exact(+G, -Prob, -Status)}
\paragraph{}
This predicate returns the exact total probability of achieving the goal G and the status of the query.
\subsection{problog\_kbest}
\textit{problog\_kbest(+G, +K, -Prob, -Status)}
\paragraph{}
This predicate returns the sum of the probabilities of the best K proofs of achieving the goal G and the status of the query.
\subsection{problog\_montecarlo}
\textit{problog\_montecarlo(+G, +Interval\_width, -Prob)}
\paragraph{}
This predicate approximates the probability of achieving the goal G by using a Monte Carlo approach, with 95\% confidence in the given interval width.
\subsection{problog\_delta}
\textit{problog\_delta(+G , +Interval\_width, -Bound\_low, -Bound\_up, -Status)}
\paragraph{}
This predicate returns the lower and upper bound of the probability of achieving the goal G by using an iterative
deepening approach with the given interval width.
\subsection{problog\_threshold}
\textit{problog\_threshold(+G , +Prob, -Bound\_low, -Bound\_up, -Status)}
\paragraph{}
This predicate returns the lower and upper bound of the probability of achieving the goal G obtained by cutting the sld tree at the given probability for each branch.
\subsection{problog\_low}
\textit{problog\_low(+G, +Prob, -Bound\_low, -Status)}
\paragraph{}
This predicate returns the lower bound of the probability of achieving the goal G obtained by cutting the sld tree at the given probability for each branch.
\section{ProbLog Parameter Learning Predicates}
\subsection{Training Example Predicate}
\textit{example(+N, +Q, +Prob)}
\paragraph{}
This predicate specifies an example. Every example has as input a unique identifier (N), a query (Q) and a probability (Prob) associated with it.
Instead of queries, you can also give proofs as training example. They are encoded as the conjunction of the probabilistic facts used in the proof.
\subsection{Test Example Predicate}
\textit{test\_example(+N, +Q, +Prob)}
\paragraph{}
This predicate specifies a test example. Every test example has as input a unique identifier (N), a query (Q) and a probability (Prob) associated with it.
Test examples are ignored during learning but are used afterwards to check the performance of the model. The ID namespace is shared between the test examples and the training examples and you may only reuse an ID if the queries are identical.
\subsection{Learning Predicates}
\textit{:- do\_learning(+N).}
\paragraph{}
Starts the learning algorithm with N iterations.
\paragraph{}
\textit{:- do\_learning(+N, +Epsilon).}
\paragraph{}
Starts the learning algorithm. The learning will stop after N iterations or if the difference of the Mean Squared Error (MSE) between two iterations gets smaller than Epsilon - depending on what happens first.
\subsection{Learning Output}
The output is created in the output subfolder of the current folder where YAP was started. There you will find the file log.dat which contains MSE on training and test set for every iteration, the timings, and some metrics on the gradient in CSV format. The files factprobs\_N.pl contain the fact probabilities after the Nth iteration and the files predictions\_N.pl contain the estimated probabilities for each training and test example - per default these file are generated every 5th iteration only.
\section{Miscelaneous}
Both the learning and the inference module have various parameters, or flags, that can be adjusted by the user.
The following predicates are defined by ProbLog to access and set these flags.
\subsection{problog\_flags}
\textit{problog\_flags}
\paragraph{}
This predicate lists all the flags name, value, domain and description.
\subsection{problog\_flag}
\textit{problog\_flag(+Name, -Value)}
\paragraph{}
This predicate gives the value of the flag with the specified name. The supported flags are:
\paragraph{}
\texttt{use\_db\_trie}
Flag telling whether to use the builtin trie to trie transformation.
The possible values for this flag are true or false.
\paragraph{}
\texttt{db\_trie\_opt\_lvl}
Sets the optimization level for the trie to trie transformation
The possible values for this flag are any integer
\paragraph{}
\texttt{compare\_opt\_lvl}
Flag telling whether to use comparison mode for the optimization level.
The possible values for this flag are true or false.
\paragraph{}
\texttt{db\_min\_prefix}
Sets the minimum size of the prefix for dbtrie to optimize.
The possible values for this flag are any integer
\paragraph{}
\texttt{use\_naive\_trie}
Flag telling whether to use the naive algorithm to generate bdd scripts.
The possible values for this flag are true or false.
\paragraph{}
\texttt{use\_old\_trie}
Flag telling whether to use the old not nested trie to trie transformation.
The possible values for this flag are true or false.
\paragraph{}
\texttt{use\_dec\_trie}
Flag telling whether to use the decomposition method.
The possible values for this flag are true or false.
\paragraph{}
\texttt{subset\_check}
Flag telling whether to perform subset check in nested tries.
The possible values for this flag are true or false.
\paragraph{}
\texttt{deref\_terms}
Flag telling whether to dereference BDD terms after their last use.
The possible values for this flag are true or false.
\paragraph{}
\texttt{trie\_preprocess}
Flag telling whether to perform a preprocess step to nested tries.
The possible values for this flag are true or false.
\paragraph{}
\texttt{refine\_anclst}
Flag telling whether to refine the ancestor list with their children.
The possible values for this flag are true or false.
\paragraph{}
\texttt{anclst\_represent}
Flag that sets the representation of the ancestor list.
The possible values for this flag are list or integer
\paragraph{}
\texttt{max\_depth}
Sets the maximum proof depth.
The possible values for this flag are any integer.
\paragraph{}
\texttt{retain\_tables}
Flag telling whether to retain tables after the query.
The possible values for this flag are true or false.
\paragraph{}
\texttt{mc\_batchsize}
Flag related to Monte Carlo Sampling that sets the number of samples before update.
The possible values for this flag are any integer greater than zero.
\paragraph{}
\texttt{min\_mc\_samples}
Flag related to Monte Carlo Sampling that sets the minimum number of samples before convergence.
The possible values for this flag are any integer greater than or equal to zero.
\paragraph{}
\texttt{max\_mc\_samples}
Flag related to Monte Carlo Sampling that sets the maximum number of samples waiting to converge.
The possible values for this flag are any integer greater than or equal to zero.
\paragraph{}
\texttt{randomizer}
Flag related to Monte Carlo Sampling telling whether the random numbers are repeatable or not.
The possible values for this flag are repeatable or nonrepeatable.
\paragraph{}
\texttt{search\_method}
Flag related to DNF Monte Carlo Sampling that sets the search method for picking the proof.
The possible values for this flag are linear or binary.
\paragraph{}
\texttt{represent\_world}
Flag related to Monte Carlo Sampling that sets the structure that represents sampled world.
The possible values for this flag are list, record, array or hash\_table
\paragraph{}
\texttt{first\_threshold}
Flag related to inference that sets the starting threshold of iterative deepening.
The possible values for this flag are a number in the interval (0,1).
\paragraph{}
\texttt{last\_threshold}
Flag related to inference that sets the stopping threshold of iterative deepening.
The possible values for this flag are a number in the interval (0,1).
\paragraph{}
\texttt{id\_stepsize}
Flag related to inference that sets the threshold shrinking factor of iterative deepening.
The possible values for this flag are a number in the interval [0,1].
\paragraph{}
\texttt{prunecheck}
Flag related to inference telling whether to stop derivations including all facts of known proofs.
The possible values for this flag are on or off.
\paragraph{}
\texttt{maxsteps}
Flag related to inference that sets the max. number of prob. steps per derivation.
The possible values for this flag are any integer greater than zero.
\paragraph{}
\texttt{mc\_logfile}
Flag related to MCMC that sets the logfile for montecarlo.
The possible values for this flag are any valid filename.
\paragraph{}
\texttt{bdd\_time}
Flag related to BDD that sets the BDD computation timeout in seconds.
The possible values for this flag are any integer greater than zero.
\paragraph{}
\texttt{bdd\_par\_file}
Flag related to BDD that sets the file for BDD variable parameters.
The possible values for this flag are any valid filename.
\paragraph{}
\texttt{bdd\_result}
Flag related to BDD that sets the file to store result calculated from BDD.
The possible values for this flag are any valid filename.
\paragraph{}
\texttt{bdd\_file}
Flag related to BDD that sets the file for the BDD script.
The possible values for this flag are any valid filename.
\paragraph{}
\texttt{save\_bdd}
Flag related to BDD telling whether to save BDD files for (last) lower bound.
The possible values for this flag are true or false.
\paragraph{}
\texttt{dynamic\_reorder}
Flag related to BDD telling whether to use dynamic re-ordering for BDD.
The possible values for this flag are true or false.
\paragraph{}
\texttt{bdd\_static\_order}
Flag related to BDD telling whether to use static order.
The possible values for this flag are true or false.
\paragraph{}
\texttt{static\_order\_file}
Flag related to BDD that sets the file for BDD static order.
The possible values for this flag are any valid filename.
\paragraph{}
\texttt{verbose}
Flag telling whether to output intermediate information.
The possible values for this flag are true or false.
\paragraph{}
\texttt{show\_proofs}
Flag telling whether to output proofs.
The possible values for this flag are true or false.
\paragraph{}
\texttt{triedump}
Flag telling whether to generate the file: trie\_file containing the trie structure.
The possible values for this flag are true or false.
\paragraph{}
\texttt{dir}
Flag telling the location of the output files directory.
The possible values for this flag are any valid directory name.
\subsection{set\_problog\_flag}
\textit{set\_problog\_flag(+Name, +Value)}
\paragraph{}
This predicate sets the value of the given flag. The supported flags are the ones listed in above.
\subsection{learning\_flags}
\textit{learning\_flags}
\paragraph{}
This predicate lists all the learning flags name, value, domain and description.
\subsection{learning\_flag}
\textit{learning\_flag(+Name, -Value)}
\paragraph{}
This predicate gives the value of the learning flag with the specified name. The supported flags are:
\paragraph{}
\texttt{output\_directory}
Flag setting the directory where to store results.
The possible values for this flag are any valid path name.
\paragraph{}
\texttt{query\_directory}
Flag setting the directory where to store BDD files.
The possible values for this flag are any valid path name.
\paragraph{}
\texttt{verbosity\_level}
Flag telling how much output shall be given.
The possible values for this flag are an integer between 0 and 5 (0=nothing, 5=all).
\paragraph{}
\texttt{reuse\_initialized\_bdds}
Flag telling whether to reuse BDDs from previous runs.
The possible values for this flag are true or false.
\paragraph{}
\texttt{rebuild\_bdds}
Flag telling whether to rebuild BDDs every nth iteration.
The possible values for this flag are any integer greater or equal to zero (0=never).
\paragraph{}
\texttt{check\_duplicate\_bdds}
Flag telling whether to store intermediate results in hash table.
The possible values for this flag are true or false.
\paragraph{}
\texttt{init\_method}
Flag setting the ProbLog predicate to search proofs.
The possible values for this flag are of the form: (+Query,-P,+BDDFile,+ProbFile,+Call). For example: A,B,C,D,problog\_kbest\_save(A,100,B,E,C,D)
\paragraph{}
\texttt{probability\_initializer}
Flag setting the ProbLog predicate to initialize probabilities.
The possible values for this flag are of the form: (+FactID,-P,+Call). For example: A,B,random\_probability(A,B)
\paragraph{}
\texttt{log\_frequency}
Flag telling whether to log results every nth iteration.
The possible values for this flag are any integer greater than zero.
\paragraph{}
\texttt{alpha}
Flag setting the weight of negative examples.
The possible values for this flag are number or "auto" (auto=n\_p/n\_n).
\paragraph{}
\texttt{slope}
Flag setting the slope of the sigmoid function.
The possible values for this flag are any real number greater than zero.
\paragraph{}
\texttt{learning\_rate}
Flag setting the default Learning rate (if line\_search=false)
The possible values for this flag are any number greater than zero or "examples``
\paragraph{}
\texttt{line\_search}
Flag telling whether to use line search to estimate the learning rate.
The possible values for this flag are true or false.
\paragraph{}
\texttt{line\_search\_tau}
Flag setting the Tau value for line search.
The possible values for this flag are a number in the interval (0,1).
\paragraph{}
\texttt{line\_search\_tolerance}
Flag setting the tolerance value for line search.
The possible values for this flag are any number greater than zero.
\paragraph{}
\texttt{line\_search\_interval}
Flag setting the interval for line search.
The possible values for this flag are of the form a,b where a and b are numbers and define an interval with $0<=a<b$
\paragraph{}
\texttt{line\_search\_never\_stop}
Flag telling whether to make tiny step if line search returns 0.
The possible values for this flag are true or false.
\subsection{set\_learning\_flag}
\textit{set\_learning\_flag(+Name, +Value)}
\paragraph{}
This predicate sets the value of the given learning flag. The supported flags are the ones listed in above.
\section{Further Help}
\paragraph{}
To access the help information in ProbLog type:
\textit{problog\_help.}
\paragraph{}
Further information about ProbLog can also be found at:
http://dtai.cs.kuleuven.be/problog/index.html
\end{document}

View File

@ -206,124 +206,30 @@
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ProbLog inference
%
% assumes probabilistic facts as Prob::Fact and clauses in normal Prolog format
%
% provides following inference modes (16/12/2008):
% - approximation with interval width Delta (IJCAI07): problog_delta(+Query,+Delta,-Low,-High,-Status)
% - bounds based on single probability threshold: problog_threshold(+Query,+Threshold,-Low,-High,-Status)
% - as above, but lower bound only: problog_low(+Query,+Threshold,-Low,-Status)
% - lower bound based on K most likely proofs: problog_kbest(+Query,+K,-Low,-Status)
% - explanation probability (ECML07): problog_max(+Query,-Prob,-FactsUsed)
% - exact probability: problog_exact(+Query,-Prob,-Status)
% - sampling: problog_montecarlo(+Query,+Delta,-Prob)
%
%
% angelika.kimmig@cs.kuleuven.be
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
@defgroup ProbLog1 The Leuven ProbLog1 System
@ingroup packages
@brief This document is intended as a user guide for the users of ProbLog. ProbLog is a probabilistic Prolog, a probabilistic logic programming language, which is integrated in YAP-Prolog.
## Installing ProbLog
### Requirements
For installing and running ProbLog, the following are required:
+ a reasonable up-to-date computer, running Linux or Mac OS
+ YAP Prolog 5.1.3 (for Mac OS the more recent version 5.1.4 is needed) or YAP-6
### Download
To install ProbLog1, it is first necessary to download SimpleCUDD or CUDD. YAP Prolog also needs to be downloaded if it is not already installed on the machine
For downloading SimpleCUDD, go to:
+ http://www.cs.kuleuven.be/$sim$theo/tools/SimpleCUDD.tar.gz
You can also use the CUDD interface package in YAP. You will need to
1. If a Fedora user, CUDD is just available.
2. If a Mac user, there is a ports package.
3. Otherwise, you can obtain the version at . This version compiles under WIN32.
Last, when you configure YAP you need to add the options --with-cidd --enable-bddlib. Binary distributed versions already have the interface.
## Running ProbLog
To use ProbLog, the ProbLog module has to be loaded at the top of your Prolog programs. This is done with the following statement:
~~~~
:- use_module(library(problog)).
~~~~
Similarly, to compile the ProbLog learning module, use:
~~~~
:- use_module(library(problog_learning)).
~~~~
or
~~~~
:- use_module(library(problog_learning_lbdd)).
~~~~
## Encoding Probabilistic Facts
A probabilistic fact is encoded in ProbLog by preceding a predicate with a probability value. For example:
~~~~
0.5::heads(_).
~~~~
encodes the fact that there's 50% chance of getting heads when tossing an unbiassed coin.
### Encoding Parameter Learning Facts
Instead of probabilities every fact has a t( ) prefix. The t stands for tunable and indicate that ProbLog should learn the probability. The number between the parentheses indicates the ground truth probability. It is ignored by the learning algorithm and if you do not know the ground truth, you can write t(_). The ground truth is used after learning to estimate the distance of the learned model parameters to the ground truth model parameters. For example:
~~~~
t(0.5)::heads(_).
~~~~
*/
/** @defgroup ProbLogPredicates ProbLog Predicates
@ingroup ProbLog1
This chapter describes the predicates defined by ProbLog for evaluating the probability of queries.
In the description of the arguments of functors the following notation will be used:
+ a preceding plus sign will denote an argument as an "input argument" - it cannot be a free variable at the time of the call
+ a preceding minus sign will denote an "output argument"
+ an argument with no preceding symbol can be used in both ways
/**
* @pred problog_max(+G, -Prob, -FactsUsed)
/** @defgroup ProbLogPredicates Computing Probabilities of Events
* @ingroup problog
*
This predicate returns the most likely explanation of proving the goal G and the facts used in achieving this explanation.
*/
/**
* @pred problog_exact(+G, -Prob, -Status)
* This chapter describes the predicates defined by ProbLog for evaluating the probability of queries.
*
This predicate returns the exact total probability of achieving the goal G and the status of the query.
*/
/**
* @pred problog_kbest(+G, +K, -Prob, -Status)
*@{
*
This predicate returns the sum of the probabilities of the best K proofs of achieving the goal G and the status of the query.
*/
/**
* @pred problog_montecarlo(+G, +Interval_width, -Prob)
* ProbLog inference
*
This predicate approximates the probability of achieving the goal G by using a Monte Carlo approach, with 95% confidence in the given interval width.
* assumes probabilistic facts as Prob::Fact and clauses in normal Prolog format
*
* provides following inference modes (16/12/2008):
* - approximation with interval width Delta (IJCAI07): problog_delta(+Query,+Delta,-Low,-High,-Status)
* - bounds based on single probability threshold: problog_threshold(+Query,+Threshold,-Low,-High,-Status)
* - as above, but lower bound only: problog_low(+Query,+Threshold,-Low,-Status)
* - lower bound based on K most likely proofs: problog_kbest(+Query,+K,-Low,-Status)
* - explanation probability (ECML07): problog_max(+Query,-Prob,-FactsUsed)
* - exact probability: problog_exact(+Query,-Prob,-Status)
* - sampling: problog_montecarlo(+Query,+Delta,-Prob)
*
*
* angelika.kimmig@cs.kuleuven.be
*/
/**
@ -344,10 +250,19 @@ This predicate returns the lower and upper bound of the probability of achieving
This predicate returns the lower bound of the probability of achieving the goal G obtained by cutting the sld tree at the given probability for each branch.
*/
/**
@pred problog_help.
To access the help information in ProbLog type:
*/
%%@}
%%@{
/**
@defgroup ProbLogParameterLearning ProbLog Parameter Learning Predicates
@ingroup ProbLog1
@ingroup ProbLogI
@{
*/
@ -381,319 +296,20 @@ The output is created in the output subfolder of the current folder where YAP wa
1
Starts the learning algorithm. The learning will stop after N iterations or if the difference of the Mean Squared Error (MSE) between two iterations gets smaller than Epsilon - depending on what happens first.
*/
@paragraph Learning Output
---------------
%% @}
/** @defgroup ProbLogMiscellaneous ProbLog Miscellaneous Predicates
@ingroup ProbLog1
@{
Both the learning and the inference module have various parameters, or flags, that can be adjusted by the user.
The following predicates are defined by ProbLog to access and set these flags.
The output is created in the output subfolder of the current folder
where YAP was started. There you will find the file log.dat which
contains MSE on training and test set for every iteration, the timings,
and some metrics on the gradient in CSV format. The files
factprobs_N.pl contain the fact probabilities after the Nth iteration
and the files predictions_N.pl contain the estimated probabilities for
each training and test example - per default these file are generated
every 5th iteration only.
*/
/**
* @pred problog_flags
*
This predicate lists all the flags name, value, domain and description.
*/
/** @pred problog_flag(+Name, -Value)
This predicate gives the value of the flag with the specified name. The supported flags are:
+ use_db_trie
Flag telling whether to use the builtin trie to trie transformation.
The possible values for this flag are true or false.
+ db_trie_opt_lvl
Sets the optimization level for the trie to trie transformation
The possible values for this flag are any integer
+ compare_opt_lvl
Flag telling whether to use comparison mode for the optimization level.
The possible values for this flag are true or false.
+ db_min_prefix
Sets the minimum size of the prefix for dbtrie to optimize.
The possible values for this flag are any integer
+ use_naive_trie
Flag telling whether to use the naive algorithm to generate bdd scripts.
The possible values for this flag are true or false.
+ use_old_trie
Flag telling whether to use the old not nested trie to trie transformation.
The possible values for this flag are true or false.
+ use_dec_trie
Flag telling whether to use the decomposition method.
The possible values for this flag are true or false.
+ subset_check
Flag telling whether to perform subset check in nested tries.
The possible values for this flag are true or false.
+ deref_terms
Flag telling whether to dereference BDD terms after their last use.
The possible values for this flag are true or false.
+ trie_preprocess
Flag telling whether to perform a preprocess step to nested tries.
The possible values for this flag are true or false.
+ refine_anclst
Flag telling whether to refine the ancestor list with their children.
The possible values for this flag are true or false.
+ anclst_represent
Flag that sets the representation of the ancestor list.
The possible values for this flag are list or integer
+ max_depth
Sets the maximum proof depth.
The possible values for this flag are any integer.
+ retain_tables
Flag telling whether to retain tables after the query.
The possible values for this flag are true or false.
+ mc_batchsize
Flag related to Monte Carlo Sampling that sets the number of samples before update.
The possible values for this flag are any integer greater than zero.
+ min_mc_samples
Flag related to Monte Carlo Sampling that sets the minimum number of samples before convergence. The possible values for this flag are any integer greater than or equal to zero.
+ max_mc_samples
Flag related to Monte Carlo Sampling that sets the maximum number of samples waiting to converge.
The possible values for this flag are any integer greater than or equal to zero.
+ randomizer
Flag related to Monte Carlo Sampling telling whether the random numbers are repeatable or not.
The possible values for this flag are repeatable or nonrepeatable.
+ search_method
Flag related to DNF Monte Carlo Sampling that sets the search method for picking the proof.
The possible values for this flag are linear or binary.
+ represent_world
Flag related to Monte Carlo Sampling that sets the structure that represents sampled world.
The possible values for this flag are list, record, array or hash_table
+ first_threshold
Flag related to inference that sets the starting threshold of iterative deepening.
The possible values for this flag are a number in the interval (0,1).
+ last_threshold
Flag related to inference that sets the stopping threshold of iterative deepening.
The possible values for this flag are a number in the interval (0,1).
+ id_stepsize
Flag related to inference that sets the threshold shrinking factor of iterative deepening.
The possible values for this flag are a number in the interval [0,1].
+ prunecheck
Flag related to inference telling whether to stop derivations including all facts of known proofs.
The possible values for this flag are on or off.
+ maxsteps
Flag related to inference that sets the max. number of prob. steps per derivation.
The possible values for this flag are any integer greater than zero.
+ mc_logfile
Flag related to MCMC that sets the logfile for montecarlo.
The possible values for this flag are any valid filename.
+ bdd_time
Flag related to BDD that sets the BDD computation timeout in seconds.
The possible values for this flag are any integer greater than zero.
+ bdd_par_file
Flag related to BDD that sets the file for BDD variable parameters.
The possible values for this flag are any valid filename.
+ bdd_result
Flag related to BDD that sets the file to store result calculated from BDD.
The possible values for this flag are any valid filename.
+ bdd_file
Flag related to BDD that sets the file for the BDD script.
The possible values for this flag are any valid filename.
+ save_bdd
Flag related to BDD telling whether to save BDD files for (last) lower bound.
The possible values for this flag are true or false.
+ dynamic_reorder
Flag related to BDD telling whether to use dynamic re-ordering for BDD.
The possible values for this flag are true or false.
+ bdd_static_order
Flag related to BDD telling whether to use static order.
The possible values for this flag are true or false.
+ static_order_file
Flag related to BDD that sets the file for BDD static order.
The possible values for this flag are any valid filename.
+ verbose
Flag telling whether to output intermediate information.
The possible values for this flag are true or false.
+ show_proofs
Flag telling whether to output proofs.
The possible values for this flag are true or false.
+ triedump
Flag telling whether to generate the file: trie_file containing the trie structure.
The possible values for this flag are true or false.
+ dir
Flag telling the location of the output files directory.
The possible values for this flag are any valid directory name.
*/
/** @pred set_problog_flag(+Name, +Value)
the predicate sets the value of the given flag. The supported flags are the ones listed in above
*/
/** @pred learning_flags
the predicate sets the value of the given flag. The supported flags are the ones listed in above
*/
/** @pred learning_flag(+Name, -Value)
This predicate gives the value of the learning flag with the specified name. The supported flags are:
+ output_directory
Flag setting the directory where to store results.
The possible values for this flag are any valid path name.
+ query_directory
Flag setting the directory where to store BDD files.
The possible values for this flag are any valid path name.
+ verbosity_level
Flag telling how much output shall be given.
The possible values for this flag are an integer between 0 and 5 (0=nothing, 5=all).
+ reuse_initialized_bdds
Flag telling whether to reuse BDDs from previous runs.
The possible values for this flag are true or false.
+ rebuild_bdds
Flag telling whether to rebuild BDDs every nth iteration.
The possible values for this flag are any integer greater or equal to zero (0=never).
+ check_duplicate_bdds
Flag telling whether to store intermediate results in hash table.
The possible values for this flag are true or false.
+ init_method
Flag setting the ProbLog predicate to search proofs.
The possible values for this flag are of the form: (+Query,-P,+BDDFile,+ProbFile,+Call). For example: A,B,C,D,problog_kbest_save(A,100,B,E,C,D)
+ probability_initializer
Flag setting the ProbLog predicate to initialize probabilities.
The possible values for this flag are of the form: (+FactID,-P,+Call). For example: A,B,random_probability(A,B)
+ log_frequency
Flag telling whether to log results every nth iteration.
The possible values for this flag are any integer greater than zero.
+ alpha
Flag setting the weight of negative examples.
The possible values for this flag are number or "auto" (auto=n_p/n_n).
+ slope
Flag setting the slope of the sigmoid function.
The possible values for this flag are any real number greater than zero.
+ learning_rate
Flag setting the default Learning rate (if line_search=false)
The possible values for this flag are any number greater than zero or "examples``
+ line_search
Flag telling whether to use line search to estimate the learning rate.
The possible values for this flag are true or false.
+ line_search_tau
Flag setting the Tau value for line search.
The possible values for this flag are a number in the interval (0,1).
+ line_search_tolerance
Flag setting the tolerance value for line search.
The possible values for this flag are any number greater than zero.
+ line_search_interval
Flag setting the interval for line search.
*/
%% @}
:- module(problog, [problog_koptimal/3,
problog_koptimal/4,
@ -2820,21 +2436,25 @@ eval_upper(N,UpP,ok) :-
up(_,UpP)
).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% explanation probability - returns list of facts used or constant 'unprovable' as third argument
% problog_max(+Goal,-Prob,-Facts)
%
% uses iterative deepening with samw parameters as bounding algorithm
% threshold gets adapted whenever better proof is found
%
% uses local dynamic predicates max_probability/1 and max_proof/1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
@pred problog_max(+G, -Prob, -FactsUsed)
This predicate returns the most likely explanation of proving the goal G
and the facts used in achieving this explanation.
explanation probability - returns list of facts used or constant 'unprovable' as third argument
problog_max(+Goal,-Prob,-Facts)
uses iterative deepening with samw parameters as bounding algorithm
threshold gets adapted whenever better proof is found
uses local dynamic predicates max_probability/1 and max_proof/1
*/
problog_max(Goal, Prob, Facts) :-
problog_flag(first_threshold,InitT),
init_problog_max(InitT),
problog_control(off,up),
problog_max_id(Goal, Prob, FactIDs),% theo todo
problog_max_id(Goal, Prob, FactIDs),theo todo
( FactIDs = [_|_] -> get_fact_list(FactIDs, Facts);
Facts = FactIDs).
@ -2919,6 +2539,12 @@ problog_kbest_save(Goal, K, Prob, Status, BDDFile, ParamFile) :-
% ;
% true).
/**
* @pred problog_kbest(+G, +K, -Prob, -Status)
*
* This predicate returns the sum of the probabilities of the best K proofs of achieving the goal G and the status of the query.
*/
problog_kbest(Goal, K, Prob, Status) :-
problog_flag(first_threshold,InitT),
init_problog_kbest(InitT),
@ -3060,13 +2686,14 @@ to_external_format_with_reverse([LogP-FactIDs|Intern],Acc,Extern) :-
Facts = FactIDs),
to_external_format_with_reverse(Intern,[Prob-Facts|Acc],Extern).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% exact probability
% problog_exact(+Goal,-Prob,-Status)
%
% using all proofs = using all proofs with probability > 0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
* @pred problog_exact(+G, -Prob, -Status)
*
This predicate returns the exact total probability of achieving the goal G and the status of the query.
using all proofs = using all proofs with probability > 0
*/
problog_exact(Goal,Prob,Status) :-
problog_control(on, exact),
problog_low(Goal,0,Prob,Status),
@ -3132,13 +2759,17 @@ problog_exact_nested(Goal, Prob, Status):-
delete_ptree(Trie_Completed_Proofs),
problog_restore_state(State).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% probability by sampling:
% running another N samples until 95percentCI-width<Delta
% lazy sampling using three-valued array indexed by internal fact IDs for ground facts,
% internal database keys mc_true and mc_false for groundings of non-ground facts (including dynamic probabilities)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
/**
* @pred problog_montecarlo(+G, +Interval_width, -Prob)
*
* This predicate approximates the probability of achieving the goal G by using a Monte Carlo approach, with 95% confidence in the given interval width.
*
* probability by sampling:
* running another N samples until 95percentCI-width<Delta
* lazy sampling using three-valued array indexed by internal fact IDs for ground facts,
* internal database keys mc_true and mc_false for groundings of non-ground facts (including dynamic probabilities)
*/
problog_montecarlo(Goal,Delta,Prob) :-
retractall(mc_prob(_)),
nb_getval(probclause_counter,ID), !,

View File

@ -204,6 +204,8 @@
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% @file problog/flags
:-module(flags, [problog_define_flag/4,
problog_define_flag/5,
problog_define_flag/6,
@ -218,6 +220,314 @@
:- use_module(logger).
:- use_module(library(system), [file_exists/1, delete_file/1]).
/** @defgroup ProbLogMiscellaneous ProbLog Miscellaneous Predicates
@ingroup problog
@{
Both the learning and the inference module have various parameters, or flags, that can be adjusted by the user.
The following predicates are defined by ProbLog to access and set these flags.
*/
/**
* @pred problog_flags
*
This predicate lists all the flags name, value, domain and description.
*/
/** @pred problog_flag(+Name, -Value)
This predicate gives the value of the flag with the specified name. The supported flags are:
+ use_db_trie
Flag telling whether to use the builtin trie to trie transformation.
The possible values for this flag are true or false.
+ db_trie_opt_lvl
Sets the optimization level for the trie to trie transformation
The possible values for this flag are any integer
+ compare_opt_lvl
Flag telling whether to use comparison mode for the optimization level.
The possible values for this flag are true or false.
+ db_min_prefix
Sets the minimum size of the prefix for dbtrie to optimize.
The possible values for this flag are any integer
+ use_naive_trie
Flag telling whether to use the naive algorithm to generate bdd scripts.
The possible values for this flag are true or false.
+ use_old_trie
Flag telling whether to use the old not nested trie to trie transformation.
The possible values for this flag are true or false.
+ use_dec_trie
Flag telling whether to use the decomposition method.
The possible values for this flag are true or false.
+ subset_check
Flag telling whether to perform subset check in nested tries.
The possible values for this flag are true or false.
+ deref_terms
Flag telling whether to dereference BDD terms after their last use.
The possible values for this flag are true or false.
+ trie_preprocess
Flag telling whether to perform a preprocess step to nested tries.
The possible values for this flag are true or false.
+ refine_anclst
Flag telling whether to refine the ancestor list with their children.
The possible values for this flag are true or false.
+ anclst_represent
Flag that sets the representation of the ancestor list.
The possible values for this flag are list or integer
+ max_depth
Sets the maximum proof depth.
The possible values for this flag are any integer.
+ retain_tables
Flag telling whether to retain tables after the query.
The possible values for this flag are true or false.
+ mc_batchsize
Flag related to Monte Carlo Sampling that sets the number of samples before update.
The possible values for this flag are any integer greater than zero.
+ min_mc_samples
Flag related to Monte Carlo Sampling that sets the minimum number of samples before convergence. The possible values for this flag are any integer greater than or equal to zero.
+ max_mc_samples
Flag related to Monte Carlo Sampling that sets the maximum number of samples waiting to converge.
The possible values for this flag are any integer greater than or equal to zero.
+ randomizer
Flag related to Monte Carlo Sampling telling whether the random numbers are repeatable or not.
The possible values for this flag are repeatable or nonrepeatable.
+ search_method
Flag related to DNF Monte Carlo Sampling that sets the search method for picking the proof.
The possible values for this flag are linear or binary.
+ represent_world
Flag related to Monte Carlo Sampling that sets the structure that represents sampled world.
The possible values for this flag are list, record, array or hash_table
+ first_threshold
Flag related to inference that sets the starting threshold of iterative deepening.
The possible values for this flag are a number in the interval (0,1).
+ last_threshold
Flag related to inference that sets the stopping threshold of iterative deepening.
The possible values for this flag are a number in the interval (0,1).
+ id_stepsize
Flag related to inference that sets the threshold shrinking factor of iterative deepening.
The possible values for this flag are a number in the interval [0,1].
+ prunecheck
Flag related to inference telling whether to stop derivations including all facts of known proofs.
The possible values for this flag are on or off.
+ maxsteps
Flag related to inference that sets the max. number of prob. steps per derivation.
The possible values for this flag are any integer greater than zero.
+ mc_logfile
Flag related to MCMC that sets the logfile for montecarlo.
The possible values for this flag are any valid filename.
+ bdd_time
Flag related to BDD that sets the BDD computation timeout in seconds.
The possible values for this flag are any integer greater than zero.
+ bdd_par_file
Flag related to BDD that sets the file for BDD variable parameters.
The possible values for this flag are any valid filename.
+ bdd_result
Flag related to BDD that sets the file to store result calculated from BDD.
The possible values for this flag are any valid filename.
+ bdd_file
Flag related to BDD that sets the file for the BDD script.
The possible values for this flag are any valid filename.
+ save_bdd
Flag related to BDD telling whether to save BDD files for (last) lower bound.
The possible values for this flag are true or false.
+ dynamic_reorder
Flag related to BDD telling whether to use dynamic re-ordering for BDD.
The possible values for this flag are true or false.
+ bdd_static_order
Flag related to BDD telling whether to use static order.
The possible values for this flag are true or false.
+ static_order_file
Flag related to BDD that sets the file for BDD static order.
The possible values for this flag are any valid filename.
+ verbose
Flag telling whether to output intermediate information.
The possible values for this flag are true or false.
+ show_proofs
Flag telling whether to output proofs.
The possible values for this flag are true or false.
+ triedump
Flag telling whether to generate the file: trie_file containing the trie structure.
The possible values for this flag are true or false.
+ dir
Flag telling the location of the output files directory.
The possible values for this flag are any valid directory name.
*/
/** @pred set_problog_flag(+Name, +Value)
the predicate sets the value of the given flag. The supported flags are the ones listed in above
*/
/** @pred learning_flags
the predicate sets the value of the given flag. The supported flags are the ones listed in above
*/
/** @pred learning_flag(+Name, -Value)
This predicate gives the value of the learning flag with the specified name. The supported flags are:
+ output_directory
Flag setting the directory where to store results.
The possible values for this flag are any valid path name.
+ query_directory
Flag setting the directory where to store BDD files.
The possible values for this flag are any valid path name.
+ verbosity_level
Flag telling how much output shall be given.
The possible values for this flag are an integer between 0 and 5 (0=nothing, 5=all).
+ reuse_initialized_bdds
Flag telling whether to reuse BDDs from previous runs.
The possible values for this flag are true or false.
+ rebuild_bdds
Flag telling whether to rebuild BDDs every nth iteration.
The possible values for this flag are any integer greater or equal to zero (0=never).
+ check_duplicate_bdds
Flag telling whether to store intermediate results in hash table.
The possible values for this flag are true or false.
+ init_method
Flag setting the ProbLog predicate to search proofs.
The possible values for this flag are of the form: (+Query,-P,+BDDFile,+ProbFile,+Call). For example: A,B,C,D,problog_kbest_save(A,100,B,E,C,D)
+ probability_initializer
Flag setting the ProbLog predicate to initialize probabilities.
The possible values for this flag are of the form: (+FactID,-P,+Call). For example: A,B,random_probability(A,B)
+ log_frequency
Flag telling whether to log results every nth iteration.
The possible values for this flag are any integer greater than zero.
+ alpha
Flag setting the weight of negative examples.
The possible values for this flag are number or "auto" (auto=n_p/n_n).
+ slope
Flag setting the slope of the sigmoid function.
The possible values for this flag are any real number greater than zero.
+ learning_rate
Flag setting the default Learning rate (if line_search=false)
The possible values for this flag are any number greater than zero or "examples``
+ line_search
Flag telling whether to use line search to estimate the learning rate.
The possible values for this flag are true or false.
+ line_search_tau
Flag setting the Tau value for line search.
The possible values for this flag are a number in the interval (0,1).
+ line_search_tolerance
Flag setting the tolerance value for line search.
The possible values for this flag are any number greater than zero.
+ line_search_interval
Flag setting the interval for line search.
*/
problog_define_flag(Flag, Type, Description, DefaultValue):-
flag_define(Flag, Type, DefaultValue, Description).
@ -405,3 +715,5 @@ problog_flag_validate_interval( (V1,V2) ) :-
V1<V2.
*/
%% @}

View File

@ -412,7 +412,7 @@ namespace generic_gecode
break;
case Optimizing::OPT_RATIO:
{
IntArgs c(2, sol.ivars[optim.den].val(),
IntArgs c = Gecode::IntArgs::create(2, sol.ivars[optim.den].val(),
- sol.ivars[optim.num].val());
IntVarArgs v(2);
v[0] = ivars[optim.num];

View File

@ -53,7 +53,6 @@ SET_PROPERTY(SOURCE ${MYDDAS_SOURCES}
${MYDDAS_UTIL_SOURCES}
${MYDDAS_HEADERS} PROPERTY COMPILE_DEFINITIONS YAP_KERNEL=1 )
MY_add_dependencies(myddas plmyddas)
add_subdirectory(pl)

View File

@ -9,74 +9,32 @@ set(MYDDAS_YPP
myddas_prolog2sql_optimizer.ypp)
set(MYDDAS_DRIVERS
"myddas_driver.ypp"
myddas_driver.ypp
)
if (ANDROID)
set (MYDDAS_PREFIX ${YAP_INSTALL_DATADIR} )
else()
set (MYDDAS_PREFIX ${CMAKE_CURRENT_BINARY_DIR} )
endif()
get_property(MYDDAS_FLAGS GLOBAL PROPERTY COMPILE_DEFINITIONS)
function(cpp_compile output filename)
get_filename_component(base ${filename} NAME_WE)
set(base_abs ${MYDDAS_PREFIX}/${base})
set(outfile ${base_abs}.yap)
set(${output} ${${output}} ${outfile} PARENT_SCOPE)
IF (MSVC)
add_custom_command(
OUTPUT ${outfile}
COMMAND ${CMAKE_C_COMPILER} ${MYDDAS_FLAGS} /EP /P ${outfile} ${CMAKE_CURRENT_SOURCE_DIR}/${filename}
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${filename}")
ELSE (MSVC)
add_custom_command(
OUTPUT ${outfile}
COMMAND ${CMAKE_C_COMPILER} ${MYDDAS_FLAGS} -x c -E -P -w ${CMAKE_CURRENT_SOURCE_DIR}/${filename} -o ${outfile}
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${filename}")
ENDIF (MSVC)
set_source_files_properties(${outfile} PROPERTIES GENERATED TRUE)
endfunction()
if (ANDROID)
set (MYDDAS_PL_OUTDIR ${YAP_APP_DIR}/src/generated/assets/Yap )
else()
set (MYDDAS_PL_OUTDIR ${CMAKE_CURRENT_BINARY_DIR} )
endif()
function(cpp_driver output dbms filename)
set(outfile ${MYDDAS_PL_OUTDIR}/myddas_${dbms}.yap)
set(${output} ${${output}} ${outfile} PARENT_SCOPE)
IF (MSVC)
add_custom_command(
OUTPUT ${outfile}
COMMAND ${CMAKE_C_COMPILER} -D${dbms} /EP /P ${outfile} ${CMAKE_CURRENT_SOURCE_DIR}/${filename}
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${filename}")
else ()
add_custom_command(
OUTPUT ${outfile}
COMMAND ${CMAKE_C_COMPILER} -D${dbms} -x c -E -P -w ${CMAKE_CURRENT_SOURCE_DIR}/${filename} -o ${outfile}
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${filename}")
ENDIF (MSVC)
set_source_files_properties(${outfile} PROPERTIES GENERATED TRUE)
endfunction()
set(MYDDAS_DBMS sqlite3 postgres odbc)
foreach (file ${MYDDAS_YPP})
cpp_compile(MYDDAS_YAP ${file})
endforeach ()
foreach (driver ${MYDDAS_DBMS})
cpp_driver(MYDDAS_YAP ${driver} myddas_driver.ypp)
endforeach ()
set (MYDDAS_PL_OUTDIR ${YAP_APP_DIR}/src/generated/assets/Yap )
get_property(MYDDAS_FLAGS GLOBAL PROPERTY COMPILE_DEFINITIONS)
foreach (filename in ${MYDDAS_YPP})
get_filename_component(base ${filename} NAME_WE)
set(base_abs ${MYDDAS_PL_OUTDIR}/${base})
set(outfile ${base_abs}.yap)
execute_process(
COMMAND ${CMAKE_C_COMPILER} ${MYDDAS_FLAGS} -x c -E -P -w ${CMAKE_CURRENT_SOURCE_DIR}/${filename} -o ${outfile}
)
set_source_files_properties(outfile PROPERTIES GENERATED TRUE)
endforeach ()
foreach (dbms in ${MYDDAS_DBMS} )
set(outfile ${MYDDAS_PL_OUTDIR}/myddas_${dbms}.yap)
execute_process(
COMMAND ${CMAKE_C_COMPILER} -D${dbms} -x c -E -P -w ${CMAKE_CURRENT_SOURCE_DIR}/myddas_driver.ypp -o ${outfile}
)
list (APPEND MYDDAS_YAP ${CMAKE_CURRENT_SOURCE_DIR}/../sqlite3/sqlitest.yap ${CMAKE_CURRENT_SOURCE_DIR}/../sqlite3/chinook.db)
add_to_group(MYDDAS_YAP pl_library )
set_source_files_properties(outfile PROPERTIES GENERATED TRUE)
add_custom_target(plmyddas ALL DEPENDS ${MYDDAS_YAP} )
endforeach()
install(FILES ${MYDDAS_YAP}
DESTINATION ${YAP_INSTALL_DATADIR}
)
set( MYDDAS_YAP ${CMAKE_CURRENT_SOURCE_DIR}/../sqlite3/sqlitest.yap ${CMAKE_CURRENT_SOURCE_DIR}/../sqlite3/chinook.db)
#add_to_group(MYDDAS_YAP pl_library )
file(INSTALL ${MYDDAS_YAP}
DESTINATION ${MYDDAS_PL_OUTDIR} )

View File

@ -1,150 +0,0 @@
#include "py4yap.h"
static foreign_t array_to_python_list(term_t addr, term_t type, term_t szt,
term_t py) {
void *src;
Py_ssize_t sz, i;
int is_float;
if (!PL_get_pointer(addr, &src) || !PL_get_bool(type, &is_float) ||
!PL_get_intptr(szt, &sz))
return false;
PyObject *list = PyList_New(sz);
if (!list)
return false;
if (is_float) {
double *v = (double *)src;
for (i = 0; i < sz; i++) {
PyObject *x = PyFloat_FromDouble(v[i]);
PyList_SET_ITEM(list, i, x);
}
} else {
YAP_Int *v = (YAP_Int *)src;
for (i = 0; i < sz; i++) {
PyObject *x = PyFloat_FromDouble(v[i]);
PyList_SET_ITEM(list, i, x);
}
}
if (PL_is_variable(py)) {
return address_to_term(list, py);
}
return assign_to_symbol(py, list);
}
static foreign_t array_to_python_tuple(term_t addr, term_t type, term_t szt,
term_t py) {
void *src;
Py_ssize_t sz, i;
int is_float;
if (!PL_get_pointer(addr, &src) || !PL_get_bool(type, &is_float) ||
!PL_get_intptr(szt, &sz))
return false;
PyObject *list = PyTuple_New(sz);
if (!list)
return false;
if (is_float) {
double *v = (double *)src;
for (i = 0; i < sz; i++) {
PyObject *x;
x = PyFloat_FromDouble(v[i]);
if (PyTuple_SetItem(list, i, x)) {
PyErr_Print();
return FALSE;
}
}
} else {
int32_t *v = (int32_t *)src;
PyObject *x;
for (i = 0; i < sz; i++) {
#if PY_MAJOR_VERSION < 3
x = PyInt_FromLong(v[i]);
#else
x = PyLong_FromLong(v[i]);
#endif
if (PyTuple_SetItem(list, i, x)) {
PyErr_Print();
return FALSE;
}
}
}
if (PL_is_variable(py)) {
return address_to_term(list, py);
}
return assign_to_symbol(py, list);
}
static foreign_t array_to_python_view(term_t addr, term_t type, term_t szt,
term_t colt, term_t py) {
void *src;
Py_ssize_t sz, rows;
int is_float;
Py_ssize_t shape[2];
if (!PL_get_pointer(addr, &src) || !PL_get_bool(type, &is_float) ||
!PL_get_intptr(szt, &sz) || !PL_get_intptr(colt, &rows))
return false;
Py_buffer buf;
buf.buf = src;
if (is_float) {
buf.len = sz * sizeof(double);
buf.itemsize = sizeof(double);
} else {
buf.len = sz * sizeof(YAP_Int);
buf.itemsize = sizeof(YAP_Int);
}
buf.readonly = false;
buf.format = NULL;
buf.ndim = 2;
buf.shape = shape;
buf.strides = NULL;
buf.suboffsets = NULL;
PyObject *o = PyMemoryView_FromBuffer(&buf);
if (!o) {
PyErr_Print();
return false;
}
if (PL_is_variable(py)) {
return address_to_term(o, py);
}
return assign_to_symbol(py, o);
}
static foreign_t prolog_list_to_python_list(term_t plist, term_t pyt, term_t tlen) {
size_t sz, i;
PyErr_Clear();
PyObject *pyl = term_to_python(pyt, true, NULL);
term_t targ = PL_new_term_ref();
if (PL_skip_list(plist, targ, &sz) <0 || ! PL_get_nil(targ)) {
pyErrorAndReturn( false, false);
}
if (!PyList_Check(pyl))
{
pyErrorAndReturn( false, false);
}
if (sz > PyList_GET_SIZE(pyl))
pyErrorAndReturn( false, false);
for (i=0; i < sz; i++) {
if (!PL_get_list(plist, targ, plist)) {
pyErrorAndReturn( false, false);
}
PyObject *t = term_to_python(targ, true, NULL);
PyList_SET_ITEM(pyl, i, t);
}
if (PL_is_variable(tlen)) {
PL_unify_int64(tlen, sz);
} else {
python_assign(tlen, PyLong_FromUnsignedLong(sz), NULL);
}
pyErrorAndReturn( true, false);
}
install_t install_pl2pl(void) {
PL_register_foreign("array_to_python_list", 4, array_to_python_list, 0);
PL_register_foreign("array_to_python_tuple", 4, array_to_python_tuple, 0);
PL_register_foreign("array_to_python_view", 5, array_to_python_view, 0);
PL_register_foreign("prolog_list_to_python_list", 3, prolog_list_to_python_list, 0);
}

View File

@ -1,214 +0,0 @@
#include "py4yap.h"
extern PyObject *py_Local, *py_Global;
PyObject *YE(term_t t, int line, const char *file, const char *code) {
YAPPy_ThrowError__(file, code, line, SYSTEM_ERROR_INTERNAL,t,"");
}
void YEM(const char *exp, int line, const char *file, const char *code) {
fprintf(stderr, "**** Warning,%s@%s:%d: failed while executing %s\n", code,
file, line, exp);
}
static PyObject *s_to_python(const char *s, bool eval, PyObject *p0) {
PyObject *o;
if (eval) {
o = PythonLookup(s, p0);
/* if (!o)
return o;
*/
} else {
o = PythonLookupSpecial(s);
}
if (o) {
Py_INCREF(o);
return CHECKNULL(YAP_MkStringTerm(s), o);
} else {
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
return pobj;
}
}
/**
* obtain the object matching a certain string.
*
* @param t handle to Prolog term
* @param t whether should try to evaluate evaluables.
*
* @return a Python object descriptor or NULL if failed
*/
X_API PyObject *string_to_python(const char *s, bool eval, PyObject *p0) {
char *buf = malloc(strlen(s) + 1), *child;
PyObject *p1;
while ((child = strchr(s, '.')) != NULL) {
size_t len = child - s;
strncpy(buf, s, len);
buf[len] = '\0';
p1 = s_to_python(buf, eval, p0);
Py_DecRef(p0);
Py_IncRef(p1)
s = child + 1;
p0 = p1;
}
p1 = s_to_python(s, eval, p0);
Py_DecRef(p0);
return p1;
}
/**
* term_to_python translates and evaluates from Prolog to Python
*
* @param t handle to Prolog term
* @param t whether should try to evaluate evaluables.
*
* @return a Python object descriptor or NULL if failed
*/
PyObject *term_to_python(term_t t, bool eval, PyObject *o) {
// o≈
PyObject *o;\
YAP_Term yt = YAP_GetFromSlot(t);
// Yap_DebugPlWriteln(yt);
switch (PL_term_type(t)) {
case PL_VARIABLE: {
if (t == 0) {
YAPPy_ThrowErrorYA(SYSTEM_ERROR_INTERNAL,t,"");
t }
PyObject *out = PyTuple_New(1);
PyTuple_SET_ITEM(out, 0, PyLong_FromLong(t));
Py_IncRef(out);
rc = term_to_nametuple("v", 1, out);
Py_IncRef(rc);
};
case PL_ATOM: {
YAP_Atom at = YAP_AtomOfTerm(yt);
const char *s;
s = YAP_AtomName(at);
if (eval) {
o = PythonLookup(s, o);
/* if (!o)
return o;
*/
} else {
o = PythonLookupSpecial(s);
}
if (o) {
Py_INCREF(o);
return CHECKNULL(t, o);
}
}
case PL_STRING: {
const char *s = NULL;
if (YAP_IsAtomTerm(yt)) {
s = YAP_AtomName(YAP_AtomOfTerm(yt));
} else if (YAP_IsStringTerm(yt)) {
s = YAP_StringOfTerm(yt);
} else {
return CHECKNULL(t, NULL);
}
#if PY_MAJOR_VERSION < 3
if (proper_ascii_string(s)) {
PyObject *o = PyString_FromStringAndSize(s, strlen(s));
Py_IncRef(o)
return CHECKNULL(t, o);
} else
#endif
{
// char *p = malloc(strlen(s)+1);
//strcpy(p, s);
PyObject *pobj = PyUnicode_FromString(s);
Py_IncRef(pobj);
return CHECKNULL(t, pobj);
}
} break;
case PL_INTEGER: {
int64_t j;
if (!PL_get_int64_ex(t, &j))
return CHECKNULL(t, NULL);
#if PY_MAJOR_VERSION < 3
PyObject *o = PyInt_FromLong(j);
return CHECKNULL(t, o);
#else
PyObject *o = PyLong_FromLong(j);
return CHECKNULL(t, o);
#endif
}
case PL_FLOAT: {
PyObject *out;
double fl;
if (!PL_get_float(t, &fl))
return CHECKNULL(t, NULL);
out = PyFloat_FromDouble(fl);
return CHECKNULL(t, out);
}
default: {
term_t tail = PL_new_term_ref(), arg;
size_t len, i;
if (PL_skip_list(t, tail, &len) && PL_get_nil(tail)) {
PyObject *out, *a;
arg = tail;
out = PyList_New(len);
if (!out) {
PL_reset_term_refs(tail);
return CHECKNULL(t, Py_None);
}
for (i = 0; i < len; i++) {
if (!PL_get_list(t, arg, t)) {
YAPPy_ThrowErrorYA(SYSTEM_ERROR_INTERNAL,t,"");
}
a = term_to_python(arg, eval, o);
if (a) {
if (PyList_SetItem(out, i, a) < 0) {
YAPPy_ThrowErrorYA(SYSTEM_ERROR_INTERNAL,t,"");
}
}
}
PL_reset_term_refs(tail);
return CHECKNULL(t, out);
} else {
functor_t fun;
PyObject *rc;
if (!PL_get_functor(t, &fun)) {
PL_reset_term_refs(tail);
return CHECKNULL(t, Py_None);
}
if (eval)
rc = compound_to_pyeval(t, o);
else
rc = compound_to_pytree(t, o);
PL_reset_term_refs(tail);
return rc;
}
}
}
return CHECKNULL(t, Py_None);
}
PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o) {
if (t == 0)
return NULL;
term_t yt = YAP_InitSlot(t);
o = term_to_python(yt, eval, o);
PL_reset_term_refs(yt);
return o;
}
PyObject *deref_term_to_python(term_t t) {
// Yap_DebugPlWrite(YAP_GetFromSlot(t)); fprintf(stderr, " here I
// am\n");
YAP_Term yt = YAP_GetFromSlot(t);
if (YAP_IsVarTerm(yt)) {
char s[32];
char *o = YAP_WriteBuffer(yt, s, 31, 0);
PyObject *p = PyUnicode_FromString(o);
return p;
}
return term_to_python(t, false, NULL);
}

View File

@ -1,319 +0,0 @@
#include "py4yap.h"
static foreign_t repr_term(PyObject *pVal, term_t t) {
term_t to = PL_new_term_ref(), t1 = PL_new_term_ref();
PL_put_pointer(t1, pVal);
PL_cons_functor(to, FUNCTOR_pointer1, t1);
Py_INCREF(pVal);
return PL_unify(t, to);
}
foreign_t assign_to_symbol(term_t t, PyObject *e);
foreign_t assign_to_symbol(term_t t, PyObject *e) {
char *s = NULL;
if (!PL_get_atom_chars(t, &s)) {
return false;
}
PyObject *dic;
if (!lookupPySymbol(s, NULL, &dic))
dic = py_Main;
return PyObject_SetAttrString(dic, s, e) == 0;
}
foreign_t python_to_term(PyObject *pVal, term_t t) {
bool rc = true;
term_t to = PL_new_term_ref();
// fputs(" <<*** ",stderr); PyObject_Print(pVal,stderr,0);
// fputs("<<***\n",stderr);
if (pVal == Py_None) {
// fputs("<<*** ",stderr);Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// >>***\n",stderr);
rc = PL_unify_atom(t, ATOM_none);
// fputs("<<*** ",stderr);Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// >>***\n",stderr);
} else if (PyBool_Check(pVal)) {
rc = rc && PL_unify_bool(t, PyObject_IsTrue(pVal));
} else if (PyLong_Check(pVal)) {
rc = rc && PL_unify_int64(t, PyLong_AsLong(pVal));
#if PY_MAJOR_VERSION < 3
} else if (PyInt_Check(pVal)) {
rc = rc && PL_unify_int64(t, PyInt_AsLong(pVal));
#endif
} else if (PyFloat_Check(pVal)) {
rc = rc && PL_unify_float(t, PyFloat_AsDouble(pVal));
} else if (PyComplex_Check(pVal)) {
term_t t1 = PL_new_term_ref(), t2 = PL_new_term_ref();
if (!PL_put_float(t1, PyComplex_RealAsDouble(pVal)) ||
!PL_put_float(t2, PyComplex_ImagAsDouble(pVal)) ||
!PL_cons_functor(to, FUNCTOR_complex2, t1, t2)) {
rc = false;
} else {
rc = rc && PL_unify(t, to);
}
} else if (PyUnicode_Check(pVal)) {
atom_t tmp_atom;
#if PY_MAJOR_VERSION < 3
size_t sz = PyUnicode_GetSize(pVal) + 1;
wchar_t *ptr = malloc(sizeof(wchar_t) * sz);
sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, ptr, sz - 1);
tmp_atom = PL_new_atom_wchars(sz, ptr);
free(ptr);
#else
const char *s = PyUnicode_AsUTF8(pVal);
tmp_atom = PL_new_atom(s);
#endif
rc = rc && PL_unify_atom(t, tmp_atom);
} else if (PyByteArray_Check(pVal)) {
atom_t tmp_atom = PL_new_atom(PyByteArray_AsString(pVal));
rc = rc && PL_unify_atom(t, tmp_atom);
#if PY_MAJOR_VERSION < 3
} else if (PyString_Check(pVal)) {
atom_t tmp_atom = PL_new_atom(PyString_AsString(pVal));
rc = rc && PL_unify_atom(t, tmp_atom);
#endif
} else if (PyTuple_Check(pVal)) {
Py_ssize_t i, sz = PyTuple_Size(pVal);
functor_t f;
const char *s;
if (sz == 0) {
rc = rc && PL_unify_atom(t, ATOM_brackets);
} else {
if ((s = (Py_TYPE(pVal)->tp_name))) {
if (!strcmp(s, "H")) {
pVal = PyTuple_GetItem(pVal, 0);
if (pVal == NULL) {
pVal = Py_None;
PyErr_Clear();
}
}
if (s[0] == '$') {
char *ns = malloc(strlen(s) + 5);
strcpy(ns, "__");
strcat(ns, s + 1);
strcat(ns, "__");
f = PL_new_functor(PL_new_atom(ns), sz);
} else {
f = PL_new_functor(PL_new_atom(s), sz);
}
} else {
f = PL_new_functor(ATOM_t, sz);
}
if (PL_unify_functor(t, f)) {
for (i = 0; i < sz; i++) {
if (!PL_get_arg(i + 1, t, to))
rc = false;
PyObject *p = PyTuple_GetItem(pVal, i);
if (p == NULL) {
PyErr_Clear();
p = Py_None;
}
rc = rc && python_to_term(p, to);
}
} else {
rc = false;
}
// fputs(" ||*** ",stderr); Yap_DebugPlWrite(YAP_GetFromSlot(t)); fputs("
// ||***\n",stderr);
}
} else if (PyList_Check(pVal)) {
Py_ssize_t i, sz = PyList_GET_SIZE(pVal);
if (sz == 0) {
rc = rc && PL_unify_nil(t);
} else {
for (i = 0; i < sz; i++) {
PyObject *obj;
if (!PL_unify_list(t, to, t)) {
rc = false;
break;
}
if ((obj = PyList_GetItem(pVal, i)) == NULL) {
obj = Py_None;
}
rc = rc && python_to_term(obj, to);
}
rc = rc && PL_unify_nil(t);
}
// fputs("[***] ", stderr);
// Yap_DebugPlWrite(yt); fputs("[***]\n", stderr);
} else if (PyDict_Check(pVal)) {
Py_ssize_t pos = 0;
term_t to = PL_new_term_ref(), ti = to;
int left = PyDict_Size(pVal);
PyObject *key, *value;
if (left == 0) {
rc = rc && PL_unify_atom(t, ATOM_curly_brackets);
} else {
while (PyDict_Next(pVal, &pos, &key, &value)) {
term_t tkey = PL_new_term_ref(), tval = PL_new_term_ref(), tint,
tnew = PL_new_term_ref();
/* do something interesting with the values... */
if (!python_to_term(key, tkey)) {
continue;
}
if (!python_to_term(value, tval)) {
continue;
}
/* reuse */
tint = tkey;
if (!PL_cons_functor(tint, FUNCTOR_colon2, tkey, tval)) {
rc = false;
continue;
}
if (--left) {
if (!PL_cons_functor(tint, FUNCTOR_comma2, tint, tnew))
PL_reset_term_refs(tkey);
rc = false;
}
if (!PL_unify(ti, tint)) {
rc = false;
}
ti = tnew;
PL_reset_term_refs(tkey);
}
rc = rc && PL_unify(t, to);
}
} else {
rc = rc && repr_term(pVal, t);
}
PL_reset_term_refs(to);
return rc;
}
X_API YAP_Term pythonToYAP(PyObject *pVal) {
term_t t = PL_new_term_ref();
if (pVal == NULL || !python_to_term(pVal, t)) {
PL_reset_term_refs(t);
return 0;
}
YAP_Term tt = YAP_GetFromSlot(t);
PL_reset_term_refs(t);
Py_DECREF(pVal);
return tt;
}
PyObject *py_Local, *py_Global;
/**
* assigns the Python RHS to a Prolog term LHS, ie LHS = RHS
*
* @param root Python environment
* @param t left hand side, in Prolog, may be
* - a Prolog variable, exports the term to Prolog, A <- RHS
* - Python variable A, A <- RHS
* - Python variable $A, A <- RHS
* - Python string "A", A <- RHS
* - Python array range
* @param e the right-hand side
*
* @return -1 on failure.
*
* Note that this is an auxiliary routine to the Prolog
*python_assign.
*/
bool python_assign(term_t t, PyObject *exp, PyObject *context) {
context = find_obj(context, t, false);
// Yap_DebugPlWriteln(yt);
switch (PL_term_type(t)) {
case PL_VARIABLE: {
if (context == NULL) // prevent a.V= N*N[N-1]
return python_to_term(exp, t);
}
case PL_ATOM: {
char *s = NULL;
PL_get_atom_chars(t, &s);
if (!context)
context = py_Main;
return PyObject_SetAttrString(context, s, exp) == 0;
}
case PL_STRING:
case PL_INTEGER:
case PL_FLOAT:
// domain or type erro?
return false;
default: {
term_t tail = PL_new_term_ref(), arg = PL_new_term_ref();
size_t len, i;
if (PL_skip_list(t, tail, &len) &&
PL_get_nil(tail)) { // true list
bool o = true;
if (PySequence_Check(exp) && PySequence_Length(exp) == len)
for (i = 0; i < len; i++) {
PyObject *p;
if (!PL_get_list(t, arg, t)) {
PL_reset_term_refs(tail);
o = false;
p = Py_None;
}
if ((p = PySequence_GetItem(exp, i)) == NULL)
p = Py_None;
if (!python_assign(arg, p, context)) {
PL_reset_term_refs(tail);
o = false;
}
}
PL_reset_term_refs(tail);
return o;
} else {
functor_t fun;
if (!PL_get_functor(t, &fun)) {
PL_reset_term_refs(tail);
return false;
}
if (fun == FUNCTOR_sqbrackets2) {
if (!PL_get_arg(2, t, tail)) {
PL_reset_term_refs(tail);
return false;
}
PyObject *o = term_to_python(tail, true, context);
if (!PL_get_arg(2, t, tail) && !PL_get_nil(tail)) {
PL_reset_term_refs(tail);
return false;
}
if (!PL_get_arg(1, t, t)) {
PL_reset_term_refs(tail);
return false;
}
PL_reset_term_refs(tail);
PyObject *i = term_to_python(t, true, NULL);
if (!i) {
return false;
}
if (PyList_Check(i)) {
i = PyList_GetItem(i, 0);
if (i == NULL)
i = Py_None;
long int j;
if (PyList_Check(o)) {
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(i))
j = PyInt_AsLong(i);
else
#endif
if (PyLong_Check(i))
j = PyLong_AsLong(i);
else
return NULL;
return PyList_SetItem(o, j, exp) == 0;
}
if (PyDict_Check(i)) {
return PyDict_SetItem(o, i, exp) == 0;
}
return PyObject_SetAttr(o, i, exp) == 0;
}
}
}
}
}
return NULL;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,687 +0,0 @@
#include "py4yap.h"
PyObject *py_Main;
void pyErrorHandler__(int line, const char *file, const char *code) {
// this code is called if a Python error is found.
fprintf(stderr, " Python error detected at %s %s:%d\n\n", code, file, line);
PyErr_Print();
}
static foreign_t python_len(term_t tobj, term_t tf) {
Py_ssize_t len;
PyObject *o;
o = term_to_python(tobj, true, NULL);
if (o == NULL) {
pyErrorAndReturn(false, false);
}
len = PyObject_Length(o);
pyErrorAndReturn(PL_unify_int64(tf, len), false);
}
static foreign_t python_dir(term_t tobj, term_t tf) {
PyObject *dir;
PyObject *o;
o = term_to_python(tobj, true, NULL);
if (o == NULL) {
pyErrorAndReturn(false, false);
}
dir = PyObject_Dir(o);
{
foreign_t rc = address_to_term(dir, tf);
;
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_index(term_t tobj, term_t tindex, term_t val) {
PyObject *i;
PyObject *o;
PyObject *f;
o = term_to_python(tobj, true, NULL);
if (o == NULL) {
pyErrorAndReturn(false, false);
}
if (!PySequence_Check(o)) {
pyErrorAndReturn(false, false);
}
i = term_to_python(tindex, true, NULL);
if (i == NULL) {
pyErrorAndReturn(false, false);
}
#if PY_MAJOR_VERSION < 3
f = PyObject_CallMethodObjArgs(o, PyString_FromString("getitem"), i);
#else
f = PyObject_CallMethodObjArgs(o, PyUnicode_FromString("getitem"), i);
#endif
{
foreign_t rc = address_to_term(f, val);
;
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_is(term_t tobj, term_t tf) {
PyObject *o;
term_t lim = python_acquire_GIL();
o = term_to_python(tobj, true, NULL);
if (!o) {
python_release_GIL(lim);
pyErrorAndReturn(false, false);
}
foreign_t rc = python_to_term(o, tf);
if (rc)
PyErr_Clear();
python_release_GIL(lim);
pyErrorAndReturn(rc, false);
}
static foreign_t python_proc(term_t tobj) {
PyObject *o;
term_t lim = python_acquire_GIL();
o = term_to_python(tobj, true, NULL);
python_release_GIL(lim);
bool rc = o != NULL;
pyErrorAndReturn(rc , false);
}
static foreign_t python_slice(term_t parent, term_t indx, term_t tobj) {
PyObject *pF, *pI;
PyObject *p;
// get Scope ...
pI = term_to_python(indx, true, NULL);
// got Scope.Exp
// get Scope ...
p = term_to_python(parent, true, NULL);
// Exp
if (!pI || !p) {
{ pyErrorAndReturn(false, false); }
} else if ((pF = PySequence_GetSlice(p, 0, 0)) == NULL) {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
Py_DecRef(pI);
Py_DecRef(p);
Py_INCREF(pF);
{
foreign_t rc;
rc = address_to_term(pF, tobj);
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
term_t tf) {
PyObject *pF;
PyObject *pArgs, *pKeywords;
PyObject *pValue;
int i, arity;
atom_t aname;
foreign_t out;
term_t targ = PL_new_term_ref();
pF = term_to_python(tin, true, NULL);
PyErr_Clear();
if (pF == NULL) {
{ pyErrorAndReturn(false, false); }
}
if (PL_is_atom(targs)) {
pArgs = NULL;
} else {
if (!PL_get_name_arity(targs, &aname, &arity)) {
{ pyErrorAndReturn(false, false); }
}
if (arity == 1 && PL_get_arg(1, targs, targ) && PL_is_variable(targ)) {
/* ignore (_) */
pArgs = NULL;
} else {
pArgs = PyTuple_New(arity);
DebugPrintf("Tuple %p\n", pArgs);
if (!pArgs) {
pyErrorAndReturn(false, false);
}
for (i = 0; i < arity; i++) {
PyObject *pArg;
if (!PL_get_arg(i + 1, targs, targ)) {
pyErrorAndReturn(false, false);
}
pArg = term_to_python(targ, true, NULL);
if (pArg == NULL) {
pyErrorAndReturn(false, false);
}
/* pArg reference stolen here: */
PyTuple_SetItem(pArgs, i, pArg);
}
}
}
if (PL_is_atom(keywds)) {
pKeywords = NULL;
} else {
pKeywords = term_to_python(keywds, true, NULL);
}
if (PyCallable_Check(pF)) {
pValue = PyEval_CallObjectWithKeywords(pF, pArgs, pKeywords);
// PyObject_Print(pF,stderr,0);fprintf(stderr, "\n");
// PyObject_Print(pArgs,stderr,0);fprintf(stderr, " ");
// PyObject_Print(pKeywords,stderr,0);fprintf(stderr, "\n");
if (!pValue)
PyErr_Print();
else
Py_IncRef(pValue);
} else if (pArgs == NULL) {
pValue = pF;
if (pF) {
Py_IncRef(pValue);
}
} else {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
if (pArgs)
Py_DECREF(pArgs);
Py_DECREF(pF);
if (pValue == NULL) {
pyErrorAndReturn(false, false);
}
out = address_to_term(pValue, tf);
pyErrorAndReturn(out, false);
}
static foreign_t assign_python(term_t exp, term_t name) {
term_t stackp = python_acquire_GIL();
PyObject *e = term_to_python(exp, true, NULL);
if (e == NULL) {
python_release_GIL(stackp);
pyErrorAndReturn(false, false);
}
bool b = python_assign(name, e, NULL);
python_release_GIL(stackp);
pyErrorAndReturn(b, false);
}
static foreign_t python_builtin_eval(term_t caller, term_t dict, term_t out) {
PyErr_Clear();
PyObject *pI, *pArgs, *pOut;
PyObject *env;
atom_t name;
char *s;
int i, arity;
term_t targ = PL_new_term_ref();
if ((env = py_Builtin) == NULL) {
// no point in even trying
{ pyErrorAndReturn(false, false); }
}
if (PL_get_name_arity(caller, &name, &arity)) {
if (!(s = PL_atom_chars(name))) {
pyErrorAndReturn(false, false);
}
if ((pI = PyObject_GetAttrString(env, s)) == NULL) {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
Py_INCREF(pI);
} else {
// Prolog should make sure this never happens.
{ pyErrorAndReturn(false, false); }
}
pArgs = PyTuple_New(arity);
DebugPrintf("Tuple %p\n", pArgs);
for (i = 0; i < arity; i++) {
PyObject *pArg;
if (!PL_get_arg(i + 1, caller, targ)) {
pyErrorAndReturn(false, false);
}
/* ignore (_) */
if (i == 0 && PL_is_variable(targ)) {
pArg = Py_None;
} else {
pArg = term_to_python(targ, true, NULL);
if (pArg == NULL) {
pyErrorAndReturn(false, false);
}
}
/* pArg reference stolen here: */
if (PyTuple_SetItem(pArgs, i, pArg)) {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
}
pOut = PyObject_CallObject(pI, pArgs);
Py_DECREF(pArgs);
Py_DECREF(pI);
if (pOut == NULL) {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
{
foreign_t rc = address_to_term(pOut, out);
;
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_access(term_t obj, term_t f, term_t out) {
PyErr_Clear();
PyObject *o = term_to_python(obj, true, NULL), *pValue, *pArgs, *pF;
atom_t name;
char *s = NULL;
int i, arity;
term_t targ = PL_new_term_ref();
if (o == NULL) {
pyErrorAndReturn(false, false);
}
if (PL_is_atom(f)) {
if (!PL_get_atom_chars(f, &s)) {
pyErrorAndReturn(false, false);
}
if ((pValue = PyObject_GetAttrString(o, s)) == NULL) {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
Py_INCREF(pValue);
{ pyErrorAndReturn(python_to_term(pValue, out), false); }
}
if (!PL_get_name_arity(f, &name, &arity)) {
{ pyErrorAndReturn(false, false); }
}
s = PL_atom_chars(name);
if (!s) {
pyErrorAndReturn(false, false);
}
if ((pF = PyObject_GetAttrString(o, s)) == NULL) {
DebugPrintf("Function %p\n", pArgs);
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
pArgs = PyTuple_New(arity);
DebugPrintf("Tuple %p\n", pArgs);
for (i = 0; i < arity; i++) {
PyObject *pArg;
if (!PL_get_arg(i + 1, f, targ)) {
pyErrorAndReturn(false, false);
}
/* ignore (_) */
if (i == 0 && PL_is_variable(targ)) {
pArgs = Py_None;
}
pArg = term_to_python(targ, true, NULL);
if (pArg == NULL) {
pyErrorAndReturn(false, false);
}
/* pArg reference stolen here: */
PyTuple_SetItem(pArgs, i, pArg);
}
pValue = PyObject_CallObject(pF, pArgs);
Py_DECREF(pArgs);
Py_DECREF(pF);
if (pValue == NULL) {
{ pyErrorAndReturn(false, false); }
}
{ pyErrorAndReturn(python_to_term(pValue, out), false); }
}
static foreign_t python_field(term_t parent, term_t att, term_t tobj) {
PyObject *pF;
atom_t name;
char *s;
int arity;
if (!PL_get_name_arity(att, &name, &arity)) {
{ pyErrorAndReturn(false, false); }
} else {
PyObject *p;
// got Scope.Exp
// get Scope ...
p = term_to_python(parent, true, NULL);
// Exp
if (!PL_get_name_arity(att, &name, &arity)) {
{ pyErrorAndReturn(false, false); }
}
s = PL_atom_chars(name);
if (arity == 1 && !strcmp(s, "()")) {
if (!PL_get_arg(1, att, att)) {
pyErrorAndReturn(false, false);
}
if (!PL_get_name_arity(att, &name, &arity)) {
{ pyErrorAndReturn(false, false); }
}
s = PL_atom_chars(name);
}
if (!s || !p) {
{ pyErrorAndReturn(false, false); }
} else if ((pF = PyObject_GetAttrString(p, s)) == NULL) {
PyErr_Clear();
{ pyErrorAndReturn(false, false); }
}
}
{
foreign_t rc;
rc = address_to_term(pF, tobj);
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_main_module(term_t mod) {
{
foreign_t rc;
PyErr_Clear();
rc = address_to_term(py_Main, mod);
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_function(term_t tobj) {
PyErr_Clear();
PyObject *obj = term_to_python(tobj, true, NULL);
foreign_t rc = PyFunction_Check(obj);
pyErrorAndReturn(rc, false);
}
foreign_t python_builtin(term_t out) {
{
foreign_t rc;
PyErr_Clear();
rc = address_to_term(py_Builtin, out);
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_run_file(term_t file) {
char *s;
size_t len;
char si[256];
s = si;
PyErr_Clear();
if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
PyObject *PyFileObject = PyFile_FromString(si, "r");
PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1);
#else
FILE *f = fopen(s, "r");
if (f == NULL) {
pyErrorAndReturn(false, false);
}
PyRun_SimpleFileEx(f, s, 1);
#endif
{
{ pyErrorAndReturn(true, false); }
}
}
{ pyErrorAndReturn(false, false); }
}
extern PyThreadState *YAP_save;
static foreign_t python_run_command(term_t cmd) {
char *s;
bool rc = false;
size_t len;
char si[256];
PyErr_Clear();
s = si;
if (PL_get_nchars(cmd, &len, &s, CVT_ALL | CVT_EXCEPTION)) {
PyRun_SimpleString(s);
rc = true;
}
pyErrorAndReturn(rc, false);
}
static foreign_t python_run_script(term_t cmd, term_t fun) {
char si[256], sf[256];
size_t len = 255, len1 = 255;
PyObject *pName, *pModule, *pFunc;
PyObject *pArgs = NULL, *pValue;
char *s;
PyErr_Clear();
s = si;
if (PL_get_nchars(cmd, &len, &s, CVT_ALL | CVT_EXCEPTION) &&
(s = sf) != NULL &&
PL_get_nchars(fun, &len1, &s, CVT_ALL | CVT_EXCEPTION)) {
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString("rbm");
#else
// asssumes UTF-8
pName = PyUnicode_FromString("rbm");
#endif
/* Error checking of pName left out */
pModule = PyImport_Import(pName);
PyErr_Clear();
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, sf);
/* pFunc is a new reference */
if (pFunc && PyCallable_Check(pFunc)) {
pValue = PyObject_CallObject(pFunc, pArgs);
if (pValue != NULL) {
Py_DECREF(pValue);
} else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr, "Call failed\n");
{ pyErrorAndReturn(false, false); }
}
} else {
pyErrorHandler();
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"%s\"\n", sf);
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
} else {
PyErr_Print();
{ pyErrorAndReturn(false, false); }
}
{ pyErrorAndReturn(true, false); }
}
{ pyErrorAndReturn(false, false); }
}
static foreign_t python_export(term_t t, term_t pl) {
foreign_t rc = false;
PyErr_Clear();
if (PL_is_functor(t, FUNCTOR_pointer1)) {
void *ptr;
term_t targ = PL_new_term_ref();
if (!PL_get_arg(1, t, targ)) {
pyErrorAndReturn(false, false);
}
if (!PL_get_pointer(targ, &ptr)) {
pyErrorAndReturn(false, false);
}
Py_INCREF((PyObject *)ptr);
/* pyErrorAndReturn( __main__, false) */
rc = python_to_term((PyObject *)ptr, pl);
}
pyErrorAndReturn(rc, false);
}
/**
* @pred python_import(MName, Mod)
* Import a python module to the YAP environment.
*
* @param mname module name, either an atom or a sequence of atoms,
* eg os.sys
* @param mod the pointer to the Python object
* @return success?
*/
static int python_import(term_t mname, term_t mod) {
PyObject *pName;
term_t t0 = python_acquire_GIL();
term_t arg = PL_new_term_ref();
char s0[MAXPATHLEN], *s = s0;
while (true) {
size_t len;
len = (MAXPATHLEN - 1) - (s - s0);
if (PL_is_pair(mname)) {
char *sa = NULL;
if (!PL_get_arg(1, mname, arg) || !PL_get_atom_chars(arg, &sa) ||
!PL_get_arg(2, mname, mname)) {
python_release_GIL(t0);
pyErrorAndReturn(false, false);
}
PL_get_atom_chars(arg, &sa);
strcpy(s, sa);
s += strlen(s);
*s++ = '.';
s[0] = '\0';
} else if (!PL_get_nchars(mname, &len, &s,
CVT_ATOM | CVT_STRING| CVT_EXCEPTION | REP_UTF8)) {
python_release_GIL(t0);
pyErrorAndReturn(false, false);
} else {
break;
}
}
#if PY_MAJOR_VERSION < 3
pName = PyString_FromString(s0);
#else
pName = PyUnicode_FromString(s0);
#endif
python_release_GIL(t0);
if (pName == NULL) {
pyErrorAndReturn(false, false);
}
PyObject *pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule == NULL) {
#if EXTRA_MESSSAGES
if (PyErr_Occurred())
PyErr_Print();
PyErr_Clear();
#endif
{ pyErrorAndReturn(false, false); }
}
{
foreign_t rc = address_to_term(pModule, mod);
pyErrorAndReturn(rc, false);
}
}
static foreign_t python_to_rhs(term_t inp, term_t t) {
PyObject *pVal;
PyErr_Clear();
pVal = term_to_python(inp, true, NULL);
if (pVal == NULL)
pyErrorAndReturn(false, false);
pyErrorAndReturn(address_to_term(pVal, t), false);
}
// static PyThreadState *_saveP = NULL;
static bool _threaded = false;
/*
static YAP_Int
p_python_ensure(term_t ptr)
{
PyGILState_STATE _tState = PyGILState_Ensure();
pyErrorAndReturn( PL_unify_int64(ptr, _tState), false);
}
static YAP_Int
p_python_release(term_t ptr)
{
PyGILState_STATE _tState;
PL_get_int64( ptr, &_tState);
PyGILState_Release( _tState );
pyErrorAndReturn( true, false);
}
*/
int _locked = 0;
PyThreadState *tstate;
static YAP_Int p_python_threaded(void) {
PyErr_Clear();
// PyEval_ReleaseThread(tstate);
// _threaded = true;
// _locked = 0;
pyErrorAndReturn(true, false);
}
static PyGILState_STATE gstate;
term_t python_acquire_GIL(void) {
term_t curSlot = PL_new_term_ref();
if (!_threaded)
pyErrorAndReturn(curSlot, false);
// extern int Yap_do_low_level_trace;
// Yap_do_low_level_trace = 1;
// f[rintf( stderr, "++%d\n", ++_locked);
// if (_locked > 0) { _locked++ ; }
// else
gstate = PyGILState_Ensure();
pyErrorAndReturn(curSlot, false);
}
bool python_release_GIL(term_t curBlock) {
PyErr_Clear();
PL_reset_term_refs(curBlock);
if (_threaded) {
PyGILState_Release(gstate);
}
pyErrorAndReturn(true, false);
}
//: prolog: release python
install_t install_pypreds(void) {
PL_register_foreign("python_builtin_eval", 3, python_builtin_eval, 0);
PL_register_foreign("python_builtin", 1, python_builtin, 0);
PL_register_foreign("python_import", 2, python_import, 0);
PL_register_foreign("python_to_rhs", 2, python_to_rhs, 0);
PL_register_foreign("python_len", 2, python_len, 0);
PL_register_foreign("python_is", 2, python_is, 0);
PL_register_foreign("python_dir", 2, python_dir, 0);
PL_register_foreign("python_apply", 4, python_apply, 0);
PL_register_foreign("python_index", 3, python_index, 0);
PL_register_foreign("python_field", 3, python_field, 0);
PL_register_foreign("python_assign", 2, assign_python, 0);
PL_register_foreign("python_export", 2, python_export, 0);
PL_register_foreign("python_function", 1, python_function, 0);
PL_register_foreign("python_slice", 4, python_slice, 0);
PL_register_foreign("python_run_file", 1, python_run_file, 0);
PL_register_foreign("python_proc", 1, python_proc, 0);
PL_register_foreign("python_run_command", 1, python_run_command, 0);
PL_register_foreign("python_run_script", 2, python_run_script, 0);
PL_register_foreign("python_main_module", 1, python_main_module, 0);
PL_register_foreign("python_import", 2, python_import, 0);
PL_register_foreign("python_access", 3, python_access, 0);
PL_register_foreign("python_threaded", 0, p_python_threaded, 0);
}

View File

@ -1,222 +0,0 @@
#include "py4yap.h"
#include <VFS.h>
atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
ATOM_comma, ATOM_builtin, ATOM_A, ATOM_V, ATOM_self, ATOM_nil, ATOM_brackets, ATOM_curly_brackets;
functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
FUNCTOR_float1, FUNCTOR_int1, FUNCTOR_iter1, FUNCTOR_iter2, FUNCTOR_long1,
FUNCTOR_len1, FUNCTOR_curly1, FUNCTOR_ord1, FUNCTOR_range1, FUNCTOR_range2,
FUNCTOR_range3, FUNCTOR_sum1, FUNCTOR_pointer1, FUNCTOR_complex2,
FUNCTOR_plus2, FUNCTOR_sub2, FUNCTOR_mul2, FUNCTOR_div2, FUNCTOR_hat2,
FUNCTOR_colon2, FUNCTOR_comma2, FUNCTOR_equal2, FUNCTOR_sqbrackets2,
FUNCTOR_dot2, FUNCTOR_brackets1;
X_API PyObject *py_Builtin;
X_API PyObject *py_Yapex;
X_API PyObject *py_Sys;
PyObject *py_Context;
PyObject *py_ModDict;
VFS_t pystream;
static void *
py_open( const char *name, const char *io_mode) {
#if HAVE_STRCASESTR
if (strcasestr(name,"//python/")== name)
name += strlen("//python/");
#else
if (strstr(name,"//python/")== name)
name += strlen("//python/");
#endif
// we assume object is already open, so there is no need to open it.
PyObject *stream = string_to_python( name, true, NULL);
if (stream == Py_None)
return NULL;
return stream;
}
static bool
py_close(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fclose = PyObject_GetAttrString(s, "close");
PyObject* rc= PyObject_CallObject(fclose, NULL);
bool v = (rc == Py_True);
return v;
}
static PyObject * pyw; // buffer
static int pyw_kind;
PyObject * pyw_data;
static int
py_put(int sno, int ch) {
PyObject *s = YAP_foreign_stream(sno);
PyUnicode_WRITE( pyw_kind, pyw_data, 0, ch );
PyObject* fput = PyObject_GetAttrString(s, "write");
PyObject_CallFunctionObjArgs(fput, pyw, NULL);
return ch;
}
static int
py_get(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fget = PyObject_GetAttrString(s, "read");
PyObject *pyr = PyObject_CallFunctionObjArgs(fget, PyLong_FromLong(1), NULL);
return PyUnicode_READ_CHAR( pyr, 0) ;
}
static int64_t py_seek(int sno, int64_t where, int how) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* fseek = PyObject_GetAttrString(s, "seek");
PyObject *pyr = PyObject_CallFunctionObjArgs(fseek, PyLong_FromLong(where), PyLong_FromLong(how), NULL);
return PyLong_AsLong(pyr);
}
static void
py_flush(int sno) {
PyObject *s = YAP_foreign_stream(sno);
PyObject* flush = PyObject_GetAttrString(s, "flush");
PyObject_CallFunction( flush, NULL);
}
static bool
init_python_stream(void)
{
pyw = PyUnicode_FromString("x");
pyw_kind = PyUnicode_KIND(pyw);
pyw_data = PyUnicode_DATA(pyw);
pystream.name = "python stream";
pystream.vflags = VFS_CAN_WRITE|VFS_CAN_EXEC| VFS_CAN_SEEK|VFS_HAS_PREFIX;
pystream.prefix = "//python/";
pystream.suffix = NULL;
pystream.open = py_open;
pystream.close = py_close;
pystream.get_char = py_get;
pystream.put_char = py_put;
pystream.flush = py_flush;
pystream.seek = py_seek;
pystream.next = GLOBAL_VFS;
GLOBAL_VFS = &pystream;
// NULL;
return true;
}
X_API PyObject *py_F2P;
extern X_API bool python_in_python;
static void add_modules(void) {
py_Main = PyImport_AddModule("__main__");
Py_INCREF(py_Main);
py_Sys = PyImport_AddModule("sys");
Py_INCREF(py_Sys);
py_Builtin = PyImport_AddModule("__builtin__");
Py_INCREF(py_Builtin);
py_ModDict = PyObject_GetAttrString(py_Sys, "modules");
// py_Yapex = PyImport_ImportModule("yap4py.yapi");
// PyObject *py_Yap =
py_Yapex = PyImport_AddModule("yap4py.yapi");
if (py_Yapex)
Py_INCREF(py_Yapex);
//py_F2P = PyObject_GetAttrString(py_Yap, "globals");
py_F2P = NULL;
init_python_stream();
}
static void install_py_constants(void) {
FUNCTOR_dot2 = PL_new_functor(PL_new_atom("."), 2);
// FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2);
// FUNCTOR_boolop1 = PL_new_functor(PL_new_atom("@"), 1);
ATOM_A = PL_new_atom("A");
ATOM_V = PL_new_atom("V");
ATOM_builtin = PL_new_atom("__builtin__");
ATOM_comma = PL_new_atom(",");
ATOM_colon = PL_new_atom(":");
ATOM_true = PL_new_atom("true");
ATOM_false = PL_new_atom("false");
ATOM_dot = PL_new_atom(".");
ATOM_self = PL_new_atom("self");
ATOM_nil = PL_new_atom("[]");
ATOM_brackets = PL_new_atom("()");
ATOM_curly_brackets = PL_new_atom("{}");
FUNCTOR_abs1 = PL_new_functor(PL_new_atom("abs"), 1);
FUNCTOR_all1 = PL_new_functor(PL_new_atom("all"), 1);
FUNCTOR_any1 = PL_new_functor(PL_new_atom("any"), 1);
FUNCTOR_bin1 = PL_new_functor(PL_new_atom("bin"), 1);
FUNCTOR_ord1 = PL_new_functor(PL_new_atom("ord"), 1);
FUNCTOR_int1 = PL_new_functor(PL_new_atom("int"), 1);
FUNCTOR_long1 = PL_new_functor(PL_new_atom("long"), 1);
FUNCTOR_float1 = PL_new_functor(PL_new_atom("float"), 1);
FUNCTOR_curly1 = PL_new_functor(PL_new_atom("{}"), 1);
FUNCTOR_brackets1 = PL_new_functor(PL_new_atom("()"), 1);
FUNCTOR_dollar1 = PL_new_functor(PL_new_atom("$"), 1);
FUNCTOR_pointer1 = PL_new_functor(PL_new_atom("__obj__"), 1);
FUNCTOR_dir1 = PL_new_functor(PL_new_atom("dir"), 1);
FUNCTOR_iter1 = PL_new_functor(PL_new_atom("iter"), 1);
FUNCTOR_iter2 = PL_new_functor(PL_new_atom("iter"), 2);
FUNCTOR_len1 = PL_new_functor(PL_new_atom("len"), 1);
FUNCTOR_range1 = PL_new_functor(PL_new_atom("range"), 1);
FUNCTOR_range2 = PL_new_functor(PL_new_atom("range"), 2);
FUNCTOR_range3 = PL_new_functor(PL_new_atom("range"), 3);
FUNCTOR_sum1 = PL_new_functor(PL_new_atom("sum"), 1);
FUNCTOR_complex2 = PL_new_functor(PL_new_atom("i"), 2);
FUNCTOR_plus2 = PL_new_functor(PL_new_atom("+"), 2);
FUNCTOR_sub2 = PL_new_functor(PL_new_atom("-"), 2);
FUNCTOR_mul2 = PL_new_functor(PL_new_atom("*"), 2);
FUNCTOR_div2 = PL_new_functor(PL_new_atom("/"), 2);
FUNCTOR_hat2 = PL_new_functor(PL_new_atom("^"), 2);
FUNCTOR_colon2 = PL_new_functor(PL_new_atom(":"), 2);
FUNCTOR_comma2 = PL_new_functor(PL_new_atom(","), 2);
FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2);
FUNCTOR_sqbrackets2 = PL_new_functor(PL_new_atom("[]"), 2);
}
foreign_t end_python(void) {
if (!python_in_python)
Py_Finalize();
return true;
}
static bool libpython_initialized = 0;
X_API bool do_init_python(void) {
// char **argv;
if (libpython_initialized)
return true;
libpython_initialized = true;
// PyGILState_STATE gstate = PyGILState_Ensure();
term_t t = PL_new_term_ref();
if (!python_in_python)
Py_Initialize();
install_py_constants();
PL_reset_term_refs(t);
install_pl2pl();
// PyGILState_Release(gstate);
add_modules();
return true;
}
#ifndef _WIN32
O_API bool init_python_dll(void);
O_API bool init_python_dll(void) {
do_init_python();
install_pypreds();
return 1;
}
#endif

View File

@ -1,84 +1,68 @@
# This is a CMake file for SWIG and Android
# This is a CMake file for SWIG and Android
set (SWIG_CXX_DIR ${YAP_APP_DIR}/src/generated/jni)
FILE( MAKE_DIRECTORY ${YAP_APP_DIR}/src/generated/java/pt/up/yap/lib )
FILE( MAKE_DIRECTORY ${YAP_APP_DIR}/src/generated/assets)
FILE( MAKE_DIRECTORY ${YAP_APP_DIR}/src/generated/jni)
set ( pllib ${YAP_APP_DIR}/src/generated/assets/Yap )
set(JAVA_SWIG_OUTDIR ${CMAKE_SOURCE_DIR}/../yaplib/src/generated/java/pt/up/yap/lib)
set(SWIG_CXX_DIR ${CMAKE_BINARY_DIR}/src/generated/jni)
FILE(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/src/generated/java/pt/up/yap/lib)
FILE(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/src/generated/assets/Yap/pl)
FILE(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/src/generated/assets/so)
FILE(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/src/generated/jni)
set(YAP_ASSETS ${CMAKE_SOURCE_DIR}/../yaplib/src/generated/assets/Yap)
set ( SWIG_SOURCES ${CMAKE_SOURCE_DIR}/packages/swig/yap.i )
SET_SOURCE_FILES_PROPERTIES(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON)
set(SWIG_SOURCES ${CMAKE_SOURCE_DIR}/packages/swig/yap.i)
SET_SOURCE_FILES_PROPERTIES(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON)
include_directories (
${CMAKE_SOURCE_DIR}/CXX
)
set( GMP_ROOT ${CMAKE_SOURCE_DIR}/../gmp/${ANDROID_ABI} )
set (GMP_INCLUDE_DIRS ${GMP_ROOT})
set (GMP_LIBRARIES ${GMP_ROOT}/libgmp.so)
#
# add_custom_target (pllib
# COMMAND ${CMAKE_COMMAND} -E make_directory ${YAP_INSTALL_DATADIR}
# COMMAND ${CMAKE_COMMAND} -E copy ${pl_library} ${YAP_INSTALL_DATADIR}
# COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/android.yap ${YAP_INSTALL_DATADIR}
# DEPENDS ${pl_library}
#)
#
# add_custom_target (pllibpl
# COMMAND ${CMAKE_COMMAND} -E make_directory ${YAP_INSTALL_DATADIR}/pl
# COMMAND ${CMAKE_COMMAND} -E copy ${pl_boot_library} ${YAP_INSTALL_DATADIR}/pl
#DEPENDS pllib ${pl_boot_library}
# )
# add_custom_target (pllibos ALL
# COMMAND ${CMAKE_COMMAND} -E make_directory ${YAP_INSTALL_DATADIR}/os
# COMMAND ${CMAKE_COMMAND} -E copy ${pl_os_library} ${YAP_INSTALL_DATADIR}/os
#DEPENDS pllibpl ${pl_os_library}
# )
#
# add_custom_command (OUTPUT ${CMAKE_SWIG_OUTPUT}/swig_streamer.cpp
# COMMAND ${SWIG_EXECUTABLE} -c++ -java -package ${SWIG_MODULE_NAME} -O -outdir ${CMAKE_SWIG_OUTDIR} -addextern -I${CMAKE_CURRENT_SOURCE_DIR} -o ${CMAKE_SWIG_OUTPUT}/swig_streamer.cpp -oh ${CMAKE_SWIG_OUTPUT}/swig_streamer.hh streamer.i
# DEPENDS streamer.i
# )
#
# add_custom_command (OUTPUT ${CMAKE_SWIG_OUTPUT}/yap_swig.cpp
# COMMAND ${SWIG_EXECUTABLE} -c++ -java -package ${SWIG_MODULE_NAME} -O -outdir ${CMAKE_SWIG_OUTDIR} -addextern -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/include -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_BINARY_DIR} -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_SWIG_OUTPUT}/yap_swig.cpp -oh ${CMAKE_SWIG_OUTPUT}/yap_swig.hh ${SWIG_SOURCES}
# DEPENDS pllibos ${SWIG_SOURCES} YAP++)
#
include_directories(
${CMAKE_SOURCE_DIR}/CXX
)
set(GMP_ROOT ${CMAKE_SOURCE_DIR}/../gmp/${ANDROID_ABI})
set(GMP_INCLUDE_DIRS ${GMP_ROOT})
set(GMP_LIBRARIES ${GMP_ROOT}/libgmp.so)
add_library(YAPJava OBJECT
${SWIG_CXX_DIR}/streamer_swig.cxx
${SWIG_CXX_DIR}/yapi_swig.cxx
streamer.cpp
)
file(INSTALL ${pl_library} DESTINATION ${YAP_ASSETS})
file(INSTALL ${CMAKE_CURRENT_SOURCE_DIR}/android.yap DESTINATION ${YAP_ASSETS})
set_target_properties(YAPJava PROPERTIES LINKER_LANGUAGE CXX)
file(INSTALL ${pl_boot_library} DESTINATION ${YAP_ASSETS}/pl)
file(INSTALL ${pl_os_library} DESTINATION ${YAP_ASSETS}/os)
execute_process(COMMAND swig -c++ -java -package pt.up.yap.lib -O -outdir ${JAVA_SWIG_OUTDIR} -addextern -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/include -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_BINARY_DIR} -I${GMP_INCLUDE_DIRS} -DX_API -o ${SWIG_CXX_DIR}/yapi_swig.cxx ${SWIG_SOURCES}
)
execute_process(COMMAND ${SWIG_EXECUTABLE} -c++ -java -package pt.up.yap.lib -O -outdir ${JAVA_SWIG_OUTDIR} -addextern -I${CMAKE_CURRENT_SOURCE_DIR} -o ${SWIG_CXX_DIR}/streamer_swig.cxx streamer.i
)
add_library(YAPJava OBJECT
${CMAKE_BINARY_DIR}/src/generated/jni/streamer_swig.cxx
${CMAKE_BINARY_DIR}/src/generated/jni/yapi_swig.cxx
streamer.cpp
)
set_target_properties(YAPJava PROPERTIES LINKER_LANGUAGE CXX)
# GMP_FOUND - true if GMP/MPIR was found
# GMP_INCLUDE_DIRS - include search path
# GMP_LIBRARIES - libraries to link with
#config.h needs this (TODO: change in code latter)
include_directories( .;${GMP_INCLUDE_DIRS};${CMAKE_SOURCE_DIR}/include;${CMAKE_SOURCE_DIR}/H;${CMAKE_SOURCE_DIR}/H/generated;${CMAKE_SOURCE_DIR}/os;${CMAKE_SOURCE_DIR}/OPTYap;${CMAKE_BINARY_DIR};${CMAKE_CURRENT_SOURCE_DIR} )
include_directories(.;${GMP_INCLUDE_DIRS};${CMAKE_SOURCE_DIR}/include;${CMAKE_SOURCE_DIR}/H;${CMAKE_SOURCE_DIR}/H/generated;${CMAKE_SOURCE_DIR}/os;${CMAKE_SOURCE_DIR}/OPTYap;${CMAKE_BINARY_DIR};${CMAKE_CURRENT_SOURCE_DIR})
if (FALSE)
set (SWIG_ADD_MODULE YAPJava SHARED CPLUSPLUS ${SWIG_SOURCES} )
# Define swig module with given name and specified language
set(SWIG_ADD_MODULE YAPJava SHARED CPLUSPLUS ${SWIG_SOURCES})
# Define swig module with given name and specified language
set (SWIG_LINK_LIBRARIES YAPJava YAP++ libYAP )
#- Link libraries to swig module
set(SWIG_LINK_LIBRARIES YAPJava YAP++ libYAP)
#- Link libraries to swig module
add_library (YAPJavaTop SHARED
main.cpp main.h
)
add_library(YAPJavaTop SHARED
main.cpp main.h
)
target_link_libraries( YAPJavaTop ${SWIG_MODULE_${YAPJava}_REAL_NAME} YAP++ libYap android)
target_link_libraries(YAPJavaTop ${SWIG_MODULE_${YAPJava}_REAL_NAME} YAP++ libYap android)
endif()
endif ()

View File

@ -968,7 +968,7 @@ source_file(Mod:Pred, FileName) :-
+ directory (prolog_load_context/2 option)
Full name for the directory where YAP is currently consulting the
Full name for the directory where YAP is currently consulting the
file.
+ file (prolog_load_context/2 option)