Python Library improved
This commit is contained in:
parent
a53615ceaf
commit
5d6ff87d19
10
.gitignore
vendored
10
.gitignore
vendored
@ -80,14 +80,10 @@ GitSHA1.c
|
||||
CMakeLists.txt.*
|
||||
FindPackageLog.txt
|
||||
GitSHA1.c
|
||||
|
||||
GitSHA1.c
|
||||
|
||||
os/YapIOConfig.h
|
||||
|
||||
os/YapIOConfig.h
|
||||
|
||||
clang
|
||||
cmake-build-debug
|
||||
os/YapIOConfig.h
|
||||
CodeBlocks
|
||||
|
||||
os/readterm.c.cpp
|
||||
|
||||
|
@ -1,7 +0,0 @@
|
||||
set (PYTHON_SOURCES python.c pl2py.c pybips.c py2pl.c pl2pl.c pypreds.c)
|
||||
|
||||
|
||||
set (PYTHON_HEADERS
|
||||
python.h)
|
||||
|
||||
|
@ -1,48 +0,0 @@
|
||||
import base64
|
||||
import imghdr
|
||||
import os
|
||||
|
||||
#from IPython.
|
||||
|
||||
_TEXT_SAVED_IMAGE = "yap_kernel: saved image data to:"
|
||||
|
||||
image_setup_cmd = """
|
||||
display () {
|
||||
TMPFILE=$(mktemp ${TMPDIR-/tmp}/yap_kernel.XXXXXXXXXX)
|
||||
cat > $TMPFILE
|
||||
echo "%s $TMPFILE" >&2
|
||||
}
|
||||
""" % _TEXT_SAVED_IMAGE
|
||||
|
||||
def display_data_for_image(filename):
|
||||
with open(filename, 'rb') as f:
|
||||
image = f.read()
|
||||
os.unlink(filename)
|
||||
|
||||
image_type = imghdr.what(None, image)
|
||||
if image_type is None:
|
||||
raise ValueError("Not a valid image: %s" % image)
|
||||
|
||||
image_data = base64.b64encode(image).decode('ascii')
|
||||
content = {
|
||||
'data': {
|
||||
'image/' + image_type: image_data
|
||||
},
|
||||
'metadata': {}
|
||||
}
|
||||
return content
|
||||
|
||||
|
||||
def extract_image_filenames(output):
|
||||
output_lines = []
|
||||
image_filenames = []
|
||||
|
||||
for line in output.split("\n"):
|
||||
if line.startswith(_TEXT_SAVED_IMAGE):
|
||||
filename = line.rstrip().split(": ")[-1]
|
||||
image_filenames.append(filename)
|
||||
else:
|
||||
output_lines.append(line)
|
||||
|
||||
output = "\n".join(output_lines)
|
||||
return image_filenames, output
|
@ -1,92 +0,0 @@
|
||||
from __future__ import print_function
|
||||
|
||||
from metakernel import MetaKernel
|
||||
|
||||
from metakernel import register_ipython_magics
|
||||
register_ipython_magics()
|
||||
|
||||
class MetaKernelyap(MetaKernel):
|
||||
implementation = 'MetaKernel YAP'
|
||||
implementation_version = '1.0'
|
||||
language = 'text'
|
||||
language_version = '0.1'
|
||||
banner = "MetaKernel YAP"
|
||||
language_info = {
|
||||
'mimetype': 'text/plain',
|
||||
'name': 'text',
|
||||
# ------ If different from 'language':
|
||||
'codemirror_mode': {
|
||||
"version": 2,
|
||||
"name": "prolog"
|
||||
}
|
||||
'pygments_lexer': 'language',
|
||||
'version' : "0.0.1",
|
||||
'file_extension': '.yap',
|
||||
'help_links': MetaKernel.help_links,
|
||||
}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
|
||||
MetaKernel.__init__(self, **kwargs)
|
||||
self._start_yap()
|
||||
self.qq = None sq
|
||||
|
||||
def _start_yap(self):
|
||||
# Signal handlers are inherited by forked processes, and we can't easily
|
||||
# reset it from the subprocess. Since kernelapp ignores SIGINT except in
|
||||
# message handlers, we need to temporarily reset the SIGINT handler here
|
||||
# so that yap and its children are interruptible.
|
||||
sig = signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||
try:
|
||||
engine = yap.YAPEngine()
|
||||
engine.query("load_files(library(python), [])").command()
|
||||
banner = "YAP {0} Kernel".format(self.engine.version())
|
||||
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, sig)
|
||||
|
||||
# Register Yap function to write image data to temporary file
|
||||
#self.yapwrapper.run_command(image_setup_cmd)
|
||||
|
||||
def get_usage(self):
|
||||
return "This is the YAP kernel."
|
||||
|
||||
def do_execute_direct(self, code):
|
||||
if not code.strip():
|
||||
return {'status': 'ok', 'execution_count': self.execution_count,
|
||||
'payload': [], 'user_expressions': {}}
|
||||
|
||||
interrupted = False
|
||||
try:
|
||||
print self.q
|
||||
if self.q is None:
|
||||
self.q = self.engine.query(code.rstrip())
|
||||
if self.q.next():
|
||||
vs = self.q.namedVars()
|
||||
if vs.length() > 0:
|
||||
l = []
|
||||
while vs.length() > 0:
|
||||
eq = vs.car()
|
||||
l.append(' '.join([getArg(1).text(), '=', eq.getArg(2).text())
|
||||
vs = vs.cdr()
|
||||
l.append(';')
|
||||
o = '\n'.join(l)
|
||||
else:
|
||||
return 'yes'
|
||||
self.q = None
|
||||
|
||||
else:
|
||||
return 'no'
|
||||
self.q = None
|
||||
|
||||
|
||||
|
||||
def repr(self, data):
|
||||
return repr(data)
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
from ipykernel.kernelapp import IPKernelApp
|
||||
except ImportError:
|
||||
from IPython.kernel.zmq.kernelapp import IPKernelApp
|
||||
IPKernelApp.launch_instance(kernel_class=MetaKernelyap)
|
@ -1,61 +1,7 @@
|
||||
%matplotlib inline
|
||||
import numpy as np
|
||||
import seaborn as sns
|
||||
import matplotlib.pyplot as plt
|
||||
sns.set(style="white", context="talk")
|
||||
rs = np.random.RandomState(7)
|
||||
|
||||
pos={0:(0,0),
|
||||
1:(1,0),
|
||||
2:(0,1),
|
||||
3:(1,1),
|
||||
4:(0.1,0.9),
|
||||
5:(0.3,1.1),
|
||||
6:(0.9,0.9)
|
||||
}
|
||||
:- use_module( library(python) ).
|
||||
|
||||
names={4:'MMM',
|
||||
5:'XXX',
|
||||
6:'ZZZ'}
|
||||
:- := import(pandas)).
|
||||
|
||||
def plot1(y10,y20):
|
||||
def gen(f,f0):
|
||||
return [f[0],f[1],-f[2]]/max(f,f0)
|
||||
ax1 = plt.subplot2grid((1,2), (0,0), colspan=2)
|
||||
ax2 = plt.subplot2grid((1,2), (0,1), colspan=2)
|
||||
ax3 = plt.subplot2grid((2,2), (2,0), colspan=2, rowspan=2)
|
||||
|
||||
xs = ["+-","++","--"]
|
||||
y1 = gen(y10, y20)
|
||||
sns.barplot(xs, y1, palette="RdBu_r", ax=ax1)
|
||||
y2 = gen(y20,y10)
|
||||
sns.barplot(xs, y2, palette="Set3", ax=ax2)
|
||||
# Finalize the plot
|
||||
# sns.despine(bottom=True)
|
||||
|
||||
|
||||
G=nx.Graph()
|
||||
i=0
|
||||
G.pos={} # location
|
||||
G.pop={} # size
|
||||
lpos={0:(0,0),1:(0,0),2:(0,0),3:(0,0)}
|
||||
last=len(pos)-1
|
||||
for i in range(4,len(pos)):
|
||||
G.pos[i]=pos[i]
|
||||
G.pop[i]=2000
|
||||
(x,y) = pos[i]
|
||||
lpos[i] = (x,y-0.05)
|
||||
if i > 4:
|
||||
G.add_edge(i-1,i)
|
||||
else:
|
||||
G.add_edge(2,i)
|
||||
G.add_edge(3,last)
|
||||
nx.draw_networkx_nodes(G,pos,nodelist=range(4,len(pos)),ax=ax3)
|
||||
nx.draw_networkx_nodes(G,pos,nodelist=[0,1,2,3],node_color='b',ax=ax3)
|
||||
nx.draw_networkx_edges(G,pos,alpha=0.5,ax=ax3)
|
||||
nx.draw_networkx_labels(G,lpos,names,alpha=0.5,ax=ax3)
|
||||
plt.axis('off')
|
||||
plt.tight_layout(h_pad=3)
|
||||
plt.savefig("house_with_colors.png") # save as png
|
||||
|
||||
plot1([20,30,10],[30,30,5])
|
||||
pred2panda(Pred, Obj) :-
|
||||
|
@ -27,7 +27,7 @@ static foreign_t array_to_python_list(term_t addr, term_t type, term_t szt,
|
||||
}
|
||||
}
|
||||
if (PL_is_variable(py)) {
|
||||
return python_to_ptr(list, py);
|
||||
return address_to_term(list, py);
|
||||
}
|
||||
return assign_to_symbol(py, list);
|
||||
}
|
||||
@ -71,7 +71,7 @@ static foreign_t array_to_python_tuple(term_t addr, term_t type, term_t szt,
|
||||
}
|
||||
}
|
||||
if (PL_is_variable(py)) {
|
||||
return python_to_ptr(list, py);
|
||||
return address_to_term(list, py);
|
||||
}
|
||||
return assign_to_symbol(py, list);
|
||||
}
|
||||
@ -107,13 +107,44 @@ static foreign_t array_to_python_view(term_t addr, term_t type, term_t szt,
|
||||
return false;
|
||||
}
|
||||
if (PL_is_variable(py)) {
|
||||
return python_to_ptr(o, 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);
|
||||
}
|
||||
|
@ -2,112 +2,104 @@
|
||||
|
||||
#include "python.h"
|
||||
|
||||
PyObject *yap_to_python(YAP_Term t, bool eval) {
|
||||
term_t yt = YAP_InitSlot(t);
|
||||
PyObject *o = term_to_python(yt, eval);
|
||||
PL_reset_term_refs(yt);
|
||||
return o;
|
||||
PyObject *py_Local, *py_Global;
|
||||
|
||||
PyObject *YE(term_t t, int line, const char *file, const char *code)
|
||||
{
|
||||
char buf[1024];
|
||||
YAP_WriteBuffer(YAP_GetFromSlot(t), buf, 1023, 0);
|
||||
fprintf(stderr, "**** Warning,%s@%s:%d: failed on expression %s\n", code, file, line, buf );
|
||||
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
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 );
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
// Yap_DebugPlWritep(YAP_GetFromSlot(t)); fprintf(stderr, " here I
|
||||
* 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≈
|
||||
YAP_Term yt = YAP_GetFromSlot(t);
|
||||
// Yap_DebugPlWriteln(yt);
|
||||
switch (PL_term_type(t)) {
|
||||
case PL_VARIABLE: {
|
||||
YAP_Term i = YAP_MkIntTerm(t);
|
||||
return term_to_nametuple(
|
||||
"H", 1, YAP_InitSlot(YAP_MkApplTerm(
|
||||
YAP_MkFunctor(YAP_LookupAtom("H"), 1), 1, &i)));
|
||||
PyObject *rc = term_to_nametuple(
|
||||
"H", 1, YAP_InitSlot(YAP_MkApplTerm(
|
||||
YAP_MkFunctor(YAP_LookupAtom("H"), 1), 1, &i)));
|
||||
return CHECKNULL( t, rc );
|
||||
};
|
||||
case PL_ATOM: {
|
||||
YAP_Atom at = YAP_AtomOfTerm(yt);
|
||||
const char *s;
|
||||
PyObject *o;
|
||||
PyObject *c = NULL;
|
||||
|
||||
s = YAP_AtomName(at);
|
||||
if (strcmp(s, "true") == 0)
|
||||
return Py_True;
|
||||
if (strcmp(s, "false") == 0)
|
||||
return Py_False;
|
||||
if (strcmp(s, "none") == 0)
|
||||
return Py_None;
|
||||
if (strcmp(s, "[]") == 0)
|
||||
o = PyList_New(0);
|
||||
else if (strcmp(s, "{}") == 0)
|
||||
o = PyDict_New();
|
||||
/* return __main__,s */
|
||||
else if ((o = PyRun_String(s, Py_single_input, PyEval_GetGlobals(),
|
||||
PyEval_GetLocals()))) {
|
||||
Py_IncRef(o);
|
||||
return o;
|
||||
} else if (PyObject_HasAttrString(py_Main, s)) {
|
||||
o = PyObject_GetAttrString(py_Main, s);
|
||||
} else {
|
||||
o = PyUnicode_FromString(s);
|
||||
if (eval)
|
||||
return NULL;
|
||||
if (PyObject_HasAttrString(py_Main, "A"))
|
||||
c = PyObject_GetAttrString(py_Main, "A");
|
||||
if (!c && PyObject_HasAttrString(py_Yapex, "A"))
|
||||
c = PyObject_GetAttrString(py_Yapex, "A");
|
||||
if (!c || !PyCallable_Check(c)) {
|
||||
return o;
|
||||
} else {
|
||||
PyObject *t = PyTuple_New(1);
|
||||
PyTuple_SET_ITEM(t, 0, PyUnicode_FromString(s));
|
||||
o = PyObject_CallObject(c, t);
|
||||
if (eval) {
|
||||
o = PythonLookup(s, o);
|
||||
/* if (!o)
|
||||
return o;
|
||||
*/
|
||||
} else
|
||||
{
|
||||
PyObject *o = PythonLookupSpecial(s);
|
||||
}
|
||||
}
|
||||
if (o) {
|
||||
Py_IncRef(o);
|
||||
}
|
||||
return o;
|
||||
} break;
|
||||
if (o) {
|
||||
Py_INCREF( o );
|
||||
return CHECKNULL(t,o);
|
||||
}
|
||||
}
|
||||
case PL_STRING: {
|
||||
char *s = NULL;
|
||||
if (!PL_get_chars(t, &s, REP_UTF8 | CVT_ATOM | CVT_STRING | BUF_MALLOC)) {
|
||||
return NULL;
|
||||
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)) {
|
||||
return PyString_FromStringAndSize(s, strlen(s));
|
||||
PyObject *o = PyString_FromStringAndSize(s, strlen(s)) ;
|
||||
return CHECKNULL(t, o);
|
||||
} else
|
||||
#endif
|
||||
{
|
||||
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
|
||||
// fprintf(stderr, "%s\n", s);
|
||||
free(s);
|
||||
if (pobj) {
|
||||
Py_IncRef(pobj);
|
||||
{
|
||||
PyObject *pobj = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
|
||||
return CHECKNULL(t,pobj);
|
||||
}
|
||||
return pobj;
|
||||
}
|
||||
} break;
|
||||
case PL_INTEGER: {
|
||||
int64_t j;
|
||||
if (!PL_get_int64_ex(t, &j))
|
||||
return NULL;
|
||||
return CHECKNULL(t,NULL);
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
return PyInt_FromLong(j);
|
||||
PyObject *o = PyInt_FromLong(j);
|
||||
return CHECKNULL(t,o);
|
||||
#else
|
||||
return PyLong_FromLong(j);
|
||||
PyObject *o = PyLong_FromLong(j);
|
||||
return CHECKNULL(t,o);
|
||||
#endif
|
||||
}
|
||||
|
||||
case PL_FLOAT: {
|
||||
PyObject *out;
|
||||
double fl;
|
||||
if (!PL_get_float(t, &fl))
|
||||
return NULL;
|
||||
return PyFloat_FromDouble(fl);
|
||||
return CHECKNULL(t,NULL);
|
||||
out = PyFloat_FromDouble(fl);
|
||||
return CHECKNULL(t, out);
|
||||
}
|
||||
default: {
|
||||
term_t tail = PL_new_term_ref(), arg;
|
||||
@ -118,29 +110,44 @@ PyObject *term_to_python(term_t t, bool eval) {
|
||||
arg = tail;
|
||||
out = PyList_New(len);
|
||||
if (!out)
|
||||
return NULL;
|
||||
return CHECKNULL(t,NULL);
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
if (!PL_get_list(t, arg, t)) {
|
||||
return NULL;
|
||||
PL_reset_term_refs(tail);
|
||||
return CHECKNULL(t,NULL);
|
||||
}
|
||||
if (PyList_SetItem(out, i, term_to_python(arg, eval)) < 0) {
|
||||
return NULL;
|
||||
if (PyList_SetItem(out, i, term_to_python(arg, eval, o)) < 0) {
|
||||
return CHECKNULL(t,NULL);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
PL_reset_term_refs(tail);
|
||||
return CHECKNULL(t,out);
|
||||
} else {
|
||||
functor_t fun;
|
||||
PyObject *rc;
|
||||
|
||||
if (!PL_get_functor(t, &fun))
|
||||
return NULL;
|
||||
if (!PL_get_functor(t, &fun)) {
|
||||
PL_reset_term_refs(tail);
|
||||
return CHECKNULL(t,NULL);
|
||||
}
|
||||
if (eval)
|
||||
return compound_to_pyeval(t, fun);
|
||||
return compound_to_pytree(t, fun);
|
||||
rc = compound_to_pyeval(t, o);
|
||||
else
|
||||
rc = compound_to_pytree(t, o);
|
||||
PL_reset_term_refs(tail);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
return CHECKNULL(t,NULL);
|
||||
}
|
||||
|
||||
PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o) {
|
||||
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) {
|
||||
@ -150,7 +157,8 @@ PyObject *deref_term_to_python(term_t t) {
|
||||
if (YAP_IsVarTerm(yt)) {
|
||||
char s[32];
|
||||
char *o = YAP_WriteBuffer(yt, s, 31, 0);
|
||||
return PyUnicode_FromString(o);
|
||||
PyObject *p = PyUnicode_FromString(o);
|
||||
return p;
|
||||
}
|
||||
return term_to_python(t, false);
|
||||
return term_to_python(t, false, NULL);
|
||||
}
|
||||
|
@ -1,61 +0,0 @@
|
||||
%matplotlib inline
|
||||
import numpy as np
|
||||
import seaborn as sns
|
||||
import matplotlib.pyplot as plt
|
||||
sns.set(style="white", context="talk")
|
||||
rs = np.random.RandomState(7)
|
||||
|
||||
pos={0:(0,0),
|
||||
1:(1,0),
|
||||
2:(0,1),
|
||||
3:(1,1),
|
||||
4:(0.1,0.9),
|
||||
5:(0.3,1.1),
|
||||
6:(0.9,0.9)
|
||||
}
|
||||
|
||||
names={4:'MMM',
|
||||
5:'XXX',
|
||||
6:'ZZZ'}
|
||||
|
||||
def plot1(y10,y20):
|
||||
def gen(f,f0):
|
||||
return [f[0],f[1],-f[2]]/max(f,f0)
|
||||
ax1 = plt.subplot2grid((1,2), (0,0), colspan=2)
|
||||
ax2 = plt.subplot2grid((1,2), (0,1), colspan=2)
|
||||
ax3 = plt.subplot2grid((2,2), (2,0), colspan=2, rowspan=2)
|
||||
|
||||
xs = ["+-","++","--"]
|
||||
y1 = gen(y10, y20)
|
||||
sns.barplot(xs, y1, palette="RdBu_r", ax=ax1)
|
||||
y2 = gen(y20,y10)
|
||||
sns.barplot(xs, y2, palette="Set3", ax=ax2)
|
||||
# Finalize the plot
|
||||
# sns.despine(bottom=True)
|
||||
|
||||
|
||||
G=nx.Graph()
|
||||
i=0
|
||||
G.pos={} # location
|
||||
G.pop={} # size
|
||||
lpos={0:(0,0),1:(0,0),2:(0,0),3:(0,0)}
|
||||
last=len(pos)-1
|
||||
for i in range(4,len(pos)):
|
||||
G.pos[i]=pos[i]
|
||||
G.pop[i]=2000
|
||||
(x,y) = pos[i]
|
||||
lpos[i] = (x,y-0.05)
|
||||
if i > 4:
|
||||
G.add_edge(i-1,i)
|
||||
else:
|
||||
G.add_edge(2,i)
|
||||
G.add_edge(3,last)
|
||||
nx.draw_networkx_nodes(G,pos,nodelist=range(4,len(pos)),ax=ax3)
|
||||
nx.draw_networkx_nodes(G,pos,nodelist=[0,1,2,3],node_color='b',ax=ax3)
|
||||
nx.draw_networkx_edges(G,pos,alpha=0.5,ax=ax3)
|
||||
nx.draw_networkx_labels(G,lpos,names,alpha=0.5,ax=ax3)
|
||||
plt.axis('off')
|
||||
plt.tight_layout(h_pad=3)
|
||||
plt.savefig("house_with_colors.png") # save as png
|
||||
|
||||
plot1([20,30,10],[30,30,5])
|
@ -1,9 +1,9 @@
|
||||
|
||||
#include "python.h"
|
||||
|
||||
static foreign_t repr_term(const char *pVal, size_t sz, term_t t) {
|
||||
static foreign_t repr_term(PyObject *pVal, term_t t) {
|
||||
term_t to = PL_new_term_ref(), t1 = PL_new_term_ref();
|
||||
PL_put_string_chars(t1, pVal);
|
||||
PL_put_pointer(t1, pVal);
|
||||
PL_cons_functor(to, FUNCTOR_pointer1, t1);
|
||||
Py_INCREF(pVal);
|
||||
PL_reset_term_refs(to);
|
||||
@ -12,119 +12,16 @@ static foreign_t repr_term(const char *pVal, size_t sz, term_t t) {
|
||||
|
||||
foreign_t assign_to_symbol(term_t t, PyObject *e);
|
||||
|
||||
/**
|
||||
* assign_python 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.
|
||||
*/
|
||||
int assign_python(PyObject *root, term_t t, PyObject *e) {
|
||||
switch (PL_term_type(t)) {
|
||||
case PL_VARIABLE:
|
||||
if (python_to_ptr(e, t))
|
||||
return 1;
|
||||
else
|
||||
return -1;
|
||||
case PL_ATOM:
|
||||
return assign_to_symbol(t, e);
|
||||
case PL_STRING:
|
||||
case PL_INTEGER:
|
||||
case PL_FLOAT:
|
||||
return -1;
|
||||
case PL_TERM:
|
||||
if (PL_is_list(t)) {
|
||||
return -1;
|
||||
} else {
|
||||
functor_t fun;
|
||||
|
||||
if (!PL_get_functor(t, &fun))
|
||||
return -1;
|
||||
if (fun == FUNCTOR_dollar1) {
|
||||
if (!PL_get_arg(1, t, t))
|
||||
return -1;
|
||||
return assign_to_symbol(t, e);
|
||||
}
|
||||
if (fun == FUNCTOR_pointer1) {
|
||||
return -1;
|
||||
}
|
||||
if (fun == FUNCTOR_sqbrackets2) {
|
||||
term_t targ = PL_new_term_ref(), trhs = PL_new_term_ref();
|
||||
PyObject *lhs, *rhs;
|
||||
|
||||
if (!PL_get_arg(1, t, targ))
|
||||
return -1;
|
||||
lhs = term_to_python(targ, true);
|
||||
if (!PL_get_arg(2, t, targ) || !PL_is_list(targ) ||
|
||||
!PL_get_list(targ, trhs, targ))
|
||||
return -1;
|
||||
if (PL_is_functor(trhs, FUNCTOR_dot2)) {
|
||||
Py_ssize_t left, right;
|
||||
if (!PL_get_arg(1, trhs, targ))
|
||||
return -1;
|
||||
left = get_p_int(term_to_python(targ, true), 0);
|
||||
if (!PL_get_arg(2, trhs, targ))
|
||||
return -1;
|
||||
right = get_p_int(term_to_python(targ, true), PyObject_Size(lhs));
|
||||
if (!PySequence_Check(lhs))
|
||||
return -1;
|
||||
PL_reset_term_refs(targ);
|
||||
return PySequence_SetSlice(lhs, left, right, e);
|
||||
} else {
|
||||
rhs = term_to_python(trhs, true);
|
||||
PL_reset_term_refs(targ);
|
||||
return PyObject_SetItem(lhs, rhs, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
foreign_t assign_to_symbol(term_t t, PyObject *e) {
|
||||
char *s;
|
||||
char *s = NULL;
|
||||
PyErr_Clear();
|
||||
if (!PL_get_atom_chars(t, &s)) {
|
||||
wchar_t *w;
|
||||
atom_t at;
|
||||
size_t len;
|
||||
PyObject *attr;
|
||||
|
||||
if (!PL_get_atom(t, &at)) {
|
||||
return false;
|
||||
}
|
||||
if (!(w = PL_atom_wchars(at, &len)))
|
||||
return false;
|
||||
attr = PyUnicode_FromWideChar(w, wcslen(w));
|
||||
if (attr) {
|
||||
return PyObject_SetAttr(py_Main, attr, e) >= 0;
|
||||
} else {
|
||||
PyErr_Print();
|
||||
return false;
|
||||
}
|
||||
} else if (proper_ascii_string(s)) {
|
||||
return PyObject_SetAttrString(py_Main, s, e) >= 0;
|
||||
} else {
|
||||
PyObject *attr = PyUnicode_DecodeLatin1(s, strlen(s), NULL);
|
||||
if (!attr)
|
||||
return -1;
|
||||
return PyObject_SetAttr(py_Main, attr, e) >= 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
foreign_t python_to_ptr(PyObject *pVal, term_t t) {
|
||||
Py_IncRef(pVal);
|
||||
return address_to_term(pVal, t);
|
||||
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) {
|
||||
@ -162,17 +59,17 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
|
||||
atom_t tmp_atom;
|
||||
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
Py_ssize_t sz = PyUnicode_GetSize(pVal) + 1;
|
||||
= PyUnicode_GetSize(pVal) + 1;
|
||||
wchar_t *ptr = malloc(sizeof(wchar_t) * sz);
|
||||
sz = PyUnicode_AsWideChar((PyUnicodeObject *)pVal, ptr, sz - 1);
|
||||
#else
|
||||
Py_ssize_t sz = PyUnicode_GetLength(pVal) + 1;
|
||||
wchar_t *ptr = malloc(sizeof(wchar_t) * sz);
|
||||
sz = PyUnicode_AsWideChar(pVal, ptr, sz);
|
||||
#endif
|
||||
tmp_atom = PL_new_atom_wchars(sz, ptr);
|
||||
tmp_atom = PL_new_atom_wchars(sz, ptr);
|
||||
free(ptr);
|
||||
return PL_unify_atom(t, tmp_atom);
|
||||
return PL_unify_atom(t, tmp_atom);
|
||||
#else
|
||||
const char *s = PyUnicode_AsUTF8(pVal);
|
||||
tmp_atom = PL_new_atom( s);
|
||||
return PL_unify_atom(t, tmp_atom);
|
||||
#endif
|
||||
} else if (PyByteArray_Check(pVal)) {
|
||||
atom_t tmp_atom = PL_new_atom(PyByteArray_AsString(pVal));
|
||||
return PL_unify_atom(t, tmp_atom);
|
||||
@ -209,14 +106,14 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
|
||||
f = PL_new_functor(ATOM_t, sz);
|
||||
if (!PL_unify_functor(t, f))
|
||||
return FALSE;
|
||||
term_t to = PL_new_term_ref();
|
||||
for (i = 0; i < sz; i++) {
|
||||
term_t to = PL_new_term_ref();
|
||||
if (!PL_unify_arg(i + 1, t, to))
|
||||
if (!PL_get_arg(i + 1, t, to))
|
||||
return FALSE;
|
||||
if (!python_to_term(PyTuple_GetItem(pVal, i), to))
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
return true;
|
||||
} else if (PyList_Check(pVal)) {
|
||||
term_t to = PL_new_term_ref();
|
||||
Py_ssize_t i, sz = PyList_GET_SIZE(pVal);
|
||||
@ -238,43 +135,34 @@ foreign_t python_to_term(PyObject *pVal, term_t t) {
|
||||
tnew = PL_new_term_ref();
|
||||
/* do something interesting with the values... */
|
||||
if (!python_to_term(key, tkey)) {
|
||||
PL_reset_term_refs(tkey);
|
||||
return FALSE;
|
||||
}
|
||||
if (!python_to_term(value, tval)) {
|
||||
PL_reset_term_refs(tkey);
|
||||
return FALSE;
|
||||
}
|
||||
/* reuse */
|
||||
tint = tkey;
|
||||
if (!PL_cons_functor(tint, FUNCTOR_colon2, tkey, tval)) {
|
||||
PL_reset_term_refs(tkey);
|
||||
return FALSE;
|
||||
}
|
||||
if (--left) {
|
||||
if (!PL_cons_functor(tint, FUNCTOR_comma2, tint, tnew))
|
||||
return FALSE;
|
||||
}
|
||||
if (!PL_unify(ti, tint))
|
||||
PL_reset_term_refs(tkey);
|
||||
return FALSE;
|
||||
}
|
||||
if (!PL_unify(ti, tint)) {
|
||||
PL_reset_term_refs(tkey);
|
||||
return FALSE;
|
||||
}
|
||||
ti = tnew;
|
||||
PL_reset_term_refs(tkey);
|
||||
}
|
||||
PL_cons_functor(to, FUNCTOR_curly1, to);
|
||||
return PL_unify(t, to);
|
||||
} else {
|
||||
PyObject *pValR = PyObject_Repr(pVal);
|
||||
if (pValR == NULL)
|
||||
return address_to_term(pVal, t);
|
||||
Py_ssize_t sz = PyUnicode_GetSize(pValR) + 1;
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
char *s = malloc(sizeof(char) * sz);
|
||||
PyObject *us = PyUnicode_EncodeUTF8((const Py_UNICODE *)pValR, sz, NULL);
|
||||
PyString_AsStringAndSize(us, &s, &sz);
|
||||
foreign_t rc = repr_term(s, sz, t);
|
||||
free((void *)s);
|
||||
return rc;
|
||||
#else
|
||||
// new interface
|
||||
char *s = PyUnicode_AsUTF8AndSize(pValR, &sz);
|
||||
return repr_term(s, sz, t);
|
||||
#endif
|
||||
return repr_term(pVal, t);
|
||||
}
|
||||
}
|
||||
|
||||
@ -283,6 +171,122 @@ X_API YAP_Term pythonToYAP(PyObject *pVal) {
|
||||
if (!python_to_term(pVal, t))
|
||||
return 0;
|
||||
YAP_Term tt = YAP_GetFromSlot(t);
|
||||
YAP_RecoverSlots(1, 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
|
||||
|
||||
if (PySequence_Check(exp) && PySequence_Length(exp) == len)
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
if (!PL_get_list(t, arg, t)) {
|
||||
PL_reset_term_refs(tail);
|
||||
return false;
|
||||
}
|
||||
if (!python_assign(arg, PySequence_GetItem(exp, i), context)) {
|
||||
PL_reset_term_refs(tail);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
PL_reset_term_refs(tail);
|
||||
return true;
|
||||
} 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);
|
||||
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
File diff suppressed because it is too large
Load Diff
@ -1,10 +1,8 @@
|
||||
|
||||
#include "python.h"
|
||||
|
||||
int assign_python(PyObject *root, term_t t, PyObject *e);
|
||||
|
||||
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_comma, ATOM_builtin, ATOM_A, ATOM_V, ATOM_self;
|
||||
|
||||
functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
|
||||
FUNCTOR_bin1, FUNCTOR_brackets1, FUNCTOR_comma2, FUNCTOR_dir1,
|
||||
@ -12,21 +10,16 @@ functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
|
||||
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_equal2, FUNCTOR_sqbrackets2, FUNCTOR_dot2;
|
||||
FUNCTOR_colon2, FUNCTOR_comma2, FUNCTOR_equal2, FUNCTOR_sqbrackets2,
|
||||
FUNCTOR_dot2, FUNCTOR_brackets1;
|
||||
|
||||
PyObject *py_Main;
|
||||
PyObject *py_Builtin;
|
||||
PyObject *py_Yapex;
|
||||
PyObject *term_to_python(term_t t, bool eval);
|
||||
foreign_t python_to_ptr(PyObject *pVal, term_t t);
|
||||
X_API PyObject *py_Builtin;
|
||||
X_API PyObject *py_Yapex;
|
||||
X_API PyObject *py_Sys;
|
||||
PyObject *py_Context;
|
||||
PyObject *py_ModDict;
|
||||
|
||||
PyObject *py_F2P;
|
||||
PyObject *term_to_python(term_t t, bool eval);
|
||||
|
||||
int assign_python(PyObject *root, term_t t, PyObject *e);
|
||||
|
||||
PyObject *ActiveModules[32];
|
||||
int active_modules = 0;
|
||||
X_API PyObject *py_F2P;
|
||||
|
||||
bool python_in_python;
|
||||
|
||||
@ -54,6 +47,7 @@ static void install_py_constants(void) {
|
||||
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);
|
||||
@ -74,43 +68,68 @@ static void install_py_constants(void) {
|
||||
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);
|
||||
// if (python_in_python) {
|
||||
py_Main = PyImport_AddModule("__main__");
|
||||
Py_INCREF(py_Main);
|
||||
py_Sys = PyImport_AddModule("sys");
|
||||
Py_INCREF(py_Sys);
|
||||
py_Builtin = PyImport_AddModule("__builtin__");
|
||||
py_Yapex = PyImport_AddModule("yapex");
|
||||
Py_INCREF(py_Builtin);
|
||||
py_ModDict = PyObject_GetAttrString(py_Sys, "modules");
|
||||
py_Yapex = PyImport_ImportModule("yapex");
|
||||
PyObject *py_Yap = PyImport_ImportModule("yap");
|
||||
Py_INCREF(py_Yapex);
|
||||
//py_F2P = PyObject_GetAttrString(py_Yap, "globals");
|
||||
py_F2P = NULL;
|
||||
}
|
||||
|
||||
foreign_t end_python(void) {
|
||||
Py_Finalize();
|
||||
|
||||
return TRUE;
|
||||
return true;
|
||||
}
|
||||
|
||||
X_API bool init_python(void) {
|
||||
char **argv;
|
||||
python_in_python = false;
|
||||
if (YAP_DelayInit(init_python, "python")) {
|
||||
// wait for YAP_Init
|
||||
return false;
|
||||
}
|
||||
static bool libpython_initialized = 0;
|
||||
|
||||
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 (!Py_IsInitialized()) {
|
||||
python_in_python = true;
|
||||
YAP_Argv(&argv);
|
||||
if (argv) {
|
||||
#if PY_MAJOR_VERSION < 3
|
||||
Py_SetProgramName(argv[0]);
|
||||
#else
|
||||
wchar_t *buf = Py_DecodeLocale(argv[0], NULL);
|
||||
Py_SetProgramName(buf);
|
||||
#endif
|
||||
}
|
||||
Py_Initialize();
|
||||
}
|
||||
Py_Initialize();
|
||||
install_py_constants();
|
||||
PL_reset_term_refs(t);
|
||||
install_pypreds();
|
||||
install_pl2pl();
|
||||
// PyGILState_Release(gstate);
|
||||
return !python_in_python;
|
||||
|
||||
}
|
||||
X_API bool init_python(void) {
|
||||
|
||||
return do_init_python();
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
int WINAPI win_python(HANDLE, DWORD, LPVOID);
|
||||
|
||||
int WINAPI win_python(HANDLE hinst, DWORD reason, LPVOID reserved) {
|
||||
switch (reason) {
|
||||
case DLL_PROCESS_ATTACH:
|
||||
break;
|
||||
case DLL_PROCESS_DETACH:
|
||||
break;
|
||||
case DLL_THREAD_ATTACH:
|
||||
break;
|
||||
case DLL_THREAD_DETACH:
|
||||
break;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
|
@ -1,13 +1,3 @@
|
||||
#ifdef _XOPEN_SOURCE
|
||||
#undef _XOPEN_SOURCE // python does its own thing
|
||||
#endif
|
||||
#include <Python.h>
|
||||
#include <SWI-Prolog.h>
|
||||
#ifdef HAVE_STAT
|
||||
#undef HAVE_STATa
|
||||
#endif
|
||||
#include <assert.h>
|
||||
#define EXTRA_MESSSAGES 1
|
||||
|
||||
//@{
|
||||
|
||||
@ -18,6 +8,43 @@
|
||||
* for related work.
|
||||
*/
|
||||
|
||||
#ifdef _XOPEN_SOURCE
|
||||
#undef _XOPEN_SOURCE // python does its own thing
|
||||
#endif
|
||||
|
||||
#include <Python.h>
|
||||
#include <SWI-Prolog.h>
|
||||
#ifdef HAVE_STAT
|
||||
#undef HAVE_STATa
|
||||
#endif
|
||||
#include <assert.h>
|
||||
#include <string.h>
|
||||
#define EXTRA_MESSSAGES 1
|
||||
|
||||
#ifndef PYTHON_H
|
||||
#define PYTHON_H 1
|
||||
|
||||
PyObject *find_obj(PyObject *ob, term_t lhs, bool eval);
|
||||
|
||||
#if DEBUG_MEMORY
|
||||
#define DebugPrintf(s, op) fprintf(stderr, "%s:%d: " s, __FILE__, __LINE__, op)
|
||||
#else
|
||||
#define DebugPrintf(s, op)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief A module is store as an objet plus a list of paths.
|
||||
*/
|
||||
#define PY_MAX_MODLEN 16
|
||||
typedef struct s_mod_t {
|
||||
PyObject *mod;
|
||||
int length;
|
||||
YAP_Term names[PY_MAX_MODLEN];
|
||||
} Py_mod;
|
||||
|
||||
extern X_API YAP_Term pythonToYAP(PyObject *pVal);
|
||||
extern X_API PyObject *yap_to_python(YAP_Term t, bool eval, PyObject *o);
|
||||
|
||||
typedef YAP_Arity arity_t;
|
||||
|
||||
extern atom_t ATOM_true, ATOM_false, ATOM_colon, ATOM_dot, ATOM_none, ATOM_t,
|
||||
@ -32,14 +59,20 @@ extern functor_t FUNCTOR_dollar1, FUNCTOR_abs1, FUNCTOR_all1, FUNCTOR_any1,
|
||||
FUNCTOR_colon2, FUNCTOR_comma2, FUNCTOR_equal2, FUNCTOR_sqbrackets2,
|
||||
FUNCTOR_dot2;
|
||||
|
||||
extern PyObject *py_Main;
|
||||
extern PyObject *py_Builtin;
|
||||
extern PyObject *py_Yapex;
|
||||
extern X_API PyObject *py_Main;
|
||||
extern X_API PyObject *py_Builtin;
|
||||
extern X_API PyObject *py_Yapex;
|
||||
extern X_API PyObject *py_Local;
|
||||
extern X_API PyObject *py_Global;
|
||||
extern X_API PyObject *py_Context;
|
||||
extern PyObject *py_F2P;
|
||||
extern PyObject *py_Sys;
|
||||
extern PyObject *py_ModDict;
|
||||
|
||||
extern bool python_in_python;
|
||||
|
||||
#define PythonReturn PyGILState_Release(gstate) && return
|
||||
extern bool python_release_GIL(term_t state);
|
||||
extern term_t python_acquire_GIL(void);
|
||||
|
||||
static inline Py_ssize_t get_p_int(PyObject *o, Py_ssize_t def) {
|
||||
if (o == NULL)
|
||||
@ -77,7 +110,7 @@ static inline int proper_ascii_string(const char *s) {
|
||||
static inline PyObject *atom_to_python_string(term_t t) {
|
||||
// Yap_DebugPlWrite(YAP_GetFromSlot(t)); fprintf(stderr, " here I
|
||||
// am\n");
|
||||
char *s;
|
||||
char *s = NULL;
|
||||
if (!PL_get_atom_chars(t, &s))
|
||||
return NULL;
|
||||
/* return __main__,s */
|
||||
@ -93,28 +126,68 @@ static inline PyObject *atom_to_python_string(term_t t) {
|
||||
}
|
||||
}
|
||||
|
||||
#define CHECK_CALL(rc, t, call) \
|
||||
PyErr_Clear();\
|
||||
rc = call; \
|
||||
if (rc == NULL || PyErr_Occurred()) {\
|
||||
YE(t,__LINE__,__FILE__,__FUNCTION__);\
|
||||
PyErr_Print(); PyErr_Clear();\
|
||||
}
|
||||
|
||||
#define CHECKNULL(t,rc) (rc != NULL ? rc : YE(t,__LINE__,__FILE__,__FUNCTION__) )
|
||||
#define AOK(rc, err) { if (!rc) YEM( #rc ,__LINE__,__FILE__,__FUNCTION__); }
|
||||
|
||||
|
||||
extern PyObject *YE(term_t t, int line, const char *file, const char *code);
|
||||
extern void YEM( const char *ex, int line, const char *file, const char *code);
|
||||
extern void pyErrorHandler__(int line, const char *file, const char *code);
|
||||
|
||||
#define pyErrorHandler() \
|
||||
{ \
|
||||
if (PyErr_Occurred()) { \
|
||||
pyErrorHandler__(__LINE__, __FILE__, __FUNCTION__); \
|
||||
} \
|
||||
}
|
||||
|
||||
#define pyErrorAndReturn(x, y) \
|
||||
{ \
|
||||
if (PyErr_Occurred()) { \
|
||||
pyErrorHandler__(__LINE__, __FILE__, __FUNCTION__); \
|
||||
return (x); \
|
||||
} else { \
|
||||
return (x); \
|
||||
} \
|
||||
}
|
||||
// #define pyErrorAndReturn( x, y ) return x
|
||||
|
||||
extern PyObject *compound_to_pyeval(term_t t, PyObject *context);
|
||||
extern PyObject *compound_to_pytree(term_t t, PyObject *context);
|
||||
|
||||
extern PyObject *term_to_python(term_t t, bool eval, PyObject *contextxs);
|
||||
|
||||
extern PyObject *term_to_nametuple(const char *s, int arity, term_t t);
|
||||
|
||||
extern PyObject *compound_to_pyeval(term_t t, functor_t fun);
|
||||
extern PyObject *compound_to_pytree(term_t t, functor_t fun);
|
||||
extern foreign_t python_to_term(PyObject *pVal, term_t t);
|
||||
extern bool python_assign(term_t t, PyObject *exp, PyObject *context);
|
||||
extern foreign_t assign_to_symbol(term_t t, PyObject *e);
|
||||
|
||||
extern PyObject *yap_to_python(YAP_Term t, bool eval);
|
||||
extern PyObject *term_to_python(term_t t, bool eval);
|
||||
extern foreign_t python_to_ptr(PyObject *pVal, term_t t);
|
||||
|
||||
foreign_t python_to_term(PyObject *pVal, term_t t);
|
||||
foreign_t assign_to_symbol(term_t t, PyObject *e);
|
||||
|
||||
int assign_python(PyObject *root, term_t t, PyObject *e);
|
||||
extern bool python_asign(term_t t, PyObject *exp, PyObject *context);
|
||||
|
||||
extern foreign_t python_builtin(term_t out);
|
||||
|
||||
extern PyObject *ActiveModules[32];
|
||||
extern int active_modules;
|
||||
extern int lookupPyModule(Py_mod *q);
|
||||
extern PyObject *lookupPySymbol(const char *s, PyObject *q, PyObject **d);
|
||||
|
||||
extern install_t install_pypreds(void);
|
||||
extern install_t install_pl2pl(void);
|
||||
|
||||
extern bool init_python(void);
|
||||
X_API extern bool init_python(void);
|
||||
extern bool do_init_python(void);
|
||||
|
||||
extern PyObject PyInit_yap(void);
|
||||
|
||||
extern PyObject *PythonLookup(const char *s, PyObject *o);
|
||||
|
||||
extern PyObject *PythonLookupSpecial(const char *s);
|
||||
|
||||
#endif
|
||||
|
@ -1,4 +1,4 @@
|
||||
% % % -* - Mode : Prolog; -*-
|
||||
% % % -*-Mode : Prolog; -*-
|
||||
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
||||
% Author: Vitor Santos Costa
|
||||
% E-mail: vsc@dcc.fc.up.pt
|
||||
@ -29,6 +29,8 @@
|
||||
python/2,
|
||||
acquire_GIL/0,
|
||||
release_GIL/0,
|
||||
python_threaded/0,
|
||||
prolog_list_to_python_list/3,
|
||||
(:=)/2,
|
||||
(:=)/1,
|
||||
% (<-)/2,
|
||||
@ -106,6 +108,7 @@ Data types are
|
||||
|
||||
*************************************************************************************************************/
|
||||
|
||||
|
||||
:- use_module(library(shlib)).
|
||||
:- use_module(library(lists)).
|
||||
:- use_module(library(apply_macros)).
|
||||
@ -116,277 +119,30 @@ Data types are
|
||||
:= P1,
|
||||
:= P2.
|
||||
:= import( F ) :- !, python_import(F).
|
||||
:= F :- python(F,_).
|
||||
:= F :- python_proc(F).
|
||||
|
||||
V := F :- var(V), !, python(F,V0),
|
||||
python_exports(V0,V).
|
||||
A := F :-
|
||||
python_eval_term(F, EF),
|
||||
assign(A, EF, _).
|
||||
|
||||
( V <- F ) :-
|
||||
var(V), !,
|
||||
V0 := F,
|
||||
python_exports(V0,V).
|
||||
( V <- F ) :-
|
||||
ground(V), !,
|
||||
V <- F :-
|
||||
V := F.
|
||||
( V <- F ) :-
|
||||
copy_term(V, V0),
|
||||
V0 := F,
|
||||
python_exports(V0,V).
|
||||
|
||||
python_exports(V0, V0) :-
|
||||
var(V0), !.
|
||||
python_exports(V0, V0) :-
|
||||
atomic(V0), !.
|
||||
python_exports('__obj__'(T0), T) :-
|
||||
!,
|
||||
python_export('__obj__'(T0), T).
|
||||
python_exports(V0, VF) :-
|
||||
V0 =.. [F|L],
|
||||
maplist(python_exports, L, LF),
|
||||
VF =.. [F|LF].
|
||||
( V := F ) :-
|
||||
python_assign(F, V).
|
||||
|
||||
((<- F)) :-
|
||||
python( F, _).
|
||||
:= F.
|
||||
|
||||
python_import(Module) :-
|
||||
python_do_import(Module, _).
|
||||
|
||||
python_do_import(Module, MRef) :-
|
||||
python_mref_cache(Module, MRef), !.
|
||||
python_do_import(Module, MRef) :-
|
||||
python_import(Module, MRef),
|
||||
assert( python_mref_cache(Module, MRef) ).
|
||||
|
||||
fetch_module(M:E, _M1, E, MRef) :-
|
||||
atom(M),
|
||||
python_import(M, MRef).
|
||||
|
||||
% from an exp take an object, and its corresponding Prolog representation
|
||||
descend_exp(V, _Obj) :-
|
||||
var(V), !,
|
||||
throw(error(instantiation_error,_)).
|
||||
descend_exp(Mod.Exp, Obj) :-
|
||||
atom(Mod),
|
||||
python_import(Mod, MObj),
|
||||
!,
|
||||
descend_exp(MObj.Exp, Obj).
|
||||
descend_exp(C1.C2.E, Obj) :- !,
|
||||
python_eval_term(C1, O1),
|
||||
python_field(O1, C2, Obj0 ),
|
||||
descend_exp(Obj0.E, Obj).
|
||||
descend_exp(C1.E, Obj) :-
|
||||
!,
|
||||
python_eval_term(C1, O1),
|
||||
python_field(O1, E, Obj0 ),
|
||||
python_check_args(E, NE, Dict),
|
||||
python_apply(Obj0, NE, Dict, Obj).
|
||||
descend_exp(C, O) :-
|
||||
python_is(C, O).
|
||||
|
||||
python_class(Obj) :-
|
||||
python_obj_cache(inspect:isclass(_), F),
|
||||
python_apply(F, isclass(Obj), {}, true).
|
||||
|
||||
process_obj(Obj, _, S, Obj, NS, Dict) :-
|
||||
python_callable(Obj), !,
|
||||
python_check_args(S, NS, Dict).
|
||||
process_obj(Obj, _, S, FObj, NS, Dict) :-
|
||||
descend_object(Obj.'__init__', FObj, _, _),
|
||||
descend_object(Obj.'__init__', FObj, _, _),
|
||||
python_check_args(S, NS, Dict).
|
||||
|
||||
%% @pred python_eval_term( + Obj, -Obj) is semi-det
|
||||
% It implements the Python interprter's evaluation loop.
|
||||
%
|
||||
python_eval_term(Obj, Obj) :-
|
||||
var(Obj), !,
|
||||
throw(error(instantiation_error, Obj) ).
|
||||
%% atom use basic evaluation of an atom
|
||||
%% check if a variable.
|
||||
python_eval_term(Name, Obj) :-
|
||||
atom(Name),
|
||||
!,
|
||||
python_is(Name, Obj).
|
||||
%% numbers are evaluated
|
||||
python_eval_term(N, N) :- number(N), !.
|
||||
python_eval_term(N, N) :- string(N), !.
|
||||
%% we assume objects are so yoo.
|
||||
python_eval_term('__obj__'(Obj), '__obj__'(Obj)) :- !.
|
||||
%% constant functions are useful.
|
||||
python_eval_term('()'(X), NX) :- !,
|
||||
python_eval_term(X, NX).
|
||||
%% $ -> compatibilty with older versions
|
||||
python_eval_term($Name, Obj) :- !,
|
||||
python_is(Name, Obj).
|
||||
%% lists are collections of individuals
|
||||
%% that may need futrher processing
|
||||
python_eval_term([H|T], NL) :-
|
||||
is_list(T), !,
|
||||
maplist( python_eval_term, [H|T], NL).
|
||||
%% array access, Python understands numeric
|
||||
% indices and slices.
|
||||
python_eval_term(Exp[Min:Max:Step], NEl) :- !,
|
||||
python_eval_term(slice(Min,Max,Step), Slice),
|
||||
python_slice(Exp,Slice, NEl).
|
||||
python_eval_term(Exp[Min:Max], NEl) :- !,
|
||||
python_eval_term(slice(Min,Max), Slice),
|
||||
python_slide(Exp,Min,Max, NEl).
|
||||
python_eval_term(Exp[Index], O) :- !,
|
||||
python_item(Exp,Index,O).
|
||||
% function or method call of the form
|
||||
% a.b.f(...)
|
||||
python_eval_term(Inp.Exp, Obj) :- !,
|
||||
%flatten_exp(Exp, Exp1, []),
|
||||
descend_exp(Inp.Exp, Obj).
|
||||
python_eval_term((A,B), Obj) :- !,
|
||||
flatten_conj((A,B),Cs,[]),
|
||||
maplist( python_eval_term, Cs, NCs),
|
||||
Tuple =.. [t|NCs],
|
||||
python_is(Tuple, Obj).
|
||||
% tuples and varyadic functions.
|
||||
python_eval_term(Tuple, Obj) :-
|
||||
Tuple =.. [Name|TupleL],
|
||||
maplist( python_eval_term, TupleL, NewTupleL),
|
||||
(
|
||||
Name == t
|
||||
->
|
||||
!,
|
||||
NewTuple =.. [t|NewTupleL],
|
||||
python_is(NewTuple, Obj)
|
||||
;
|
||||
Name == open ->
|
||||
!,
|
||||
% calls the file constructor
|
||||
NewTuple =.. [open|NewTupleL],
|
||||
python_builtin_eval( NewTuple, [], Obj )
|
||||
).
|
||||
python_eval_term(Exp, Obj) :-
|
||||
python_is(Exp, Obj).
|
||||
|
||||
flatten_exp( V , V, V0) :-
|
||||
V0 == [],
|
||||
var( V ),
|
||||
!.
|
||||
flatten_exp( V1 ) -->
|
||||
{ var( V1 ) },
|
||||
!,
|
||||
[V1].
|
||||
flatten_exp( (V1.V2) ) -->
|
||||
!,
|
||||
flatten_exp( V1 ), % propagte the RHS first.
|
||||
flatten_exp( V2 ).
|
||||
flatten_exp( V1() ) -->
|
||||
!,
|
||||
flatten_exp( V1 ).
|
||||
flatten_exp( V1, V1, V0 ) :- V0 == [], !.
|
||||
flatten_exp( V1 ) -->
|
||||
[V1].
|
||||
|
||||
flatten_conj( V1 ) -->
|
||||
{ var( V1 ) },
|
||||
!,
|
||||
[V1].
|
||||
flatten_conj( (V1,V2) ) -->
|
||||
!,
|
||||
flatten_conj( V1 ), % propagte the RHS first.
|
||||
flatten_conj( V2 ).
|
||||
flatten_conj( V1 ) -->
|
||||
[V1].
|
||||
|
||||
python_check_args(_Exp(), t, {}) :-
|
||||
!.
|
||||
python_check_args(Exp, t, {}) :-
|
||||
Exp =.. [_,V], var(V), !.
|
||||
python_check_args(Exp, NExp, Dict) :-
|
||||
Exp =.. [_F|LArgs], !,
|
||||
match_args(LArgs, NLArgs, Dict),
|
||||
NExp =.. [t|NLArgs].
|
||||
python_check_args(Exp, Exp, {}).
|
||||
|
||||
python_build_tuple(V) -->
|
||||
{var(V) }, !,
|
||||
[V].
|
||||
python_build_tuple((X,Y)) --> !,
|
||||
python_build_tuple(X),
|
||||
python_build_tuple(Y).
|
||||
python_build_tuple(X) --> [X].
|
||||
|
||||
% in case it is __init__ from __new__
|
||||
splice_class(Ref, Ref, ArgNames, ArgNames) :- !.
|
||||
splice_class(_FRef, _Ref, [_|ArgNames], ArgNames).
|
||||
|
||||
match_args([], [], {}).
|
||||
match_args([V=A|LArgs], [], Dict) :- !,
|
||||
python_eval_term(A, EvA),
|
||||
match_named_args([V=EvA|LArgs], Map),
|
||||
map_to_dict(Map, Dict).
|
||||
match_args([A|LArgs], [VA|NLArgs], Dict) :-
|
||||
python_eval_term(A, VA),
|
||||
match_args(LArgs, NLArgs, Dict).
|
||||
|
||||
match_named_args([], []).
|
||||
match_named_args([K=A|LArgs], [K=A|Map]) :-
|
||||
match_named_args(LArgs, Map).
|
||||
python_import(Module, _).
|
||||
|
||||
|
||||
map_to_dict([X=V], {X:V}) :- !.
|
||||
map_to_dict([X=V|Map], {X:V,NDict}) :-
|
||||
map_to_dict(Map, {NDict}).
|
||||
|
||||
match_from_anames([K|_ArgNames], K, VA, [_|Defaults], [VA|Defaults]) :- !.
|
||||
match_from_anames([_|ArgNames], K, VA, [V|Defaults], [V|NDefaults]) :-
|
||||
match_from_anames(ArgNames, K, VA, Defaults, NDefaults).
|
||||
|
||||
fetch_args(FRef, Args, Kwd, Defaults) :-
|
||||
FRef = '__obj__'(_), !,
|
||||
%python_mref_cache('inspect', M),
|
||||
python_obj_cache(inspect:getargspec(_), F),
|
||||
python_apply(F, getargspec(FRef), {}, ExtraArgs),
|
||||
ExtraArgs=t(Args, _, Kwd, Defaults).
|
||||
fetch_args(_, []).
|
||||
|
||||
|
||||
python(Obj, Out) :-
|
||||
python_eval_term(Obj, Out).
|
||||
python(Exp, Out) :-
|
||||
Out := Exp.
|
||||
|
||||
python_command(Cmd) :-
|
||||
python_run_command(Cmd).
|
||||
|
||||
python_lhs(Obj,Obj) :-
|
||||
var(Obj), !.
|
||||
python_lhs(Name,Name) :-
|
||||
atom(Name), !.
|
||||
python_lhs(N, N) :-
|
||||
number(N), !,
|
||||
throw(error(type(evaluable, N)), "in left-hand-side of s").
|
||||
python_lhs(N,N) :-
|
||||
string(N), !,
|
||||
throw(error(type(evaluable, N)), "in left-hand-side of s").
|
||||
python_lhs('__obj__'(Obj), '__obj__'(Obj)) :- !.
|
||||
python_lhs($Name, Name) :-
|
||||
!.
|
||||
python_lhs([H|T], NL) :-
|
||||
is_list(T), !,
|
||||
maplist( python_lhs, [H|T], NL).
|
||||
python_lhs((Exp1,Exp2), O) :- !,
|
||||
python_build_tuple((Exp1,Exp2), TupleL, []),
|
||||
Tuple =.. [t|TupleL], % <<<
|
||||
python_lhs( Tuple, O).
|
||||
python_lhs(F, F).
|
||||
|
||||
start_python :-
|
||||
python_main_module(MRef),
|
||||
assert(python_mref_cache('__main__', MRef)),
|
||||
python_command('import sys'),
|
||||
python_import('inspect'),
|
||||
python_mref_cache(inspect, InspRef),
|
||||
python_field(InspRef, isclass(_), IsClass),
|
||||
assert(python_obj_cache(inspect:isclass(_), IsClass)),
|
||||
python_field(InspRef, getargspec(_), GetArgSpec),
|
||||
assert(python_obj_cache(inspect:getargspec(_), GetArgSpec)),
|
||||
python_import('inspect', _),
|
||||
at_halt(end_python).
|
||||
|
||||
add_cwd_to_python :-
|
||||
@ -396,41 +152,6 @@ add_cwd_to_python :-
|
||||
python_command("sys.argv = [\"yap\"]").
|
||||
% done
|
||||
|
||||
assign( V, E, O ) :-
|
||||
var(V),
|
||||
!,
|
||||
E = V,
|
||||
O = V.
|
||||
assign( EName, E, EName ) :-
|
||||
\+ atomic(EName),
|
||||
python_assign_tuple(EName, E),
|
||||
!.
|
||||
assign(Name, Exp, Name) :-
|
||||
python_assign(Name, Exp).
|
||||
|
||||
% from an exp take an object, and its corresponding Prolog representation
|
||||
python_assign_field(V, _Obj) :-
|
||||
var(V), !,
|
||||
throw(error(instantiation_error,_)).
|
||||
python_assign_field(Mod.Exp, Obj) :-
|
||||
atom(Mod),
|
||||
python_import(Mod, MObj),
|
||||
!,
|
||||
python_assign_field(MObj.Exp, Obj).
|
||||
python_assign_field(C1.C2.E, Obj) :- !,
|
||||
python_eval_term(C1, O1),
|
||||
python_field(O1, C2, Obj0 ),
|
||||
python_assign_field(Obj0.E, Obj).
|
||||
python_assign_field(Exp, Obj) :-
|
||||
fail,
|
||||
python_mref_cache(_, MObj),
|
||||
python_field(MObj, Exp, Obj), !.
|
||||
python_assign_field(C1.E, Obj) :-
|
||||
atom(E),
|
||||
!,
|
||||
python_eval_term(C1, O1),
|
||||
python_assign_field(O1, E, Obj ).
|
||||
|
||||
%:- initialization( load_foreign_files([libYAPPython], [], init_python), now ).
|
||||
:- initialization( load_foreign_files([libYAPPython], [], init_python), now ).
|
||||
|
||||
:- initialization( load_foreign_library(foreign(libYAPPython), init_python), now ).
|
||||
|
@ -8,8 +8,10 @@ add_custom_target ( YAPKernel ALL
|
||||
DEPENDS yap_kernel.py
|
||||
)
|
||||
|
||||
set( PYTHON_INSTALL install)
|
||||
|
||||
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} install -f
|
||||
|
||||
install(CODE "execute_process(COMMAND ${PYTHON_EXECUTABLE} ${SETUP_PY} ${PYTHON_INSTALL} -f
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})")
|
||||
|
||||
install(FILES jupyter.yap
|
||||
|
@ -1,30 +0,0 @@
|
||||
"""
|
||||
Paired Density and Scatterplot Matrix
|
||||
=====================================
|
||||
|
||||
_thumb: .5, .5
|
||||
"""
|
||||
import seaborn as sns
|
||||
import matplotlib.pyplot as plt
|
||||
sns.set(style="white")
|
||||
|
||||
df = sns.load_dataset("iris")
|
||||
|
||||
g = sns.PairGrid(df, diag_sharey=False)
|
||||
g.map_lower(sns.kdeplot, cmap="Blues_d")
|
||||
g.map_upper(plt.scatter)
|
||||
g.map_diag(sns.kdeplot, lw=3)
|
||||
|
||||
"""
|
||||
Grouped barplots
|
||||
================
|
||||
|
||||
_thumb: .45, .5
|
||||
"""
|
||||
sns.set(style="whitegrid")
|
||||
|
||||
# Draw a nested barplot to show survival for class and sex
|
||||
g = sns.factorplot(x="class", y="survived", hue="sex", data=[15,30,5],
|
||||
size=3, kind="bar", palette="muted")
|
||||
g.despine(left=True)
|
||||
g.set_ylabels("survival probability")
|
@ -161,24 +161,21 @@ class YAPInteractiveShell:
|
||||
# print('{0}'.format(f.getvalue()))
|
||||
# Execute the user code
|
||||
if run:
|
||||
# this new vs should contain bindings to vars
|
||||
vs= self.q.namedVars()
|
||||
#numbervars
|
||||
i=0
|
||||
# iteraw
|
||||
for eq in vs:
|
||||
name = eq[0]
|
||||
# this is tricky, we're going to bind the variables in the term so thay we can
|
||||
# output X=Y. The Python way is to use dictionares.
|
||||
#Instead, we use the T function to tranform the Python term back to Prolog
|
||||
binding = yap.T(eq[1])
|
||||
if binding.isVar():
|
||||
binding.unify(name)
|
||||
else:
|
||||
i = binding.numberVars(i, True)
|
||||
print(name + " = " + binding.text())
|
||||
#ok, that was Prolog code
|
||||
print("yes")
|
||||
myvs = self.q.namedVarsCopy()
|
||||
if myvs:
|
||||
i = 0
|
||||
for peq in myvs:
|
||||
name = peq[0]
|
||||
bind = peq[1]
|
||||
if bind.isVar():
|
||||
var = yap.YAPAtom('$VAR')
|
||||
f = yap.YAPFunctor(var, 1)
|
||||
bind.unify(yap.YAPApplTerm(f, (name)))
|
||||
else:
|
||||
i = bind.numberVars(i, True)
|
||||
print(name.text() + " = " + bind.text())
|
||||
else:
|
||||
print("yes")
|
||||
if self.q.deterministic():
|
||||
self.closeq()
|
||||
else:
|
||||
|
@ -138,9 +138,9 @@ class YAPKernel(KernelBase):
|
||||
implementation = 'YAP'
|
||||
implementation_version = release.version
|
||||
language_info = {
|
||||
'name': 'prolog',
|
||||
'name': 'python',
|
||||
'version': sys.version.split()[0],
|
||||
'mimetype': 'text/x-prolog',
|
||||
'mimetype': 'text/x-python',
|
||||
'codemirror_mode': {
|
||||
'name': 'prolog',
|
||||
'version': sys.version_info[0]
|
||||
@ -333,7 +333,7 @@ class YAPKernel(KernelBase):
|
||||
|
||||
elif hist_access_type == 'range':
|
||||
hist = self.shell.history_manager.get_range(session, start, stop,
|
||||
raw=raw, output=output)
|
||||
raw=raw, output=output)
|
||||
|
||||
elif hist_access_type == 'search':
|
||||
hist = self.shell.history_manager.search(
|
||||
|
@ -1,7 +1,8 @@
|
||||
|
||||
import yap
|
||||
import sys
|
||||
import collections
|
||||
# debugging support.
|
||||
import pdb
|
||||
|
||||
def query_prolog(engine, s):
|
||||
|
||||
@ -12,13 +13,14 @@ def query_prolog(engine, s):
|
||||
print(e.args[1])
|
||||
return False
|
||||
|
||||
#
|
||||
#construct a query from a one-line string
|
||||
# q is opaque to Python
|
||||
q = engine.query(s)
|
||||
# vs is the list of variables
|
||||
# you can print it out, the left-side is the variable name,
|
||||
# the right side wraps a handle to a variable
|
||||
vs= q.namedVars()
|
||||
vs = q.namedVars()
|
||||
# atom match either symbols, or if no symbol exists, sttrings, In this case
|
||||
# variable names should match strings
|
||||
for eq in vs:
|
||||
@ -56,7 +58,10 @@ def query_prolog(engine, s):
|
||||
if s.startswith(';') or s.startswith('y'):
|
||||
continue
|
||||
elif s.startswith('#'):
|
||||
exec(s.lstrip('#'))
|
||||
try:
|
||||
exec(s.lstrip('#'))
|
||||
except:
|
||||
raise
|
||||
elif s.startswith('*') or s.startswith('a'):
|
||||
ask = False
|
||||
continue
|
||||
@ -70,6 +75,7 @@ def query_prolog(engine, s):
|
||||
def live():
|
||||
engine = yap.YAPEngine()
|
||||
loop = True
|
||||
pdb.set_trace()
|
||||
while loop:
|
||||
try:
|
||||
s = input("?- ")
|
||||
@ -92,4 +98,4 @@ def live():
|
||||
# initialize engine
|
||||
# engine = yap.YAPEngine();
|
||||
# engine = yap.YAPEngine(yap.YAPParams());
|
||||
live()
|
||||
#live()
|
||||
|
Reference in New Issue
Block a user