update to newer version

This commit is contained in:
Vitor Santos Costa 2012-10-08 18:27:05 +01:00
parent b0ddda1fde
commit c4da6a9c68
14 changed files with 338 additions and 469 deletions

View File

@ -1,340 +1,7 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (c) 2007-2012 Yüce Tekol
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Preamble
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,58 +1,58 @@
PySWIP INSTALL
==============
PySWIP requires SWI-Prolog as a shared library since it uses ctypes to access SWI-Prolog/C functions. The shared library is present in Win32 installer, but missing by default from the builds made directly from the source.
PySWIP requires SWI-Prolog as a shared library since it uses ctypes to access SWI-Prolog/C functions. The shared library is present in the Win32 installer, but missing by default from the builds made directly from the source.
Installing on Linux
-------------------
These instructions are tested on a Linux system, but should also work for POSIX systems. Also, you may want to install development packages for readline and libgmp (not required for basics).
These instructions are tested on a Linux system, but should also work for POSIX systems. Also, you may want to install development packages for readline, libncurses, and libgmp.
You need to do the following to install a shared library enabled version of SWI-Prolog. We use version 5.6.34 of SWI-Prolog but any other recent version should work fine. Please make the necessary modifications for your environment.
You need to do the following to install a shared library enabled version of SWI-Prolog. We use version 6.0.2 of SWI-Prolog. Please make the necessary modifications for your environment.
1) Get the source from: http://www.swi-prolog.org/download.html::
1) Get the source from http://www.swi-prolog.org/download/stable:
$ wget http://gollem.science.uva.nl/cgi-bin/nph-download/SWI-Prolog/pl-5.6.34.tar.gz
$ wget http://www.swi-prolog.org/download/stable/src/pl-6.0.2.tar.gz
2) Extract the archive and cd into it::
2) Extract the archive and cd into it:
$ tar xzvf pl-5.6.34.tar.gz
$ cd pl-5.6.34
$ tar xzvf pl-6.0.2.tar.gz
$ cd pl-6.0.2.tar.gz
3) Configure the source with shared library enabled::
3) Configure the source with shared library enabled:
$ ./configure --prefix=/usr --enable-shared
$ ./configure --enable-shared
4) Compile the source::
*** If using a 64-bit system, you may have to compile with the -ggdb flag in order to get PySWIP to work with SWI-Prolog without segfaults (But not necessarily. YMMV.):
$ CFLAGS=-ggdb ./configure --enable-shared
4) Compile the source:
$ make
5) Install the source::
5) Install the source:
$ sudo make install
6) clp library is useful for constraint handling problems, so let's install that too::
6) *** This is perhaps no longer relevant, as it appears clp is installed by default with SWI-Prolog
clp library is useful for constraint handling problems, so let's install that too:
$ cd cd packages/clpqr
$ ./configure --prefix=/usr --enable-shared
$ ./configure --enable-shared
$ make && make install
7) If you are not using Python 2.5 or later, you should install ctypes, or get a new version of Python (apt-get is fine if you're using Ubuntu).
7) Create a soft link to ``libpol.so``::
8) Unpack PySwIP package and install it with, ``python setup.py install``.
$ sudo ln -s /usr/lib/pl-5.6.34/lib/i686-linux/libpl.so.5.6.34 /usr/lib/libpl.so
8) Next, get and install ctypes from: http://starship.python.net/crew/theller/ctypes . Note that you don't need to install it if you are using Python 2.5.
9) Unpack PySwIP package and install it with, ``python setup.py install``.
10) After you install it, you can test it with the following at your Python shell::
9) After you install it, you can test it with the following at your Python shell::
>>> from pyswip import Prolog
>>> prolog = Prolog()
>>> prolog.assertz("father(michael,john)")
If you get an error, such as "libpl (shared) not found." or "FATAL ERROR: Resource not found" be sure you have installed SWI-Prolog as a share library. Check your default library directory (usually ``/usr/lib``) for ``libpl.so``.
If you get an error, such as "libpl (shared) not found." or "FATAL ERROR: Resource not found" be sure you have installed SWI-Prolog as a shared library. Check your default library directory (usually ``/usr/lib``) for ``libswipl.so``.
Installing on Win32

