Merge /home/vsc/yap

This commit is contained in:
Vítor Santos Costa 2019-04-03 17:09:29 +01:00
commit 299a1edf8b
24 changed files with 277 additions and 148 deletions

View File

@ -787,6 +787,10 @@ static void kill_children(LogUpdIndex *c, PredEntry *ap) {
ncl = c->ChildIndex;
/* kill children */
while (ncl) {
if (ncl->ClRefCount>0) {
c->ClRefCount--;
return;
}
kill_first_log_iblock(ncl, c, ap);
ncl = c->ChildIndex;
}
@ -862,7 +866,7 @@ static void kill_first_log_iblock(LogUpdIndex *c, LogUpdIndex *parent,
if (DBErasedIList)
DBErasedIList->PrevSiblingIndex = c;
DBErasedIList = c;
if (!((c->ClFlags & InUseMask) || c->ClRefCount)) {
if (!(c->ClFlags & InUseMask || c->ClRefCount)) {
kill_off_lu_block(c, parent, ap);
} else {
if (c->ClFlags & ErasedMask)

View File

@ -1840,6 +1840,15 @@ static Term MkZeroApplTerm(Functor f, UInt sz USES_REGS) {
return tf;
}
/**
* @pred nb_heap(+_Size_,-_Heap_) is deterministic.
*
* Initialize a new binomial heap of size _Size_.
* The Heap resides in the Prolog stack, but the state of the
* Heap is not backtrable.
*
*/
static Int p_nb_heap(USES_REGS1) {
Term heap_arena, heap, *ar, *nar;
UInt hsize;
@ -1881,6 +1890,21 @@ static Int p_nb_heap(USES_REGS1) {
return TRUE;
}
/**
* @pred nb_heap_reset(+_Heap_) is deterministic.
*
* Set the number if entries in the heap to 0. Allows reusing
* the same space for several heaps.
*/
static Int p_nb_heap_reset(USES_REGS1) {
CELL *qd = GetHeap(ARG1, "reset_heap");
if (!qd)
return FALSE;
qd[HEAP_SIZE] = MkIntTerm(0);
return true;
}
static Int p_nb_heap_close(USES_REGS1) {
Term t = Deref(ARG1);
if (!IsVarTerm(t)) {
@ -2796,6 +2820,7 @@ void Yap_InitGlobals(void) {
Yap_InitCPred("nb_heap_peek", 3, p_nb_heap_peek, SafePredFlag);
Yap_InitCPred("nb_heap_empty", 1, p_nb_heap_empty, SafePredFlag);
Yap_InitCPred("nb_heap_size", 2, p_nb_heap_size, SafePredFlag);
Yap_InitCPred("nb_heap_reset", 1, p_nb_heap_reset, SafePredFlag);
Yap_InitCPred("nb_beam", 2, p_nb_beam, 0L);
Yap_InitCPred("nb_beam_close", 1, p_nb_beam_close, SafePredFlag);
Yap_InitCPred("nb_beam_add", 3, p_nb_beam_add_to_beam, 0L);

View File

@ -616,7 +616,6 @@ add_subDIRECTORY(utf8proc )
set(CXX_SWIG_OUTDIR ${CMAKE_BINARY_DIR}/packages/swig/android)
add_subdirectory(packages/swig/android)
add_definitions(-DMYDDAS=1 -DEMBEDDED_MYDDAS=1 -DMYDDAS_SQLITE3=1 -DEMBEDDED_SQLITE3=1)
link_directories(${CMAKE_SOURCE_DIR}/../sqlite-android/jni/${ANDROID_ABI})
else()
add_definitions(-DMYDDAS=1 -DEMBEDDED_MYDDAS=1 -DMYDDAS_SQLITE3=1 )
@ -656,7 +655,8 @@ if (WIN32 OR ANDROID)
if (ANDROID)
List(APPEND YLIBS $<TARGET_OBJECTS:YAPsqlite3>)
List(APPEND YLIBS $<TARGET_OBJECTS:DROID>)
set(ANDROID_LIBRARIES sqliteX android log)
set(ANDROID_LIBRARIES ${CMAKE_SOURCE_DIR}/../sqlite-android/jni/${ANDROID_ABI}/libsqliteX.so android log)
link_directories(${CMAKE_SOURCE_DIR}/../sqlite-android/jni/${ANDROID_ABI})
endif ()
endif ()
@ -731,7 +731,13 @@ MY_set_target_properties(libYap
# file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/packages/python/swig/yap4py)
if (WITH_PYTHON AND PYTHONLIBS_FOUND AND SWIG_FOUND)
set( ENV{PYTHONPATH} ${CMAKE_BINARY_DIR}/packages/python/swig:${CMAKE_BINARY_DIR}/packages/python/yap_kernel:. )
if (CONDA)
set(bdist bdist_conda)
else()
set(bdist bdist_wheel)
endif()
set( ENV{PYTHONPATH} ${CMAKE_BINARY_DIR}/packages/python/swig:${CMAKE_BINARY_DIR}/packages/python/yap_kernel:. )
add_subdirectory(packages/python/swig)
include(FindPythonModule)
@ -961,6 +967,7 @@ if (WIN32)
endif (WIN32)
if (NOT ANDROID)
add_executable(yap-bin ${CONSOLE_SOURCES})
set_target_properties(yap-bin PROPERTIES OUTPUT_NAME yap)
@ -974,6 +981,7 @@ install(TARGETS libYap yap-bin
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
endif()
if (WITH_MPI)

View File

@ -94,7 +94,9 @@ public:
/// get name of (other way)
inline const char *text(void) { return getName(); } ;
/// get prop of type
Prop getProp( PropTag tag ) { return Yap_GetAProp( a , (PropFlags)tag ); }
Prop getProp( PropTag tag ) { return Yap_GetAProp( a , (PropFlags)tag ); };
/// as Atom
Atom asAtom() { return a; };
};
/**
@ -158,12 +160,15 @@ public:
/// Getter: extract name of functor as an atom
///
/// this is for external usage.
YAPAtom name(void) { return YAPAtom(NameOfFunctor(f)); }
inline YAPAtom name() { return YAPAtom(NameOfFunctor(f)); };
/// Getter: extract arity of functor as an unsigned integer
///
/// this is for external usage.
uintptr_t arity(void) { return ArityOfFunctor(f); }
inline arity_t arity() { return ArityOfFunctor(f); };
/// Getter: extract functor as C pointer
///
/// inline Functor functor() { return f; };
};

View File

@ -744,6 +744,27 @@ YAPQuery::YAPQuery(YAPFunctor f, YAPTerm mod, YAPTerm ts[])
RECOVER_MACHINE_REGS();
}
YAPQuery::YAPQuery(YAPFunctor f, YAPTerm mod, Term ts[])
: YAPPredicate(f, mod) {
/* ignore flags for now */
BACKUP_MACHINE_REGS();
Term goal;
if (ts) {
size_t arity = f.arity();
goal = Yap_MkApplTerm(Yap_MkFunctor(f.name().asAtom(),arity), arity, ts);
nts = RepAppl(goal) + 1;
for (arity_t i = 0; i < arity; i++)
XREGS[i + 1] = ts[i];
} else {
goal = MkVarTerm();
}
openQuery();
names = YAPPairTerm(TermNil);
RECOVER_MACHINE_REGS();
}
#if 0
YAPQuery::YAPQuery(YAPFunctor f, YAPTerm ts[]) : YAPPredicate(f) {
/* ignore flags for now */

View File

@ -76,6 +76,7 @@ public:
/// least
/// the same arity as the functor.
YAPQuery(YAPPredicate p, YAPTerm t[]);
///
/// full constructor,
///
///
@ -83,6 +84,9 @@ public:
/// least
/// the same arity as the functor.
YAPQuery(YAPFunctor f, YAPTerm mod, YAPTerm t[]);
/// often, this is more efficient
///
YAPQuery(YAPFunctor f, YAPTerm mod, Term t[]);
/// functor/term constructor,
///
/// It is given a functor, and an array of terms that must have at least

View File

@ -147,6 +147,7 @@ int main(int argc, char **argv)
YAP_Reset(YAP_FULL_RESET, false);
/* End preprocessor code */
//mtrace();
bool rc = exec_top_level(BootMode, &init_args);
if (!rc)
return 1;

View File

@ -45,6 +45,7 @@
nb_heap_del/3,
nb_heap_peek/3,
nb_heap_empty/1,
nb_heap_reset/1,
nb_heap_size/2,
nb_beam/2,
nb_beam_close/1,

View File

@ -145,7 +145,7 @@ for ( [key,v] of singletonVars.entries()) {
console.log("reset");
}
CodeMirror.registerHelper("lint", "prolog", exportErrors);
//CodeMirror.registerHelper("lint", "prolog", exportErrors);
/*******************************
* CHARACTER ESCAPES *

View File

@ -30,6 +30,7 @@ set (PROBLOG_PROGRAMS
problog/version_control.yap
problog/nestedtries.yap
problog/utils.yap
problog/lbdd.yap
problog/utils_lbdd.yap
problog/ad_converter.yap
problog/termhandling.yap

View File

@ -1330,7 +1330,7 @@ set_fact_probability(ID,Prob) :-
retract(ProblogTerm),
ProblogTerm =.. [ProblogName|ProblogTermArgs],
nth1(ProblogArity,ProblogTermArgs,_,KeepArgs),
NewLogProb is log(Prob),
(isnan(Prob) -> NewLogProb = 0.0 ; NewLogProb is log(Prob)),
nth1(ProblogArity,NewProblogTermArgs,NewLogProb,KeepArgs),
NewProblogTerm =.. [ProblogName|NewProblogTermArgs],
assertz(NewProblogTerm).

View File

@ -68,10 +68,18 @@ log2prob(X,Slope,FactID,V) :-
sigmoid(V0, Slope, V).
bind_maplist([], _Slope, _X).
bind_maplist([Node-(Node-Pr)|MapList], Slope, X) :-
bind_maplist([Node-(Node-NPr)|MapList], Slope, X) :-
SigPr <== X[Node],
sigmoid(SigPr, Slope, Pr),
bind_maplist(MapList, Slope, X).
(Pr > 0.999
->
NPr = 0.999
;
Pr < 0.001
->
NPr = 0.001 ;
Pr = NPr ),
bind_maplist(MapList, Slope, X).
%get_prob(Node, Prob) :-

View File

@ -2,7 +2,6 @@
:- ensure_loaded(library(lists)).
:- ensure_loaded(library(rbtrees)).
:- ensure_loaded(library(tries)).
:- ensure_loaded(('../problog/ptree')).
:- ensure_loaded(library(trie_sp)).
:- ensure_loaded(library(bdd)).
:- ensure_loaded(library(bhash)).
@ -29,6 +28,8 @@ graph2bdd(Query,1,bdd(D,T,Vs)) :-
:- set_problog_flag(init_method,(Q,N,Bdd,user:graph2bdd(Q,N,Bdd))).
:- nb_heap(100000,Q), nb_setval(heap,Q).
%:- leash(0), spy graph2bdd.
@ -58,7 +59,8 @@ graph(X,Y,Trie_Completed_Proofs,Vs) :-
!,
export_answer([Y|Final], Trie_Completed_Proofs,Vs).
graph(X,Y,Trie_Completed_Proofs, Vs) :-
nb_heap(100000,Q),
nb_getval(heap, Q),
nb_heap_reset(Q),
path(X,Y,X,[X],Final, 0, _Pr, Q),
!,
export_answer(Final, Trie_Completed_Proofs, Vs).

View File

@ -17,7 +17,7 @@
:- use_module('../problog_lbfgs').
:- if(false).
:- if(true).
:- use_module('kbgraph').

View File

@ -800,6 +800,20 @@ gradient_descent :-
set_fact(FactID, Slope, P ) :-
X <== P[FactID],
sigmoid(X, Slope, Pr),
(Pr > 0.999
->
NPr = 0.999
;
Pr < 0.001
->
NPr = 0.001 ;
Pr = NPr ),
set_fact_probability(FactID, NPr).
set_tunable(I,Slope,P) :-
X <== P[I],
sigmoid(X,Slope,Pr),
(Pr > 0.99
->
NPr = 0.99
@ -808,13 +822,7 @@ set_fact(FactID, Slope, P ) :-
->
NPr = 0.01 ;
Pr = NPr ),
set_fact_probability(FactID, NPr).
set_tunable(I,Slope,P) :-
X <== P[I],
sigmoid(X,Slope,Pr),
set_fact_probability(I,Pr).
set_fact_probability(I,NPr).
:- include(problog/lbdd).

View File

@ -11,7 +11,6 @@ ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/os ${CMAKE_SOURCE_DIR}/H ${CMAKE
#talk to python.pl
add_library(YAPPython pyload.c ${PYTHON_HEADERS} )
if (WIN32)
add_library (Py4YAP OBJECT ${PYTHON_SOURCES} ${PYTHON_HEADERS})
else()

View File

@ -29,9 +29,6 @@ configure_file(yap4py/__init__.py.in yap4py/__init__.py)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/include
)
SET(SWIG_SOURCES
${CMAKE_SOURCE_DIR}/packages/swig/yap.i
)
@ -46,36 +43,37 @@ INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH} ${CMAKE_CURRENT_BINARY_DIR}/yap4py/i
# LIBRARY DESTINATION ${PYTHON_MODULE_PATH}
# )
if (CONDA)
set(bdist bdist_conda)
else()
set(bdist bdist_wheel)
endif()
add_custom_target( YAP4PY ALL
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -addextern -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/H/generated -I${CMAKE_SOURCE_DIR}/include
-I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/utf8proc -I.././.. -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/packages/python
-outdir ${CMAKE_CURRENT_BINARY_DIR}/yap4py -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx -oh ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh ${SWIG_SOURCES}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${SWIG_SOURCES} Py4YAP YAP++ yap4py/yapi.cpp YAP4PY_PY
)
add_custom_command( OUTPUT yap4py/yapi.cpp
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp ${CMAKE_CURRENT_BINARY_DIR}/yap4py
DEPENDS ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp
)
add_custom_command( OUTPUT YAP4PY_PY
COMMAND ${CMAKE_COMMAND} -E copy ${PYTHON_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/yap4py
DEPENDS ${PYTHON_SOURCES}
add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh
COMMAND ${SWIG_EXECUTABLE} -c++ -python -O -py3 -module "yap" -addextern -I${CMAKE_SOURCE_DIR}/H -I${CMAKE_SOURCE_DIR}/H/generated -I${CMAKE_SOURCE_DIR}/include
-I${CMAKE_SOURCE_DIR}/OPTYap -I${CMAKE_SOURCE_DIR}/os -I${CMAKE_SOURCE_DIR}/utf8proc -I.././.. -I${CMAKE_SOURCE_DIR}/CXX -I${CMAKE_SOURCE_DIR}/packages/python
-outdir ${CMAKE_CURRENT_BINARY_DIR}/yap4py -I${GMP_INCLUDE_DIRS} -DX_API="" -o ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx -oh ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh ${SWIG_SOURCES}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${SWIG_SOURCES} yap4py/yapi.cpp
)
install(CODE "execute_process(
add_custom_target( YAP4PY ALL
DEPENDS ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp Py4YAP YAP++ yap4py/yapi.cpp ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh
)
add_custom_command( TARGET YAP4PY
PRE_BUILD
COMMAND ${CMAKE_COMMAND} -E copy ${PYTHON_SOURCES} ${CMAKE_CURRENT_BINARY_DIR}/yap4py
COMMAND ${PYTHON_EXECUTABLE} setup.py sdist ${bdist}
DEPENDS ${CMAKE_SOURCE_DIR}/CXX/yapi.cpp Py4YAP YAP++ yap4py/yapi.cpp YAP4PY_PY ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.cxx ${CMAKE_CURRENT_BINARY_DIR}/yap4py/yap_wrap.hh ${PYTHON_SOURCES} Py4YAP STARTUP libYap
)
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed .
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})"
DEPENDS Py4YAP ${CMAKE_BINARY_DIR}/${YAP_STARTUP} ${YAP_INSTALL_LIBDIR} )
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
install(FILES ${YAP4PY_PL} DESTINATION ${YAP_INSTALL_DATADIR} )

View File

@ -1,6 +1,10 @@
import readline
import copy
from yap4py.yap import *
try:
from yap4py.yap import *
except Exception as e:
print(e)
exit(0)
from yap4py.systuples import python_query, show_answer, library, prolog_library, v0, compile, namedtuple
from os.path import join, dirname

View File

@ -1,7 +1,7 @@
set (PYTHON_SOURCES
core/yap_kernel/__init__.py
core/yap_kernel/getipython.py
core/__init__.py
#core/yap_kernel/__init__.py
#core/yap_kernel/getipython.py
#core/__init__.py
_version.py
yap_kernel/datapub.py
yap_kernel/serialize.py
@ -62,7 +62,7 @@ yap_kernel/pylab/__init__.py
yap_kernel/__main__.py
yap_kernel.py
kernelspec.py
__init__.py
#__init__.py
yap_kernel_launcher.py
docs/conf.py
setup.py
@ -431,17 +431,15 @@ endforeach()
add_custom_target(YAP_KERNEL ALL
add_custom_target(YAP_KERNEL
ALL
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} build sdist bdist
DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-32x32.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/logo-64x64.png ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/kernel.js ${CMAKE_CURRENT_BINARY_DIR}/yap_kernel/resources/prolog.js ${OUTS} YAP4PY
COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} sdist ${bdist}
)
set(REAL_SOURCES real.c)
install(CODE "execute_process(
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed --no-deps .
COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PYTHON_USER_INSTALL} --ignore-installed .
COMMAND ${PYTHON_EXECUTABLE} -m yap_kernel.kernelspec
ERROR_VARIABLE setupErr
OUTPUT_VARIABLE setupOut

View File

@ -34,12 +34,20 @@ import os
import shutil
from distutils.core import setup
from glob import glob
from shutil import copy
pjoin = os.path.join
here = os.path.abspath(os.path.dirname(__file__))
packages = ['yap_kernel','yap_ipython']
# pkg_root = pjoin(here, name)
try:
copy(glob(pjoin(here,"../swig/build/lib*/_yap*"))[0],here)
copy(glob(pjoin(here,"../../../libYap*"))[-1],here)
except:
pass
for d, _, _ in os.walk(pjoin(here, 'yap_kernel')):
if os.path.exists(pjoin(d, '__init__.py')):
packages.append(d[len(here)+1:].replace(os.path.sep, '.'))

View File

@ -14,6 +14,7 @@ name = 'yap_kernel'
#-----------------------------------------------------------------------------
import sys
import os
v = sys.version_info
if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
@ -28,10 +29,13 @@ PY3 = (sys.version_info[0] >= 3)
#-----------------------------------------------------------------------------
import os
from glob import glob
from glob import globx
from shutil import copy
from distutils.core import setup
copy(glob("../swig/build/lib/_yap*")[0],"../swig/yap4py")
copy(glob("../../libYap*")[-1],"../swig/yap4py")
packages = ["${CMAKE_CURRENT_SOURCE_DIR}"]
version_ns = {}
@ -53,9 +57,8 @@ setup_args = dict(
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'License :: OSI Approved :: Perl License',
'Programming Language :: Prolog',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
)
@ -79,4 +82,5 @@ if 'setuptools' in sys.modules:
setup_args.update(setuptools_args)
if __name__ == '__main__':
sys.path += ['../swig']
setup(**setup_args)

View File

@ -20,12 +20,17 @@ class yap4r {
std::vector<YAPTerm> args;
bool failed;
public:
SEXP qsexp;
yap4r();
bool query(std::string p_name,std::string p_module,Rcpp::GenericVector sexps);
bool query(std::string p_name, GenericVector sexps=R_NilValue, std::string p_module="user");
bool more();
bool done();
SEXP peek(int i);
bool compile(std::string s);
bool library(std::string s);
};
yap4r::yap4r() {
@ -36,25 +41,57 @@ public:
bool yap4r::query(std::string p_name,std::string p_module,Rcpp::GenericVector sexps) {
bool yap4r::query(std::string p_name, GenericVector sexps, std::string p_module) {
if (q) {
q->close();
q = NULL;
q = nullptr;
}
std::vector<Term> args = std::vector<Term>();
yhandle_t t;
arity_t arity;
if (sexps.isNULL()) {
YAPTerm qt = YAPAtomTerm(p_name.c_str());
q = new YAPQuery(qt);
t =qt.handle();
} else {
arity = sexps.length();
std::vector<YAPTerm> args = std::vector<YAPTerm>();
yhandle_t sls = Yap_NewHandles(sexps.length());
for (int i=0; i<sexps.length();i++) {
if (!sexp_to_pl(sls+i, sexps[i]))
return false;
args.push_back( Yap_GetFromSlot(sls+i) );
args.push_back( YAPTerm(Yap_GetFromSlot(sls+i)) );
}
YAPTerm qt = YAPApplTerm(p_name,args);
q = new YAPQuery(qt);
return true;
YAPFunctor f= YAPFunctor(p_name.c_str(), arity);
YAPAtomTerm mod = YAPAtomTerm(p_module.c_str());
t = YAPApplTerm(p_name.c_str(),args.data()).handle();
q = new YAPQuery(f,mod,args.data());
}
if (q == nullptr)
return false;
bool rc = q->next();
if (!rc) {
failed = true;
q = nullptr;
}
if(rc)
qsexp = term_to_sexp(t, false);
return rc;
}
bool yap4r::compile(std::string s) {
YAPTerm fs[1];
fs[0] = YAPAtomTerm(s.c_str());
return yap->mgoal(YAPApplTerm("compile",fs).term(), USER_MODULE);
}
bool yap4r::library(std::string s) {
YAPTerm fs[1], l[1];
l[0] = YAPAtomTerm(s.c_str());
fs[0] = YAPApplTerm("library", l);
return yap->mgoal(YAPApplTerm("compile",fs).term(), USER_MODULE);
}
bool yap4r::more() {
bool rc = true;
@ -83,6 +120,8 @@ public:
SEXP yap4r::peek(int i) {
if (failed || q==nullptr)
return R_MissingArg;
if (i==0)
return qsexp;
return term_to_sexp(Yap_InitSlot(Yap_XREGS[i]), false);
}
@ -93,6 +132,8 @@ public:
.method( "query", &yap4r::query, "create an active query within the engine")
.method( "more", &yap4r::more, "ask for an extra solution")
.method( "done", &yap4r::done, "terminate the query")
.method( "compile", &yap4r::compile, "compile the file")
.method( "library", &yap4r::library, "compile the library")
.method( "peek", &yap4r::peek, "load arg[i] into R")
;
}

View File

@ -26,10 +26,9 @@
lbfgs_finalize/1,
lbfgs_set_parameter/3,
lbfgs_get_parameter/3,
lbfgs_parameters/0,
lbfgs_parameters/1]).
lbfgs_set_parameter/2,
lbfgs_get_parameter/2,
lbfgs_parameters/0]).
% switch on all the checks to reduce bug searching time
% :- yap_flag(unknown,error).
@ -187,12 +186,12 @@ lbfgs_finalize(t(_N,X,_U,Params)) :-
run the algorithm. output the final score of the function being optimised
*/
lbfgs_run(t(N,X,U,Params),FX) :-
lbfgs(N,X, Params, U, FX).
lbfgs_run(t(N,X,U),FX) :-
lbfgs(N,X, U, FX).
/** @pred lbfgs_parameters/1
/** @pred lbfgs_parameters/0
Prints a table with the current parameters. See the <a href="http://www.chokkan.org/software/liblbfgs/structlbfgs__parameter__t.html#_details">documentation
of libLBFGS</a> for the meaning of each parameter.
@ -220,47 +219,43 @@ int orthantwise_end -1 End index for computing the L1 norm
~~~~
*/
lbfgs_parameters :-
lbfgs_defaults(Params),
lbfgs_parameters(t(_X,_,_,Params)).
lbfgs_parameters(t(_,_,_,Params)) :-
lbfgs_get_parameter(m,M ,Params),
lbfgs_get_parameter(epsilon,Epsilon ,Params),
lbfgs_get_parameter(past,Past ,Params),
lbfgs_get_parameter(delta,Delta ,Params),
lbfgs_get_parameter(max_iterations,Max_Iterations ,Params),
lbfgs_get_parameter(linesearch,Linesearch ,Params),
lbfgs_get_parameter(max_linesearch,Max_Linesearch ,Params),
lbfgs_get_parameter(min_step,Min_Step ,Params),
lbfgs_get_parameter(max_step,Max_Step ,Params),
lbfgs_get_parameter(ftol,Ftol ,Params),
lbfgs_get_parameter(gtol,Gtol ,Params),
lbfgs_get_parameter(xtol,Xtol ,Params),
lbfgs_get_parameter(orthantwise_c,Orthantwise_C ,Params),
lbfgs_get_parameter(orthantwise_start,Orthantwise_Start ,Params),
lbfgs_get_parameter(orthantwise_end,Orthantwise_End ,Params),
lbfgs_get_parameter(m,M ),
lbfgs_get_parameter(epsilon,Epsilon ),
lbfgs_get_parameter(past,Past ),
lbfgs_get_parameter(delta,Delta ),
lbfgs_get_parameter(max_iterations,Max_Iterations ),
lbfgs_get_parameter(linesearch,Linesearch ),
lbfgs_get_parameter(max_linesearch,Max_Linesearch ),
lbfgs_get_parameter(min_step,Min_Step ),
lbfgs_get_parameter(max_step,Max_Step ),
lbfgs_get_parameter(ftol,Ftol ),
lbfgs_get_parameter(gtol,Gtol ),
lbfgs_get_parameter(xtol,Xtol ),
lbfgs_get_parameter(orthantwise_c,Orthantwise_C ),
lbfgs_get_parameter(orthantwise_start,Orthantwise_Start ),
lbfgs_get_parameter(orthantwise_end,Orthantwise_End ),
format('/******************************************************************************************~n',[] ),
print_param('Name','Value','Description','Type' ,Params),
print_param('Name','Value','Description','Type' ),
format('******************************************************************************************~n',[] ),
print_param(m,M,'The number of corrections to approximate the inverse hessian matrix.',int ,Params),
print_param(epsilon,Epsilon,'Epsilon for convergence test.',float ,Params),
print_param(past,Past,'Distance for delta-based convergence test.',int ,Params),
print_param(delta,Delta,'Delta for convergence test.',float ,Params),
print_param(max_iterations,Max_Iterations,'The maximum number of iterations',int ,Params),
print_param(linesearch,Linesearch,'The line search algorithm.',int ,Params),
print_param(max_linesearch,Max_Linesearch,'The maximum number of trials for the line search.',int ,Params),
print_param(min_step,Min_Step,'The minimum step of the line search routine.',float ,Params),
print_param(max_step,Max_Step,'The maximum step of the line search.',float ,Params),
print_param(ftol,Ftol,'A parameter to control the accuracy of the line search routine.',float ,Params),
print_param(gtol,Gtol,'A parameter to control the accuracy of the line search routine.',float ,Params),
print_param(xtol,Xtol,'The machine precision for floating-point values.',float ,Params),
print_param(orthantwise_c,Orthantwise_C,'Coefficient for the L1 norm of variables',float ,Params),
print_param(orthantwise_start,Orthantwise_Start,'Start index for computing the L1 norm of the variables.',int ,Params),
print_param(orthantwise_end,Orthantwise_End,'End index for computing the L1 norm of the variables.',int ,Params),
print_param(m,M,'The number of corrections to approximate the inverse hessian matrix.',int ),
print_param(epsilon,Epsilon,'Epsilon for convergence test.',float ),
print_param(past,Past,'Distance for delta-based convergence test.',int ),
print_param(delta,Delta,'Delta for convergence test.',float ),
print_param(max_iterations,Max_Iterations,'The maximum number of iterations',int ),
print_param(linesearch,Linesearch,'The line search algorithm.',int ),
print_param(max_linesearch,Max_Linesearch,'The maximum number of trials for the line search.',int ),
print_param(min_step,Min_Step,'The minimum step of the line search routine.',float ),
print_param(max_step,Max_Step,'The maximum step of the line search.',float ),
print_param(ftol,Ftol,'A parameter to control the accuracy of the line search routine.',float ),
print_param(gtol,Gtol,'A parameter to control the accuracy of the line search routine.',float ),
print_param(xtol,Xtol,'The machine precision for floating-point values.',float ),
print_param(orthantwise_c,Orthantwise_C,'Coefficient for the L1 norm of variables',float ),
print_param(orthantwise_start,Orthantwise_Start,'Start index for computing the L1 norm of the variables.',int ),
print_param(orthantwise_end,Orthantwise_End,'End index for computing the L1 norm of the variables.',int ),
format('******************************************************************************************/~n',[]),
format(' use lbfgs_set_parameter(Name,Value,Solver) to change parameters~n',[]),
format(' use lbfgs_get_parameter(Name,Value,Solver) to see current parameters~n',[]),
format(' use lbfgs_set_parameter(Name,Value) to change parameters~n',[]),
format(' use lbfgs_get_parameter(Name,Value) to see current parameters~n',[]),
format(' use lbfgs_parameters to print this overview~2n',[]).

View File

@ -39,14 +39,14 @@ static lbfgsfloatval_t evaluate(void *instance, const lbfgsfloatval_t *x,
YAP_Term call;
YAP_Bool result;
lbfgsfloatval_t rc;
YAP_Term v;
YAP_Term v, t1, t12;
YAP_Term t[6], t2[2];
t[0] = v = YAP_MkVarTerm();
t[1] = YAP_MkIntTerm((YAP_Int)x);
t[1] = YAP_MkApplTerm(ffloats, 1, t + 1);
t[2] = YAP_MkIntTerm((YAP_Int)g_tmp);
t[2] = YAP_MkApplTerm(ffloats, 1, t + 2);
t1 = YAP_MkIntTerm((YAP_Int)x);
t[1] = YAP_MkApplTerm(ffloats, 1, &t1);
t12 = YAP_MkIntTerm((YAP_Int)g_tmp);
t[2] = YAP_MkApplTerm(ffloats, 1, &t12);
t[3] = YAP_MkIntTerm(n);
t[4] = YAP_MkFloatTerm(step);
t[5] = YAP_MkIntTerm((YAP_Int)instance);
@ -310,7 +310,9 @@ static YAP_Bool p_lbfgs(void) {
s = "A logic error (negative line-search step) occurred.";
break;
}
fprintf(stderr, "optimization terminated with code %d: %s\n", ret, s);
char ss[1024];
snprintf(ss, 1023, "optimization terminated with code %d: %s\n", ret, s);
fputs(ss, stderr);
return true;
}
@ -326,16 +328,8 @@ static YAP_Bool lbfgs_grab(void) {
return YAP_Unify(YAP_ARG2, YAP_MkApplTerm(ffloats, 1, &t));
}
static YAP_Bool lbfgs_parameters(void) {
lbfgs_parameter_t *x = malloc(sizeof(lbfgs_parameter_t));
lbfgs_parameter_init(x);
return YAP_Unify(YAP_ARG1, YAP_MkIntTerm((YAP_Int)x));
}
static lbfgs_parameter_t parms;
static YAP_Bool lbfgs_release_parameters(void) {
free((void *)YAP_IntOfTerm(YAP_ARG1));
return true;
}
static YAP_Bool lbfgs_release(void) {
/* if (lbfgs_status == LBFGS_STATUS_NONE) { */
@ -349,11 +343,11 @@ static YAP_Bool lbfgs_release(void) {
return TRUE;
/* return FALSE; */
}
static YAP_Bool lbfgs_defaults(void) {
static lbfgs_parameter_t *get_params(YAP_Term t) {
YAP_Int ar = YAP_ArityOfFunctor(YAP_FunctorOfTerm(t));
YAP_Term arg = YAP_ArgOfTerm(ar, t);
return (lbfgs_parameter_t *)YAP_IntOfTerm(arg);
lbfgs_parameter_init(&parms);
return TRUE;
/* return FALSE; */
}
/** @pred lbfgs_set_parameter(+Name,+Value,+Parameters)
@ -363,7 +357,7 @@ is not running.
static YAP_Bool lbfgs_set_parameter(void) {
YAP_Term t1 = YAP_ARG1;
YAP_Term t2 = YAP_ARG2;
lbfgs_parameter_t *param = get_params(YAP_ARG3);
lbfgs_parameter_t *param = &parms;
/* if (lbfgs_status != LBFGS_STATUS_NONE && lbfgs_status !=
* LBFGS_STATUS_INITIALIZED){ */
/* printf("ERROR: Lbfgs is running right now. Please wait till it is
@ -523,7 +517,7 @@ Get the current Value for Name
static YAP_Bool lbfgs_get_parameter(void) {
YAP_Term t1 = YAP_ARG1;
YAP_Term t2 = YAP_ARG2;
lbfgs_parameter_t *param = get_params(YAP_ARG3);
lbfgs_parameter_t *param = &parms;
if (!YAP_IsAtomTerm(t1)) {
return FALSE;
@ -575,14 +569,14 @@ X_API void init_lbfgs_predicates(void) {
tuser = YAP_MkAtomTerm(YAP_LookupAtom("user"));
// Initialize the parameters for the L-BFGS optimization.
// lbfgs_parameter_init(&param);
lbfgs_parameter_init(&parms);
YAP_UserCPredicate("lbfgs_grab", lbfgs_grab, 2);
YAP_UserCPredicate("lbfgs", p_lbfgs, 5);
YAP_UserCPredicate("lbfgs_release", lbfgs_release, 1);
YAP_UserCPredicate("lbfgs_defaults", lbfgs_parameters, 1);
YAP_UserCPredicate("lbfgs_release_parameters", lbfgs_release_parameters, 1);
YAP_UserCPredicate("lbfgs_set_parameter", lbfgs_set_parameter, 3);
YAP_UserCPredicate("lbfgs_get_parameter", lbfgs_get_parameter, 3);
YAP_UserCPredicate("lbfgs_defaults", lbfgs_defaults, 0);
YAP_UserCPredicate("lbfgs_set_parameter", lbfgs_set_parameter, 2);
YAP_UserCPredicate("lbfgs_get_parameter", lbfgs_get_parameter, 2);
}