View File

@ -5,7 +5,7 @@ PySWIP README
0.2.2
:Author:
Yuce Tekol. <http://www.geocities.com/yucetekol>
Yuce Tekol. <yucetekol@gmail.com>
:Project Website:
http://code.google.com/p/pyswip
@ -14,7 +14,7 @@ PySWIP README
Introduction
------------
PySWIP is a GPL'd Python - SWI-Prolog bridge enabling to query SWI-Prolog in your Python programs. It features an (incomplete) SWI-Prolog foreign language interface, a utility class that makes it easy querying with Prolog and also a Pythonic interface.
PySWIP is a Python - SWI-Prolog bridge enabling to query SWI-Prolog in your Python programs. It features an (incomplete) SWI-Prolog foreign language interface, a utility class that makes it easy querying with Prolog and also a Pythonic interface.
Since PySWIP uses SWI-Prolog as a shared library and ctypes to access it, it doesn't require compilation to be installed.

View File

@ -1,7 +1,7 @@
% Coins -- 2007 by Yuce Tekol <yucetekol@gmail.com>
:- use_module(library('clpfd')).
:- use_module(library(clpfd)).
coins(S, Count, Total) :-
% A=1, B=5, C=10, D=50, E=100

View File

@ -13,6 +13,7 @@ def main():
animal2 = PL_new_functor(PL_new_atom("animal"), 2)
assertz = PL_new_functor(PL_new_atom("assertz"), 1)
PL_put_atom_chars(a1, "gnu")
PL_put_integer(a2, 50)
#PL_cons_functor(t, animal2, a1, a2)

View File

@ -4,7 +4,7 @@
solve(Board) :-
Board = [NW,N,NE,W,E,SW,S,SE],
domains(Board,0..12),
maplist(in_board(0..12), Board),
sum(Board, #=, 12),
NW + N + NE #= 5,
NE + E + SE #= 5,
@ -12,7 +12,4 @@ solve(Board) :-
SW + S + SE #= 5,
label(Board).
domains([],_).
domains([Pos|Board],D) :-
Pos in D,
domains(Board,D).
in_board(D, V) :- V in D.

View File

@ -17,9 +17,7 @@ call(assertz(parent("gina", "bob")), module=test2)
print "knowledgebase test1"
X = Variable()
print "ok"
q = Query(parent(X, "bob"), module=test1)
print "ok"
while q.nextSolution():
print X.value
q.closeQuery()

View File

@ -2,11 +2,11 @@
% SEND + MORE = MONEY
% Adapted from: http://en.wikipedia.org/wiki/Constraint_programming
:- use_module(library(clpfd)).
:- use_module(library('bounds')).
sendmore(Digits) :-
Digits = [S,E,N,D,M,O,R,Y], % Create variables
allin(Digits, 0..9), % Associate domains to variables
Digits in 0..9, % Associate domains to variables
S #\= 0, % Constraint: S must be different from 0
M #\= 0,
all_different(Digits), % all the elements must take different values
@ -15,8 +15,3 @@ sendmore(Digits) :-
#= 10000*M + 1000*O + 100*N + 10*E + Y,
label(Digits). % Start the search
allin([],_).
allin([Pos|Board],D) :-
Pos in D,
allin(Board,D).

View File

@ -8,7 +8,7 @@
sudoku(Pss) :-
flatten(Pss, Ps),
allin(Ps, 1..9),
maplist(all_in(1..9), Ps),
maplist(all_different, Pss),
Pss = [R1,R2,R3,R4,R5,R6,R7,R8,R9],
columns(R1, R2, R3, R4, R5, R6, R7, R8, R9),
@ -25,7 +25,5 @@ blocks([X1,X2,X3|R1], [X4,X5,X6|R2], [X7,X8,X9|R3]) :-
all_different([X1,X2,X3,X4,X5,X6,X7,X8,X9]),
blocks(R1, R2, R3).
allin([],_).
allin([Pos|Board],D) :-
Pos in D,
allin(Board,D).
all_in(D, Pos) :-
Pos in D.

View File

@ -18,7 +18,7 @@
# MA 02110-1301, USA.
# PySWIP version
__VERSION__ = "0.2.2b"
__VERSION__ = "0.2.2"
from pyswip.prolog import Prolog
from pyswip.easy import *

View File

@ -1,7 +1,9 @@
# -*- coding: utf-8 -*-
# pyswip -- Python SWI-Prolog bridge
# (c) 2006-2007 Yüce TEKOL
# (c) 2010-2011 Manuel ROTTER
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
@ -17,35 +19,184 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import sys
try:
import os
import warnings
from subprocess import Popen, PIPE
from ctypes import *
except ImportError:
print>>sys.stderr, "A required module: 'ctypes' not found."
sys.exit(1)
from ctypes.util import find_library
try:
if sys.platform[:3] == "win":
# we're on windows
_lib = CDLL("yap.dll")
elif sys.platform[:3] == "dar":
# we're on Mac OS
_lib = CDLL("libYap.dylib")
else:
# UNIX-like
try:
_lib = CDLL("libYap.so")
except IndexError:
# let's try the cwd
_lib = CDLL("./libYap.so")
def _fixWindowsPath(dll):
"""
When the path to the DLL is not in Windows search path, Windows will not be
able to find other DLLs on the same directory, so we have to add it to the
path. This function takes care of it.
:param dll: File name of the DLL
:type dll: string
"""
if sys.platform[:3] != 'win':
return # Nothing to do here
pathToDll = os.path.dirname(dll)
currentWindowsPath = os.getenv('PATH')
if pathToDll not in currentWindowsPath:
# We will prepend the path, to avoid conflicts between DLLs
newPath = pathToDll + ';' + currentWindowsPath
os.putenv('PATH', newPath)
def _findYap():
"""
This function makes a big effort to find the path to the SWI-Prolog shared
library. Since this is both OS dependent and installation dependent, we may
not aways succeed. If we do, we return a name/path that can be used by
CDLL(). Otherwise we raise an exception.
:return: Name or path to the library that can be used by CDLL
:rtype: String
:raises ImportError: If we cannot guess the name of the library
"""
# No matter what the platform is, the first try should alway be
# find_library.
path = find_library('Yap') # or find_library('swipl') or find_library('pl')
if path is not None:
return path
# Now begins the guesswork
platform = sys.platform[:3]
if platform == 'win': # In Windows, we have the default installer path and
# the registry to look
dllName = 'yap.dll'
# First try: check the usual installation path (this is faster but
# hardcoded)
programFiles = os.getenv('ProgramFiles')
path = os.path.join(programFiles, r'pl\bin', dllName)
if os.path.exists(path):
return path
# Second try: use reg.exe to find the installation path in the registry
# (reg should be installed in all Windows XPs)
try:
cmd = Popen(['reg', 'query',
r'HKEY_LOCAL_MACHINE\Software\SWI\Prolog',
'/v', 'home'], stdout=PIPE)
ret = cmd.communicate()
# Result is like:
# ! REG.EXE VERSION 3.0
#
# HKEY_LOCAL_MACHINE\Software\SWI\Prolog
# home REG_SZ C:\Program Files\pl
# (Note: spaces are \t in the output)
ret = ret[0].splitlines()
ret = [line for line in ret if len(line) > 0]
data = ret[-1].split('\t')
path = data[-1]
path = os.path.join(path, 'bin', dllName)
if os.path.exists(path):
return path
except OSError:
print>>sys.stderr, "libYap (shared) not found. Possible reasons:"
print>>sys.stderr, "1) YAP has not been installed as a shared library, use --with-java)"
print>>sys.stderr, "1) set LD_LIBRARY_PATH=/usr/local/lib or somewhere elser where libYap.so can be found"
sys.exit(1)
# reg.exe not found? Weird...
pass
# Last try: maybe it is in the current dir
if os.path.exists(dllName):
return dllName
elif platform == 'lin':
# In Linux we will try some hardcoded paths. find_library will have
# already done almost all we can
paths = ['/lib', '/usr/lib', '/usr/local/lib', '.', './lib']
name = 'libYap.so' #, 'libswipl.so', 'libpl.so']
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return path
spaths=os.getenv('LD_LIBRARY_DIR')
if (spaths):
paths = spaths.split(':')
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return path
elif platform == "dar": # Help with MacOS is welcome!!
paths = ['.', './lib']
names = ['libYap.dylib'] #, 'libswipl.dylib', 'libpl.dylib']
for name in names:
for path in paths:
path = os.path.join(path, name)
if os.path.exists(path):
return path
# unix in general
path=os.getenv('YAPLIBDIR')
path = os.path.join(path, name)
if os.path.exists(path):
return path
# Last resource: see if executable is on the path
try: # try to get library path from swipl executable.
cmd = Popen(['yap', '-dump-runtime-variables'], stdout=PIPE)
ret = cmd.communicate()
# Parse the output into a dictionary
ret = ret[0].replace(';', '').splitlines()
ret = [line.split('=', 1) for line in ret]
rtvars = dict((name, value[1:-1]) for name, value in ret)
if rtvars['PLSHARED'] == 'yes':
# determine platform specific path
if platform in ("win", "cyg"):
dllName = rtvars['PLLIB'][:-4] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'],
'bin')
else: # assume UNIX-like
dllName = 'lib' + rtvars['PLLIB'][2:] + '.' + rtvars['PLSOEXT']
path = os.path.join(rtvars['PLBASE'],
'lib',
rtvars['PLARCH'])
fullName = os.path.join(path, dllName)
if os.path.exists(fullName):
return fullName
# If it does not exist, search for a name like dllName in path
files = os.listdir(path)
for f in files:
if dllName in f:
fullName = os.path.join(path, f)
return fullName
else: # PLSHARED="no"
raise ImportError('SWI-Prolog is not installed as a shared library.')
except (OSError, KeyError): # KeyError from accessing rtvars
pass
# This is a catch all raise
raise ImportError('Could not find the SWI-Prolog library in this platform. '
'If you are sure it is installed, please open an issue.')
class c_void(Structure):
_fields_ = [('dummy', c_int)]
c_void_p = POINTER(c_void)
# Load the library
path = _findYap()
_fixWindowsPath(path)
_lib = CDLL(path)
# PySWIP constants
PYSWIP_MAXSTR = 1024
@ -178,13 +329,12 @@ functor_t = c_ulong
PL_atomic_t = c_ulong
foreign_t = c_ulong
pl_wchar_t = c_wchar
atom_t_p = c_void_p
##_lib.PL_initialise(len(sys.argv), _argv)
PL_initialise = _lib.PL_initialise
##PL_initialise.argtypes = [c_int, c_c
PL_initialise.argtypes = [c_int, POINTER(c_char_p)]
PL_open_foreign_frame = _lib.PL_open_foreign_frame
PL_open_foreign_frame.restype = fid_t
@ -210,6 +360,9 @@ PL_discard_foreign_frame.argtypes = [fid_t]
PL_put_list_chars = _lib.PL_put_list_chars
PL_put_list_chars.argtypes = [term_t, c_char_p]
#PL_put_list_chars = _lib.PL_put_list_nchars
#PL_put_list_nchars.argtypes = [term_t, c_size_t, c_char_p]
#PL_EXPORT(void) PL_register_atom(atom_t a);
PL_register_atom = _lib.PL_register_atom
PL_register_atom.argtypes = [atom_t]
@ -230,27 +383,32 @@ PL_functor_arity.argtypes = [functor_t]
# /* Get C-values from Prolog terms */
#PL_EXPORT(int) PL_get_atom(term_t t, atom_t *a);
PL_get_atom = _lib.PL_get_atom
PL_get_atom.argtypes = [term_t, atom_t_p]
PL_get_atom.argtypes = [term_t, POINTER(atom_t)]
PL_get_atom_ex = _lib.PL_get_atom_ex
PL_get_atom_ex.argtypes = [term_t, POINTER(atom_t)]
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_atom_nchars = _lib.PL_get_atom_nchars
PL_get_atom_nchars.argtypes = [term_t, POINTER(c_size_t), POINTER(c_char_p)]
#PL_EXPORT(int) PL_get_bool(term_t t, int *value);
PL_get_bool = _lib.PL_get_bool
PL_get_bool.argtypes = [term_t, c_int_p]
#PL_EXPORT(int) PL_get_atom_chars(term_t t, char **a);
PL_get_atom_chars = _lib.PL_get_atom_chars # FIXME
PL_get_atom_chars.argtypes = [term_t, POINTER(c_char_p)]
PL_get_bool.argtypes = [term_t, POINTER(c_int)]
##define PL_get_string_chars(t, s, l) PL_get_string(t,s,l)
# /* PL_get_string() is depricated */
#PL_EXPORT(int) PL_get_string(term_t t, char **s, size_t *len);
PL_get_string = _lib.PL_get_string_chars
PL_get_string.argtypes = [term_t, POINTER(c_char_p), c_int_p]
PL_get_string_chars = PL_get_string
PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_get_string = _lib.PL_get_string
#PL_get_string_chars = PL_get_string_chars
#PL_get_string_chars.argtypes = [term_t, POINTER(c_char_p), c_int_p]
#PL_EXPORT(int) PL_get_chars(term_t t, char **s, unsigned int flags);
PL_get_chars = _lib.PL_get_chars # FIXME:
PL_get_chars = _lib.PL_get_chars
PL_get_chars.argtypes = [term_t, POINTER(c_char_p), c_uint]
#PL_EXPORT(int) PL_get_list_chars(term_t l, char **s,
@ -264,24 +422,28 @@ PL_get_chars.argtypes = [term_t, POINTER(c_char_p), c_uint]
# unsigned int flags);
#PL_EXPORT(int) PL_get_integer(term_t t, int *i);
PL_get_integer = _lib.PL_get_integer
PL_get_integer.argtypes = [term_t, POINTER(c_int)]
PL_get_integer.argtypes = [term_t, c_int_p]
#PL_EXPORT(int) PL_get_long(term_t t, long *i);
PL_get_long = _lib.PL_get_long
PL_get_long.argtypes = [term_t, POINTER(c_long)]
PL_get_long.argtypes = [term_t, c_long_p]
#PL_EXPORT(int) PL_get_pointer(term_t t, void **ptr);
PL_get_pointer = _lib.PL_get_pointer
PL_get_pointer.argtypes = [term_t, POINTER(c_void_p)]
#PL_EXPORT(int) PL_get_float(term_t t, double *f);
PL_get_float = _lib.PL_get_float
PL_get_float.argtypes = [term_t, c_double_p]
#PL_EXPORT(int) PL_get_functor(term_t t, functor_t *f);
PL_get_functor = _lib.PL_get_functor
#PL_get_functor.argtypes = [term_t, c_ulong]
PL_get_functor.argtypes = [term_t, POINTER(functor_t)]
#PL_EXPORT(int) PL_get_name_arity(term_t t, atom_t *name, int *arity);
PL_get_name_arity = _lib.PL_get_name_arity
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), c_int_p]
PL_get_name_arity.argtypes = [term_t, POINTER(atom_t), POINTER(c_int)]
#PL_EXPORT(int) PL_get_module(term_t t, module_t *module);
#PL_EXPORT(int) PL_get_arg(int index, term_t t, term_t a);
@ -292,18 +454,24 @@ PL_get_arg.argtypes = [c_int, term_t, term_t]
#PL_EXPORT(int) PL_get_head(term_t l, term_t h);
PL_get_head = _lib.PL_get_head
PL_get_head.argtypes = [term_t, term_t]
#PL_EXPORT(int) PL_get_tail(term_t l, term_t t);
PL_get_tail = _lib.PL_get_tail
PL_get_tail.argtypes = [term_t, term_t]
#PL_EXPORT(int) PL_get_nil(term_t l);
PL_get_nil = _lib.PL_get_nil
PL_get_nil.argtypes = [term_t]
#PL_EXPORT(int) PL_get_term_value(term_t t, term_value_t *v);
#PL_EXPORT(char *) PL_quote(int chr, const char *data);
PL_put_atom_chars = _lib.PL_put_atom_chars
PL_put_atom_chars.argtypes = [term_t, c_char_p]
PL_put_atom_nchars = _lib.PL_put_atom_nchars
PL_put_atom_nchars.argtypes = [term_t, c_size_t, c_char_p]
PL_atom_chars = _lib.PL_atom_chars
PL_atom_chars.argtypes = [atom_t]
PL_atom_chars.restype = c_char_p
@ -330,9 +498,6 @@ PL_copy_term_ref.restype = term_t
PL_get_list = _lib.PL_get_list
PL_get_list.argtypes = [term_t, term_t, term_t]
PL_get_chars = _lib.PL_get_chars
PL_get_chars.argtypes = [term_t, POINTER(c_char_p), c_uint]
PL_close_query = _lib.PL_close_query
PL_close_query.argtypes = [qid_t]
@ -344,13 +509,13 @@ PL_halt = _lib.PL_halt
PL_halt.argtypes = [c_int]
PL_unify_integer = _lib.PL_unify_integer
PL_unify_integer.argtypes = [term_t,c_long]
PL_unify_integer.argtypes = [term_t,c_int]
PL_unify = _lib.PL_unify
PL_unify.argtypes = [term_t,term_t]
PL_unify_arg = _lib.PL_unify_arg
PL_unify.argtypes = [c_int,term_t,atom_t]
PL_unify_arg.argtypes = [c_int,term_t,term_t]
# Verify types
@ -410,6 +575,8 @@ PL_is_number.restype = c_int
#PL_EXPORT(void) PL_put_variable(term_t t);
PL_put_variable = _lib.PL_put_variable
PL_put_variable.argtypes = [term_t]
PL_put_variable.restype = None
#PL_EXPORT(void) PL_put_atom(term_t t, atom_t a);
#PL_EXPORT(void) PL_put_atom_chars(term_t t, const char *chars);
#PL_EXPORT(void) PL_put_string_chars(term_t t, const char *chars);
@ -420,27 +587,39 @@ PL_put_variable.argtypes = [term_t]
#PL_EXPORT(void) PL_put_list_nchars(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_list_ncodes(term_t t, size_t l, const char *chars);
#PL_EXPORT(void) PL_put_integer(term_t t, long i);
PL_put_integer = _lib.PL_put_integer
PL_put_integer.argtypes = [term_t, c_long]
PL_put_integer.restype = None
#PL_EXPORT(void) PL_put_pointer(term_t t, void *ptr);
#PL_EXPORT(void) PL_put_float(term_t t, double f);
#PL_EXPORT(void) PL_put_functor(term_t t, functor_t functor);
PL_put_functor = _lib.PL_put_functor
PL_put_functor.argtypes = [term_t, functor_t]
PL_put_functor.restype = None
#PL_EXPORT(void) PL_put_list(term_t l);
PL_put_list = _lib.PL_put_list
PL_put_list.argtypes = [term_t]
PL_put_list.restype = None
#PL_EXPORT(void) PL_put_nil(term_t l);
PL_put_nil = _lib.PL_put_nil
PL_put_nil.argtypes = [term_t]
PL_put_nil.restype = None
#PL_EXPORT(void) PL_put_term(term_t t1, term_t t2);
PL_put_term = _lib.PL_put_term
PL_put_term.argtypes = [term_t, term_t]
PL_put_term.restype = None
# /* construct a functor or list-cell */
#PL_EXPORT(void) PL_cons_functor(term_t h, functor_t f, ...);
#class _PL_cons_functor(object):
PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_cons_functor = _lib.PL_cons_functor # FIXME:
#PL_cons_functor.argtypes = [term_t, functor_t,
#PL_EXPORT(void) PL_cons_functor_v(term_t h, functor_t fd, term_t a0);
PL_cons_functor_v = _lib.PL_cons_functor_v
@ -449,6 +628,7 @@ PL_cons_functor_v.restype = None
#PL_EXPORT(void) PL_cons_list(term_t l, term_t h, term_t t);
PL_cons_list = _lib.PL_cons_list
PL_cons_list.argtypes = [term_t, term_t, term_t]
#
# term_t PL_exception(qid_t qid)
@ -456,9 +636,12 @@ PL_exception = _lib.PL_exception
PL_exception.argtypes = [qid_t]
PL_exception.restype = term_t
#
#func_t = CFUNCTYPE(c_int)
PL_register_foreign = _lib.PL_register_foreign
PL_register_foreign.argtypes = [c_char_p, c_int, c_void_p, c_int]
PL_register_foreign.restype = None
#
#PL_EXPORT(atom_t) PL_new_atom(const char *s);
@ -483,12 +666,11 @@ PL_record.restype = record_t
#PL_EXPORT(void) PL_recorded(record_t record, term_t term);
PL_recorded = _lib.PL_recorded
PL_recorded.argtypes = [record_t,term_t]
PL_recorded.restype = None
#PL_EXPORT(void) PL_erase(record_t record);
PL_erase = _lib.PL_erase
PL_erase.argtypes = [record_t]
PL_erase.restype = None
#
#PL_EXPORT(char *) PL_record_external(term_t t, size_t *size);
#PL_EXPORT(int) PL_recorded_external(const char *rec, term_t term);
@ -580,16 +762,16 @@ IOSTREAM._fields_.extend([("tee",IOSTREAM),
#PL_EXPORT(IOSTREAM *) Sopen_string(IOSTREAM *s, char *buf, size_t sz, const char *m);
#Sopen_string = _lib.Sopen_string
#Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
#Sopen_string.restype = POINTER(IOSTREAM)
Sopen_string = _lib.Sopen_string
Sopen_string.argtypes = [POINTER(IOSTREAM), c_char_p, c_size_t, c_char_p]
Sopen_string.restype = POINTER(IOSTREAM)
#PL_EXPORT(int) Sclose(IOSTREAM *s);
#Sclose = _lib.Sclose
#Sclose.argtypes = [POINTER(IOSTREAM)]
Sclose = _lib.Sclose
Sclose.argtypes = [POINTER(IOSTREAM)]
#PL_EXPORT(int) PL_unify_stream(term_t t, IOSTREAM *s);
#PL_unify_stream = _lib.PL_unify_stream
#PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]
PL_unify_stream = _lib.PL_unify_stream
PL_unify_stream.argtypes = [term_t, POINTER(IOSTREAM)]

68
packages/pyswip/pyswip/easy.py Normal file → Executable file
View File

@ -40,7 +40,8 @@ class Atom(object):
else:
self.handle = handleOrChars
PL_register_atom(self.handle)
self.chars = c_char_p(PL_atom_chars(self.handle)).value
#self.chars = c_char_p(PL_atom_chars(self.handle)).value
self.chars = PL_atom_chars(self.handle)
def fromTerm(cls, term):
"""Create an atom from a Term or term handle."""
@ -48,7 +49,7 @@ class Atom(object):
term = term.handle
a = atom_t()
if PL_get_atom(term, addressof(a)):
if PL_get_atom(term, byref(a)):
return cls(a.value)
fromTerm = classmethod(fromTerm)
@ -115,7 +116,9 @@ class Variable(object):
else:
raise
if (self.handle == None):
t = PL_new_term_ref()
self.handle = t
fun(self.handle, value)
def get_value(self):
@ -139,7 +142,6 @@ class Variable(object):
#PL_put_variable(term)
self.handle = term
class Functor(object):
__slots__ = "handle","name","arity","args","__value","a0"
func = {}
@ -256,7 +258,7 @@ def getAtomChars(t):
"""If t is an atom, return it as a string, otherwise raise InvalidTypeError.
"""
s = c_char_p()
if PL_get_atom_chars(t, addressof(s)):
if PL_get_atom_chars(t, byref(s)):
return s.value
else:
raise InvalidTypeError("atom")
@ -269,8 +271,8 @@ def getAtom(t):
def getBool(t):
"""If t is of type bool, return it, otherwise raise InvalidTypeError.
"""
b = c_long()
if PL_get_long(t, byref(b)):
b = c_int()
if PL_get_int(t, byref(b)):
return bool(b.value)
else:
raise InvalidTypeError("bool")
@ -278,9 +280,9 @@ def getBool(t):
def getLong(t):
"""If t is of type long, return it, otherwise raise InvalidTypeError.
"""
i = c_long()
if PL_get_long(t, byref(i)):
return i.value
l = c_long()
if PL_get_long(t, byref(l)):
return l.value
else:
raise InvalidTypeError("long")
@ -305,14 +307,22 @@ def getString(t):
else:
raise InvalidTypeError("string")
mappedTerms = {}
def getTerm(t):
global mappedTerms
#print 'mappedTerms', mappedTerms
#if t in mappedTerms:
# return mappedTerms[t]
p = PL_term_type(t)
if p < PL_TERM:
return _getterm_router[p](t)
res = _getterm_router[p](t)
elif PL_is_list(t):
return getList(t)
res = getList(t)
else:
return getFunctor(t)
res = getFunctor(t)
mappedTerms[t] = res
return res
def getList(x):
"""Return t as a list.
@ -339,15 +349,31 @@ _getterm_router = {
PL_TERM:getTerm
}
arities = {}
def _callbackWrapper(arity=1):
return CFUNCTYPE(*([foreign_t] + [term_t]*arity))
global arities
res = arities.get(arity)
if res is None:
res = CFUNCTYPE(*([foreign_t] + [term_t]*arity))
arities[arity] = res
return res
funwraps = {}
def _foreignWrapper(fun):
global funwraps
res = funwraps.get(fun)
if res is None:
def wrapper(*args):
args = [getTerm(arg) for arg in args]
r = fun(*args)
return (r is None) and True or r
return wrapper
res = wrapper
funwraps[fun] = res
return res
cwraps = []
def registerForeign(func, name=None, arity=None, flags=0):
"""Register a Python predicate
@ -358,14 +384,21 @@ def registerForeign(func, name=None, arity=None, flags=0):
``arity``: Arity (number of arguments) of the function. If this value is not
used, ``func.arity`` should exist.
"""
global cwraps
if arity is None:
arity = func.arity
if name is None:
name = func.func_name
return PL_register_foreign(name, arity,
cast(_callbackWrapper(arity)(_foreignWrapper(func)),c_void_p), (flags))
cwrap = _callbackWrapper(arity)
fwrap = _foreignWrapper(func)
fwrap2 = cwrap(fwrap)
cwraps.append(fwrap2)
return PL_register_foreign(name, arity, cast(fwrap2, c_void_p), flags)
# return PL_register_foreign(name, arity,
# _callbackWrapper(arity)(_foreignWrapper(func)), flags)
newTermRef = PL_new_term_ref
@ -416,7 +449,6 @@ class Query(object):
f = Functor.fromTerm(t)
p = PL_pred(f.handle, module)
Query.fid = PL_open_foreign_frame()
Query.qid = PL_open_query(module, flags, p, f.a0)
# def __del__(self):
@ -435,9 +467,7 @@ class Query(object):
def closeQuery():
if Query.qid is not None:
PL_close_query(Query.qid)
PL_discard_foreign_frame(Query.fid)
Query.qid = None
Query.fid = None
closeQuery = staticmethod(closeQuery)

View File

@ -25,10 +25,11 @@ def _initialize():
plargs[0] = "./"
plargs[1] = "-q"
plargs[2] = "-nosignals"
#plargs[2] = "\x00"
PL_initialise(3, plargs)
swipl_fid = PL_open_foreign_frame()
swipl_load = PL_new_term_ref()
PL_chars_to_term("asserta((pyrun(GoalString,BindingList):-atom_codes(A,GoalString),atom_to_term(A,Goal,BindingList),call(Goal))).", swipl_load)
PL_chars_to_term("asserta((pyrun(GoalString,BindingList):-(atom_codes(A,GoalString),atom_to_term(A,Goal,BindingList),call(Goal)))).", swipl_load)
PL_call(swipl_load, None)
PL_discard_foreign_frame(swipl_fid)
_initialize()

View File

@ -12,7 +12,7 @@ setup(name="pyswip",
download_url="http://code.google.com/p/pyswip/downloads/list",
author="Yuce Tekol",
author_email="yucetekol@gmail.com",
description="PySWIP enables querying SWI-Prolog and YAP in your Python programs.",
description="PySWIP enables querying SWI-Prolog in your Python programs.",
long_description="""
PySWIP 0.2.2
============