noxdafox / clipspy Goto Github PK
View Code? Open in Web Editor NEWPython CFFI bindings for the 'C' Language Integrated Production System CLIPS
License: BSD 3-Clause "New" or "Revised" License
Python CFFI bindings for the 'C' Language Integrated Production System CLIPS
License: BSD 3-Clause "New" or "Revised" License
Hi, I have a problem when I use modify_slots on an instance of a subclass. Hope you can help me.
Using your code as a basis:
import clips
env = clips.Environment()
defclass = """
(defclass MyClass (is-a USER)
(slot One)
(slot Two))
"""
env.build(defclass)
defclass = env.find_class("MyClass")
instance = defclass.make_instance("MyInstance", One=1, Two=2)
fact = env.assert_string('(foo bar baz)')
instance.modify_slots(One=fact)
defclass = """
(defclass SUBMyClass (is-a MyClass)
(slot Three))
"""
env.build(defclass)
defclass = env.find_class("SUBMyClass")
instance = defclass.make_instance("SUBMyInstance", One=1)
for i in env.instances():
print(i)
This shows:
[MyInstance] of MyClass (One <Fact-1>) (Two 2)
[SUBMyInstance] of SUBMyClass (One 1) (Two nil) (Three nil)
Then, when I do this:
instance.modify_slots(Three=3)
The kernel dies...
Any idea of what I'm doing wrong?
Thanks in advance! And for your work!
Laura
It looks like *build*
in .gitignore matches clips_build.py
Hey there,
I've installed your library on RedHat7.3 VM from the sources using the Makefile provided and everything worked as expected during the process. However when I'm trying to make an Import in the python interpreter I've got the following message:
import clips
Traceback (most recent call last):
File "", line 1, in
File "clips/init.py", line 30, in
from clips.error import CLIPSError
File "clips/error.py", line 32, in
from clips.router import Router
File "clips/router.py", line 7, in
from clips._clips import lib, ffi
ImportError: No module named _clips
Indeed I don't see any module named _clips in the package. Do you have any idea where I'm missing something ?
Thanks for your help.
This is a continuation from my SO post.
After re-installing clipspy using the repo with tag 3.2, I get the errors:
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/site-packages/clipspy-0.3.1-py3.7-linux-x86_64.egg/clips/__init.py", line 30, in <module> from clips.error import CLIPSError
File "/usr/lib/python3.7/site-packages/clipspy-0.3.1-py3.7-linux-x86_64.egg/clips/error.py", line 32, in <module> from clips.router import Router
File "/usr/lib/python3.7/site-packages/clipspy-0.3.1-py3.7-linux-x86_64.egg/clips/router.py", line 7, in <module> from clips._clips import lib ffi
Import Error: libclips.so: cannot open shared object file: No such file or directory
Despite saying a libclips.so does not exist, I have the following files inside /usr/lib/
libclips.so.6
libclips.so.6.30
EDIT 1:
I think I fixed it. Renamed libclips.so.6 in the folder /usr/lib/ to libclips.so. Now I can import clips.
I cannot get a clips environment to load a text file. I'm on windows using clipspy 0.3.2.
Reproducible example:
simple_clips_test.py:
import clips
clips_env = clips.Environment()
demo_clips_facts_filename = "demo.clp"
clips_env.load(demo_clips_facts_filename)``
demo.clp:
;;; Class Structure
(defclass A (is-a USER)
(role concrete)
(multislot secondary-types)
(multislot hasIssue (type INSTANCE-NAME)))
(defclass B (is-a USER)
(role concrete)
(multislot secondary-types))
(defclass C (is-a USER)
(role concrete)
(multislot secondary-types))
(defclass D (is-a USER)
(role concrete)
(multislot connectedTo (type INSTANCE-NAME))
(multislot secondary-types))
;;; Class Instances
(definstances individuals
(temp_a of D)
(temp_b of D)
) ; close up definstance
When I use the CLIPS repl to load this, it works just fine:
https://imgur.com/a/VgSdrj1
When debugging, I see that self._load_text(path)
is called, I'm just not sure what's causing the error.
The below code outputs:
---
/path/to/binary
<class 'str'>
---
/path2/to/binary
<class 'clips.common.Symbol'>
---
/path2/to/binary
<class 'str'>
Is this how it is supposed to be? Isn't there a type InstanceName? How can I know from python if I have (slotname [a_string])
or
(slotname "a_string")
?
import clips
env = clips.Environment()
binary_class_string = """
(defclass clips_BINARY (is-a USER)
(slot path)
(slot path2)
(slot path3))
"""
env.build(binary_class_string)
network_function_class_string = """
(defclass clips_NETWORK_FUNCTION (is-a USER)
(slot binary)
(slot start_address))
"""
env.build(network_function_class_string)
make_binary_instance_string = """
(make-instance UniversalSample.exe of clips_BINARY (path [/path/to/binary]) (path2 /path2/to/binary) (path3 "/path2/to/binary"))
"""
env.eval(make_binary_instance_string)
instance_just_created = env.find_instance("UniversalSample.exe")
print(instance_just_created)
make_network_function_instance_string = """
(make-instance my_func of clips_NETWORK_FUNCTION (binary [UniversalSample.exe])(start_address 4278884))
"""
env.eval(make_network_function_instance_string)
instance_just_created = env.find_instance("my_func")
print(instance_just_created)
print(type(instance_just_created["binary"]))
linked_instance = env.find_instance(instance_just_created["binary"])
print(linked_instance)
print("---")
print(linked_instance['path'])
print(type(linked_instance['path']))
print("---")
print(linked_instance['path2'])
print(type(linked_instance['path2']))
print("---")
print(linked_instance['path3'])
print(type(linked_instance['path3']))
Environment becomes unusable after error:
import clips
env = clips.Environment()
env.eval('(printout t "Hello World!" crlf)')
try:
env.eval('(if (= 0 nil)then (printout t "Hello World!1" crlf))')
except Exception as e:
print "EXCEPTION", e
print "attempt to call CLIPS"
env.eval('(printout t "Hello World!2" crlf)')
print "attempt to call CLIPS2"
env.eval('(printout t "Hello World!3" crlf)')
(= 0 nil) causes an error. It is expected that "Hello World!2" and "Hello World!3" would be printed as in CLIPS itself. But that doesn't happen. env.eval('(printout t "Hello World!2" crlf)')
throws anv error.
Similar CLIPS example:
$ ./clips
CLIPS (6.30 3/17/15)
CLIPS> (printout t "Hello World!" crlf)
Hello World!
CLIPS> (if (= 0 nil)then (printout t "Hello World!1" crlf))
[ARGACCES5] Function = expected argument #2 to be of type integer or float
CLIPS> (printout t "Hello World!" crlf)
Hello World!
CLIPS> (exit)
I asked this also in this SO post.
Is it possible to read the ErrorStream from clips using clipspy? With pyclips, it worked this way: clips.ErrorStream.Read().
Does it even make sense to do it with clipspy, or are all errors thrown as exceptions and can be caught with clips.CLIPSError ?
;;---KB.clp---;;
(deftemplate fact_template
(slot slot_1
(type SYMBOL))
(slot slot_2
(type SYMBOL))
)
(assert (fact 1))
(assert (fact_template (slot_1 v1) (slot_2 v2)))
(defrule rule1
(fact 1)
=>
?p <- (fact_template (slot_1 ?s1)
?q <- (fact_template (slot_2 ?s2)
(py_retract ?p ?q))
# run.py
import clips
clips_env = clips.Environment()
clips_env.load("KB.clp")
def py_retract(p, q):
env.build('retract '+str(p))
clips_env.define_function(py_retract)
clips_env.run()
This does not works as both p and q are not fact-identifier but come as entire fact-template.
How to change only one slot of the template keeping other intact.
Setup.py installs files that are not needed for package operation:
data_files=[('lib', ['lib/clips.c', 'lib/clips.cdef'])],
I followed the instruction on https://pypi.org/project/clipspy/, but could net set it up.
I have compiled the clips core and cp *.h to /usr/local/include/clips and cp *.a to /usr/lib/clips
but it does not work. "Failed building wheel for clipspy"
waiting for help
when I tried code this, the method 'make_instance' cannot be found. It showed some error. There are also some other methods which behave like this.
below is the error:
Traceback (most recent call last):
File "C:\Users\GabrielLCH\Anaconda3\envs\krr_expert_system\lib\site-packages\clips\environment.py", line 84, in __getattr__
return getattr(self._namespaces[attr], attr)
KeyError: 'make_instance'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\...\clipspy tutor.py", line 50, in <module>
instance = env.make_instance('(instance-name of MyClass (One 1) (Two 2))')
File "C:\...\site-packages\clips\environment.py", line 87, in __getattr__
(self.__class__.__name__, attr))
AttributeError: 'Environment' object has no attribute 'make_instance'
How to get the RHS of each active rule after do run
Hello.
I wanted to make a custom router class so that instead of outputting to a log file, I can directly get the string and parse it to create a python object.
This python object is later used to check the inference process.
I have created the following router
from clips.routers import Router
from typing import Callable
class CallbackRouter(Router):
def __init__(self, callback: Callable, priority: int = 10):
super().__init__("callback-router", priority)
self.callback = callback
self.reset_message()
def query(self, _name: str) -> bool:
return True
return (_name == "stdout")
def write(self, _name: str, _message: str):
"""
If the message is a new-line terminate sentence,
log it at according to the mapped level.
Otherwise, append it to the message string.
Same as Logging ROuter
"""
if _message == '\n':
self.log_message(_name)
else:
self._message += _message
if self._message.rstrip(' ').endswith('\n'):
self.log_message(_name)
def log_message(self, name: str):
if self._message:
self.callback(self._message.lstrip('\n').rstrip('\n'))
self.reset_message()
def reset_message(self):
self._meesage = ""
And a parser
from myclips.callback_router import CallbackRouter
from clips import Environment
class LogParser:
def __init__(self, env: Environment) -> None:
# Setup router
self.router = CallbackRouter(callback=self.add_log)
env.add_router(self.router)
# Setup log
self.reset_log()
def reset_log(self):
self.log : list[str] = []
def add_log(self, message: str):
assert type(message) is str
self.log.append(message)
clips.Environment
is passed into the LogParser and ran. But eventhough I have altered query
method to return True
indefinitly, nothing gets added to the self.log
. I have tried this with the log router
and it correctly outputs.
What might be the problem here?
defaults to dumping everything in root directory
I'm brainstorming about running clipspy in Flask with a stateless endpoint. E.g., the web client's asserted facts would be re-sent with every GET request. The endpoint would create a new environment for the request, and terminate it when done. The reason would be to scale well for the web.
Being able to make CLIPS web apps would be pretty powerful.
In pyclips, one could do this:
clips.RegisterPythonFunction(function_to_register, function_name_in_clips)
In clipspy, I can only do this:
clips_env.define_function(function_to_register)
Is this by design? I tried to set the __name__
property of function_to_register
but it didn't work. Is it possible to change the name?
I can find the rules by 'find_rule',but why not provide the 'find_fact' method ?
I need help.
Hey there
Having successfully installed the package using "sudo make install" ( after chaning python to python3 in the 1st line) , I get the following error as I try to import clips
>>> import clips
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/pi/pythonClips/clipspy/clips/__init__.py", line 56, in <module>
from clips.environment import Environment
File "/home/pi/pythonClips/clipspy/clips/environment.py", line 32, in <module>
from clips.facts import Facts
File "/home/pi/pythonClips/clipspy/clips/facts.py", line 47, in <module>
from clips.modules import Module
File "/home/pi/pythonClips/clipspy/clips/modules.py", line 40, in <module>
from clips.common import CLIPSError
File "/home/pi/pythonClips/clipspy/clips/common.py", line 33, in <module>
from clips._clips import lib, ffi
ModuleNotFoundError: No module named 'clips._clips'
Why not use pip ? I am trying to use the package on raspberry pi , and of course have been able to compile clips on raspberry.
Any suggestions ?
thanks in advance
It looks like "gensym" is not exposed through API.
When an instance is created in CLIPS, instance name is optional.
$ clips
CLIPS (6.30 3/17/15)
CLIPS> (defclass MyClass (is-a USER)
(slot One (type INTEGER)(default 222))
(slot Two))
CLIPS> (make-instance of MyClass)
[gen1]
CLIPS>
If instance name is not supplied, CLIPS calls (gensym) and generates a name ([gen1] in the example). It would be nice to have exactly the same behavior in clipspy.
As of now:
instance = klass.new_instance('')
would create an instance with an empty name. Pyclips would generate name in such case. Another option is use None as an indicator that clipspy should call (gensym).
There are work arounds for sure - it's easy for a user to generate some symbols by himself, but that would duplicate the feature already present in CLIPS.
While installing clipspy in Pycharm on Windows via Settings->Project Interpreter I get error
Collecting clipspy
Using cached https://files.pythonhosted.org/packages/10/e8/87c3293255eb3beb328c2c0af7e9b768b066c395417c626dfc3a04e5b725/clipspy-0.3.3.tar.gz
Complete output from command python setup.py egg_info:
fatal: not a git repository (or any of the parent directories): .git
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\wodobrow\AppData\Local\Temp\pycharm-packaging\clipspy\setup.py", line 73, in <module>
long_description=read('README.rst'),
File "C:\Users\wodobrow\AppData\Local\Temp\pycharm-packaging\clipspy\setup.py", line 36, in read
return open(os.path.join(os.path.dirname(__file__), fname)).read()
File "C:\Users\wodobrow\AppData\Local\Programs\Python\Python38\lib\encodings\cp1250.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 77: character maps to <undefined>
----------------------------------------
python version 3.8
setuptools version 56.0.0
Everything I have tried in a Jupyter notebook so far is working perfectly except for printing from inside a rule. env.eval('(printout t "hello")') works fine but not in the consequent section of a rule, e.g. '(defrule xyz ... => (printout t "hello") ...)'.
My workarounds so far have been to write to a file (works fine), asserting printable facts and printing them (not my preference but works), and using embedded python to create a new function to print something (e.g. def myprint(str): print(str) and then using define_function() (also works).
Thanks for all the great work on this library, and I hope this turns out to be a simple thing for those CLIPS users with existing rule bases that they want to expose in Jupyter.
;;--- KB.clp---;;
deftemplate fact_template(
(slot slot_1 (type SYMBOL))
)
(assert (fact 1))
(defrule rule1
(fact 1)
=>
?p <- (assert (fact_template (slot_1 v_1)))
(py_foo ?p ))
# run.py
import clips
clips_env = clips.Environment()
clips_env.load("KB.clp")
def py_foo(p):
p['slot_1'] = 'slot_value'
p.assertit()
print "Done"
clips_env.define_function(py_foo)
clips_env.run()
anything after assertit() is not executed.
The below code returns None, and not the name of the instance.
It seems clipspy embedded python functions cannot handle clips variables (starting with an ?).
EDIT: It works for other slots, but not for the name slot.
import clips
def python_print(string_to_print):
print(string_to_print)
def build_instance(clips_class_name, clips_instance_name, slots=None):
instance_string = "(make-instance " + clips_instance_name + " of " + clips_class_name + ")"
env.eval(instance_string)
i = env.find_instance(clips_instance_name)
return i
if __name__ == "__main__":
env = clips.Environment()
class_string = """
(defclass A (is-a USER)
(slot One)
(slot Two))
"""
rule_string = """
(defrule my_rule
(object (is-a A)
(name ?name_of_an_A))
=>
(python_print ?name_of_an_A))
"""
env.build(class_string)
env.define_function(python_print)
env.build(rule_string)
klass = env.find_class("A")
i_1 = build_instance(klass.name, "i1")
i_1["One"] = "one"
env.run()
From pyclips
it looks like a pretty printer might be available via the underlying C API, see example 1 or example 2.
I'm currently exploring this codebase to see if something similar is available, either an API to pretty printing, or access to the underlying C library (perhaps clips._clips.ffi
?).
If anyone knows, please let me know. I'll answer my own question if I find an answer. Thanks!
Use case:
I'm basically trying to turn an ugly single-line blob of Lisp-like code into something which is indented nicely.
I am using Windows. How do I tell the installer where to find the clips.h
?
I tried adapting the setup.py
but it did not work.
Moreover, what code exactly should I download? This one:
https://sourceforge.net/projects/clipsrules/files/CLIPS/6.30/clips_core_source_630.zip/download
?
Hello! I new to clipspy and I am currently designing some rules based on dates.
When running my test scenarios with invalid dates, I noticed that exceptions throw by my python code are not reaching my except
clause.
The simplified example is:
def is_date_in_range(date: str, initial_date_range: str, final_date_range: str):
date = datetime.strptime(date, "%Y-%m-%d")
initial_date_range = datetime.strptime(initial_date_range, "%Y-%m-%d")
final_date_range = datetime.strptime(final_date_range, "%Y-%m-%d")
return initial_date_range <= date <= final_date_range
rule = """
(
defrule issue_date_rule
(issue_date ?issue_date)
=>
(bind ?is_date_in_range (is_date_in_range ?issue_date "2004-01-02" "2013-12-31"))
(
if (eq ?is_date_in_range TRUE) then
(println "condition satisfied")
else
(println "condition not satisfied")
)
)
"""
env = clips.Environment()
try:
env.define_function(is_date_in_range)
env.build(rule)
env.assert_string("(issue_date \"gibberish\")")
env.run()
except Exception as error:
print("Found an error")
In this code snippet I am asserting gibberish
to force the error on is_date_in_range
, which is thrown, but my application ends without printing condition satisfied
neither condition not satisfied
neither Found an error
.
If I debug is_date_in_range
I can see on the console:
ValueError: time data 'gibberish' does not match format '%Y-%m-%d'
ffi.error: struct udfContext: wrong offset for field 'context' (cdef says 0, but C compiler says 8). fix it or use "...;" as the last field in the cdef for struct udfContext to make it flexible
On the other hand if I purposefully add a typo to my if statement, like if (eqq ?is_date_in_range TRUE) then
, then I also won't see the condition satisfied
neither condition satisfied
, but I'll be able to catch CLIPSError
and see the Found an error
message printed.
I am running this snippet using Python 3.7.11 on MAC and also on Debian image, both showing the same results.
Am I missing some configuration that would allow me to catch it? I understand that defensive programming would be a better solution in this case, but I am concerned that my service won't be aware of unexpected errors.
Thanks in advance!
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate
c:\tmp\clipspy\clipspy>python setup.py install
Traceback (most recent call last):
File "C:\Python37\lib\urllib\request.py", line 1317, in do_open
encode_chunked=req.has_header('Transfer-encoding'))
File "C:\Python37\lib\http\client.py", line 1229, in request
self._send_request(method, url, body, headers, encode_chunked)
File "C:\Python37\lib\http\client.py", line 1275, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "C:\Python37\lib\http\client.py", line 1224, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "C:\Python37\lib\http\client.py", line 1016, in _send_output
self.send(msg)
File "C:\Python37\lib\http\client.py", line 956, in send
self.connect()
File "C:\Python37\lib\http\client.py", line 1392, in connect
server_hostname=server_hostname)
File "C:\Python37\lib\ssl.py", line 412, in wrap_socket
session=session
File "C:\Python37\lib\ssl.py", line 850, in _create
self.do_handshake()
File "C:\Python37\lib\ssl.py", line 1108, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 765, in open_url
return open_with_auth(url, self.opener)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 959, in _socket_timeout
return func(*args, **kwargs)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 1078, in open_with_auth
fp = opener(request)
File "C:\Python37\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Python37\lib\urllib\request.py", line 525, in open
response = self._open(req, data)
File "C:\Python37\lib\urllib\request.py", line 543, in _open
'_open', req)
File "C:\Python37\lib\urllib\request.py", line 503, in _call_chain
result = func(*args)
File "C:\Python37\lib\urllib\request.py", line 1360, in https_open
context=self._context, check_hostname=self._check_hostname)
File "C:\Python37\lib\urllib\request.py", line 1319, in do_open
raise URLError(err)
urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)>
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "setup.py", line 91, in <module>
"License :: OSI Approved :: BSD License"
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\__init__.py", line 130, in setup
_install_setup_requires(attrs)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\__init__.py", line 125, in _install_setup_requires
dist.fetch_build_eggs(dist.setup_requires)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\dist.py", line 514, in fetch_build_eggs
replace_conflicting=True,
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\pkg_resources\__init__.py", line 773, in resolve
replace_conflicting=replace_conflicting
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\pkg_resources\__init__.py", line 1056, in best_match
return self.obtain(req, installer)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\pkg_resources\__init__.py", line 1068, in obtain
return installer(requirement)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\dist.py", line 581, in fetch_build_egg
return cmd.easy_install(req)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\command\easy_install.py", line 664, in easy_install
not self.always_copy, self.local_index
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 654, in fetch_distribution
dist = find(requirement)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 634, in find
loc = self.download(dist.location, tmpdir)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 578, in download
found = self._download_url(scheme.group(1), spec, tmpdir)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 823, in _download_url
return self._attempt_download(url, filename)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 829, in _attempt_download
headers = self._download_to(url, filename)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 728, in _download_to
fp = self.open_url(url)
File "C:\Users\vagrant\AppData\Roaming\Python\Python37\site-packages\setuptools\package_index.py", line 779, in open_url
% (url, v.reason))
distutils.errors.DistutilsError: Download error for https://files.pythonhosted.org/packages/ca/f2/e375b7469a2dfe9d1feac81a10df97f18cd771b9a10ac62ca9864b760f7c/cffi-1.11.5-cp37-cp37m-win_amd64.whl#sha256=495c5c2d43bf6cebe0178eb3e88f9c4aa48d8934aa6e3cddb865c058da76756b: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045
```)
Consider following example:
from clips import Environment
env = Environment()
class_string = """
(defclass MyClass (is-a USER)
(slot One (type INTEGER)(default 222))
(slot Two))
"""
env.eval("(watch instances)")
env.eval("(watch slots)")
env.build(class_string)
klass = env.find_class('MyClass')
instance = klass.new_instance('instance-name')
instance['Two'] = 1
print instance
Result is:
==> instance [instance-name] of MyClass
::= local slot Two in instance instance-name <- 1
[instance-name] of MyClass (One nil) (Two 1)
which is wrong. Slot One should be 222 as it is in CLIPS.
$ clips
CLIPS (6.30 3/17/15)
CLIPS> (batch test13.clp)
TRUE
CLIPS> (defclass MyClass (is-a USER)
(slot One (type INTEGER)(default 222))
(slot Two))
CLIPS>
(watch instances)
CLIPS> (watch slots)
CLIPS>
(make-instance [r1] of MyClass)
==> instance [r1] of MyClass
::= local slot One in instance r1 <- 222
::= local slot Two in instance r1 <- nil
[r1]
CLIPS>
(exit)
Clipspy uses void *EnvCreateRawInstance(environment,defclassPtr,instanceName);
to create an instance. Documentation for this function states:
Creates an empty instance with the specified name of the specified
class. No slot overrides or class default initializations are performed
for the instance.Warning: This function bypasses message-passing.
lib/clips.cdef:void *EnvMakeInstance(void *, const char *);
should be exposed through API;
EnvCreateRawInstance is more of the internal CLIPS function. It's not really needed to be exposed through Clipspy API.
I've added a new method at my environment.py:
def make_instance(self, inststr):
"""Create a new instance from an instance string"""
ist = lib.EnvMakeInstance(self._env, inststr.encode())
if ist == ffi.NULL:
raise CLIPSError(self._env)
return clips.classes.Instance(self._env, ist)
On Windows Server 2016, python 3.7, importing clips gives me the below error, no matter if installed using pip install clipspy
or built by myself.
PS C:\tmp\clipspy> python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win3
Type "help", "copyright", "credits" or "license" for more information.
>>> import clips
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\tmp\clipspy\clips\__init__.py", line 30, in <module>
from clips.error import CLIPSError
File "C:\tmp\clipspy\clips\error.py", line 32, in <module>
from clips.router import Router
File "C:\tmp\clipspy\clips\router.py", line 5, in <module>
from clips._clips import lib, ffi
ModuleNotFoundError: No module named 'clips._clips'
I've tried installing on Windows 10 Pro with python 3.7 and I'm getting the following error:
build\temp.win-amd64-3.7\Release\_clips.c(523): fatal error C1083: Cannot open include file: 'clips.h': No such file or directory
I've tried using both Visual Studio Build Tools for 2015 (v14.00) and 2019, and both give me 'clips.h' error.
Also, the pypi link doesn't seem to show any wheels for windows? (If I'm wrong here let me know)
https://pypi.org/project/clipspy/#modal-close
Any advice or tips on how to solve this? I'd prefer to not install from scratch.
I have created a class instance named UniversalSample.exe
.
Now I have the following string:
'(make-instance my_function of clips_NETWORK_FUNCTION (binary [UniversalSample.exe])(start_address 4278884)(function_name "blah"))'
This creates a new class instance:
clips_env.eval(make_instance_string)
Then I obtain the newly created class instance via:
instance_just_created = clips_env.find_instance(clips_instance_name)
However,
type(instance_just_created["binary"])
returns
<class 'str'>`
but not (as I expected)
<class 'clips.classes.Instance'>
How can I create a class instance that has a property pointing to another class instance that I know the name of?
All Python classes should inherit from (object) for Python 2.7. Otherwise search in TYPES fails for classes that don't inherit from (object).
The error => [BLOAD2] File book.clp is not a binary construct file.
from clips import Environment, Symbol
env = Environment()
env.clear()
env.load('book.clp')
env.facts()
env.run()
(deftemplate book
(multislot surname)(slot name)(multislot title)
)
(deffacts initial
(book (surname J.P.)(name Dubreuil)(title History of francmasons))
(book (surname T.)(name Eker)(title Secrets of millionaire mind)))
(defrule find_title
?book<-(book(name Eker))
=>
(printout t ?book crlf)
)
Would be great to have mypy type checking support.
We could add this for one function after the other. It would not interrupt the regular functioning.
Just started to work with clipspy-0.3.3 in Python 3.8.3.
When extracting facts, an inconsistency was encountered in the .facts()
enumerator.
The code below
import clips
env = clips.Environment()
env.assert_string("(value 1)")
env.assert_string("(value 2)")
env.assert_string("(value 3)")
env.assert_string("(value 4)")
env.assert_string("(value 5)")
env.assert_string("(value 6)")
env.assert_string("(value 7)")
env.assert_string("(value 8)")
env.assert_string("(value 9)")
env.assert_string("(value 10)")
for fact in env.facts():
print(fact)
Produces result
(initial-fact)
(value 1)
(value 2)
(value 3)
(value 4)
(value 5)
(value 6)
(value 7)
(value 8)
(value 9)
f-10 (value 10)
from which one can see an inconsistency in which
f-1
is dropped away from the fact string, and,f-10
is not dropped away from the fact string.Even if the above inconsistency can be solved with regular expression substitution, as follow
import re
for fact in env.facts():
print(re.sub(r'^[^(]*',r'',str(fact)))
would be nice if the string representation of facts would be returned consistently by the .facts()
enumerator in clispy
package.
The pip installation worked fine with Python 3.7.
However, the same commands (pip install clipspy)
cause the below error.
C:\Users\vagrant>pip install clipspy
Collecting clipspy
Downloading https://files.pythonhosted.org/packages/e2/66/f31407774ee4dc486de406cdc84dbaf32af1a41037ebfb3c5c22d950d6e2/clipspy-0.2.4-cp37-cp37m-win_amd64.whl (476kB)
100% |████████████████████████████████| 481kB 2.2MB/s
Collecting cffi>=1.0.0 (from clipspy)
Downloading https://files.pythonhosted.org/packages/ca/f2/e375b7469a2dfe9d1feac81a10df97f18cd771b9a10ac62ca9864b760f7c/cffi-1.11.5-cp37-cp37m-win_amd64.whl (165kB)
100% |████████████████████████████████| 174kB 6.5MB/s
Collecting pycparser (from cffi>=1.0.0->clipspy)
Using cached https://files.pythonhosted.org/packages/8c/2d/aad7f16146f4197a11f8e91fb81df177adcc2073d36a17b1491fd09df6ed/pycparser-2.18.tar.gz
Installing collected packages: pycparser, cffi, clipspy
Running setup.py install for pycparser ... done
Successfully installed cffi-1.11.5 clipspy-0.2.4 pycparser-2.18
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
C:\Users\vagrant>python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import clipspy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'clipspy'
>>> import clips
>>> exit()
C:\Users\vagrant>c:\Python27\Scripts\pip.exe install clipspy
Collecting clipspy
Using cached https://files.pythonhosted.org/packages/d2/e9/5c3b0e9b6f504c24de16f2a37bea8fe872e9f66edcf1fea2b7d235a310cd/clipspy-0.2.4.tar.gz
Requirement already satisfied: cffi>=1.0.0 in c:\python27\lib\site-packages (from clipspy) (1.11.5)
Requirement already satisfied: enum34 in c:\python27\lib\site-packages (from clipspy) (1.1.6)
Requirement already satisfied: pycparser in c:\python27\lib\site-packages (from cffi>=1.0.0->clipspy) (2.18)
Installing collected packages: clipspy
Running setup.py install for clipspy ... error
Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\vagrant\\appdata\\local\\temp\\1\\pip-install-bl5so9\\clipspy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\vagrant\appdata\local\temp\1\pip-record-ikrdz6\install-record.txt --single-version-externally-managed --compile:
fatal: Not a git repository (or any of the parent directories): .git
running install
running build
running build_py
creating build
creating build\lib.win-amd64-2.7
creating build\lib.win-amd64-2.7\clips
copying clips\agenda.py -> build\lib.win-amd64-2.7\clips
copying clips\classes.py -> build\lib.win-amd64-2.7\clips
copying clips\clips_build.py -> build\lib.win-amd64-2.7\clips
copying clips\common.py -> build\lib.win-amd64-2.7\clips
copying clips\data.py -> build\lib.win-amd64-2.7\clips
copying clips\environment.py -> build\lib.win-amd64-2.7\clips
copying clips\error.py -> build\lib.win-amd64-2.7\clips
copying clips\facts.py -> build\lib.win-amd64-2.7\clips
copying clips\functions.py -> build\lib.win-amd64-2.7\clips
copying clips\modules.py -> build\lib.win-amd64-2.7\clips
copying clips\router.py -> build\lib.win-amd64-2.7\clips
copying clips\__init__.py -> build\lib.win-amd64-2.7\clips
running build_ext
generating cffi module 'build\\temp.win-amd64-2.7\\Release\\_clips.c'
creating build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release
building '_clips' extension
creating build\temp.win-amd64-2.7\Release\build
creating build\temp.win-amd64-2.7\Release\build\temp.win-amd64-2.7
creating build\temp.win-amd64-2.7\Release\build\temp.win-amd64-2.7\Release
C:\Users\vagrant\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -I/usr/include/clips -I/usr/local/include/clips -Ic:\python27\include -Ic:\python27\PC /Tcbuild\temp.win-amd64-2.7\Release\_clips.c /Fobuild\temp.win-amd64-2.7\Release\build\temp.win-amd64-2.7\Release\_clips.obj
_clips.c
build\temp.win-amd64-2.7\Release\_clips.c(523) : fatal error C1083: Cannot open include file: 'clips.h': No such file or directory
error: command 'C:\\Users\\vagrant\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2
----------------------------------------
Command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\vagrant\\appdata\\local\\temp\\1\\pip-install-bl5so9\\clipspy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record c:\users\vagrant\appdata\local\temp\1\pip-record-ikrdz6\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in c:\users\vagrant\appdata\local\temp\1\pip-install-bl5so9\clipspy\
I am new to CLIPS and to clipsPy. I am trying to create a instance of a CLIPS class
This is the class I have defined and correctly build in my python environment (clipsPy)
ENTITIES_CLASS = """
(defclass ENTITY-CLASS (is-a INITIAL-OBJECT)
(slot text (type STRING))
(slot confidence (type FLOAT))
(slot type (type SYMBOL))
)
"""
env.build(ENTITIES_CLASS)
This works as expected, but when I try to create an instance of this class:
new_instance = "(ent0-0 of ENTITY-CLASS (text 'Bruce Springsteen')(confidence 1.0)(type PER))"
env.make_instance( new_instance )
I get this empty error:
https://i.stack.imgur.com/rLTZY.png
I have tried multiple forms of building the new_instance string but none have work :
new_instance = '(ent0-0 of ENTITY-CLASS (text "Bruce Springsteen")(confidence 1.0)(type PER))'
new_instance = "(ent0-0 of ENTITY-CLASS (text 'Bruce Springsteen') (confidence 1.0) (type PER) )"
Where is my syntax error? I appreciate any help
Hi Noxdafox,
first of all I'd like to thank you for your amazing work in the Python wrapping of Clips functionalities. Your library is well documentated, well written and the manual is perfect. Congrats.
That said, I've to be frank: I'm an "absolute beginner" with Expert Systems (ES) or Rules Base Systems (RBS). My goal is to produce a thesis on this matter and so I started to study some implementations in Python, that's the language I've to use.
After some searches on web I put the attention on these libraries:
Of course, the paired CLIPS + CLIPSPY stays on other planet (NASA docet...), so I kindly ask you some information and your useful tips.
It's clear that CLIPSPY is a wrapper of the underlying C functions of CLIPS; so when we design an ES or a RBS we've to think in CLIPTONIC way, not in PYTHONIC.
Keeping in mind both are OOP, do you have some advices for using directly the Object Model written in Python to create the CLIPS CLASSES and relative inheritance hierarchy? Maybe there are something I neglected, or something you have in your to top hat.
Something like this pseudocode:
CLIPSclass: str = env.CreateFromPythonObject(object)
And this also for the creation of rules, starting, somehow, from the functions of the Python object with some adorners, why not.
If there is nothing ready-to-use, I'll be happy to write some code and send to your repository, if you agree.
Thanks in advance for your kind reply, and all the best for this new year.
Ciao
LH
Calling a Python function that returns 'long' type fails:
From cffi callback <function python_function at 0x7f6e56f65a28>:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/clipspy/environment.py", line 227, in python_function
data.value = ret if ret is not None else clips.common.Symbol('nil')
File "/usr/lib/python2.7/site-packages/clipspy/data.py", line 71, in value
dtype = TYPES[type(value)] if self._type is None else self._type
KeyError: (<type 'long'>,)
Same thing as this SO post.
Is there a built-in way to get all slots and their values from an instance as a dictionary?
I created this helper function but maybe there is a better way (using the Instance
class in classes.py
)?
Don't worry if there isn't, just checking because I used the Slots()
method in pyclips
a lot.
============================= test session starts =============================
platform win32 -- Python 3.7.0, pytest-3.8.2, py-1.6.0, pluggy-0.7.1
rootdir: C:\Users\vagrant\Desktop\clipspy, inifile:
collected 38 items
agenda_test.py ........ [ 21%]
classes_test.py .F..... [ 39%]
environment_test.py F.....F [ 57%]
facts_test.py ......... [ 81%]
functions_test.py .... [ 92%]
modules_test.py ... [100%]
================================== FAILURES ===================================
__________________________ TestClasses.test_classes ___________________________
self = <classes_test.TestClasses testMethod=test_classes>
def test_classes(self):
"""Classes wrapper test."""
self.assertEqual(
self.env.default_mode, ClassDefaultMode.CONVENIENCE_MODE)
self.env.default_mode = ClassDefaultMode.CONSERVATION_MODE
self.assertEqual(
self.env.default_mode, ClassDefaultMode.CONSERVATION_MODE)
defclass = self.env.find_class('USER')
self.assertTrue(defclass in self.env.classes())
with self.assertRaises(LookupError):
self.env.find_class('NonExisting')
defclass = self.env.find_class('ConcreteClass')
defclass.new_instance('some-instance')
defclass.new_instance('test-instance')
instance = self.env.find_instance('test-instance')
self.assertTrue(instance in self.env.instances())
with self.assertRaises(LookupError):
self.env.find_instance('NonExisting')
self.assertTrue(self.env.instances_changed)
self.assertFalse(self.env.instances_changed)
# See: https://sourceforge.net/p/clipsrules/tickets/33/
# with NamedTemporaryFile(buffering=0, delete=False) as tmp:
# saved = self.env.save_instances(tmp.name)
# self.env.reset()
# loaded = self.env.load_instances(tmp.name)
# self.assertEqual(saved, loaded)
with NamedTemporaryFile() as tmp:
saved = self.env.save_instances(tmp.name)
self.env.reset()
> loaded = self.env.restore_instances(tmp.name)
classes_test.py:76:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <clips.classes.Classes object at 0x00000238A70D9CD8>
instances = b'C:\\Users\\vagrant\\AppData\\Local\\Temp\\1\\tmp_i4ulaiw'
def restore_instances(self, instances):
"""Restore a set of instances into the CLIPS data base.
The Python equivalent of the CLIPS restore-instances command.
Instances can be passed as a set of strings or as a file.
"""
instances = instances.encode()
if os.path.exists(instances):
ret = lib.EnvRestoreInstances(self._env, instances)
if ret == -1:
> raise CLIPSError(self._env)
E clips.error.CLIPSError: [ARGACCES2] Function save-instances was unable to open file C:\Users\vagrant\AppData\Local\Temp\1\tmp_i4ulaiw.
c:\python37\lib\site-packages\clips\classes.py:179: CLIPSError
------------------------------ Captured log call ------------------------------
router.py 105 ERROR [ARGACCES2] Function save-instances was unable to open file C:\Users\vagrant\AppData\Local\Temp\1\tmp_i4ulaiw.
_______________________ TestEnvironment.test_batch_star _______________________
self = <environment_test.TestEnvironment testMethod=test_batch_star>
def test_batch_star(self):
"""Commands are evaluated from file."""
with NamedTemporaryFile() as tmp:
tmp.write(b"(assert (test-fact))\n")
tmp.flush()
> self.env.batch_star(tmp.name)
environment_test.py:111:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <clips.environment.Environment object at 0x00000238A71ADD08>
path = 'C:\\Users\\vagrant\\AppData\\Local\\Temp\\1\\tmphdq5bxa_'
def batch_star(self, path):
"""Evaluate the commands contained in the specific path.
The Python equivalent of the CLIPS batch* command.
"""
if lib.EnvBatchStar(self._env, path.encode()) != 1:
> raise CLIPSError(self._env)
E clips.error.CLIPSError: [ARGACCES2] Function batch was unable to open file C:\Users\vagrant\AppData\Local\Temp\1\tmphdq5bxa_.
c:\python37\lib\site-packages\clips\environment.py:148: CLIPSError
------------------------------ Captured log call ------------------------------
router.py 105 ERROR [ARGACCES2] Function batch was unable to open file C:\Users\vagrant\AppData\Local\Temp\1\tmphdq5bxa_.
_______________________ TestEnvironment.test_save_load ________________________
self = <environment_test.TestEnvironment testMethod=test_save_load>
def test_save_load(self):
"""Constructs are saved and loaded."""
with NamedTemporaryFile() as tmp:
> self.env.save(tmp.name)
environment_test.py:119:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <clips.environment.Environment object at 0x00000238A718E588>
path = 'C:\\Users\\vagrant\\AppData\\Local\\Temp\\1\\tmpxhcavfm7'
binary = False
def save(self, path, binary=False):
"""Save a set of constructs into the CLIPS data base.
If binary is True, the constructs will be saved in binary format.
The Python equivalent of the CLIPS load command.
"""
if binary:
ret = lib.EnvBsave(self._env, path.encode())
else:
ret = lib.EnvSave(self._env, path.encode())
if ret == 0:
> raise CLIPSError(self._env)
E clips.error.CLIPSError
c:\python37\lib\site-packages\clips\environment.py:139: CLIPSError
===================== 3 failed, 35 passed in 0.24 seconds =====================
Installation of clipspy using pip on MacOS 10.15 (Catalina) throws an error. Using command "python3 -m pip install clipspy" produces the following error: "/usr/local/include/clips.h:35:10: fatal error: 'setup.h' file not found". Full output below. Any advice would be welcome.
Collecting clipspy Using cached clipspy-0.3.3.tar.gz (22 kB) Requirement already satisfied: cffi>=1.0.0 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from clipspy) (1.14.5) Requirement already satisfied: pycparser in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from cffi>=1.0.0->clipspy) (2.20) Using legacy 'setup.py install' for clipspy, since package 'wheel' is not installed. Installing collected packages: clipspy Running setup.py install for clipspy ... error ERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-install-0938nd9m/clipspy_349f10090e3049f59c3995983c6b0475/setup.py'"'"'; __file__='"'"'/private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-install-0938nd9m/clipspy_349f10090e3049f59c3995983c6b0475/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-record-g_kqqipt/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/clipspy cwd: /private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-install-0938nd9m/clipspy_349f10090e3049f59c3995983c6b0475/ Complete output (32 lines): fatal: not a git repository (or any of the parent directories): .git running install running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.8 creating build/lib.macosx-10.9-x86_64-3.8/clips copying clips/functions.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/facts.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/agenda.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/error.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/__init__.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/clips_build.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/common.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/environment.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/modules.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/classes.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/router.py -> build/lib.macosx-10.9-x86_64-3.8/clips copying clips/data.py -> build/lib.macosx-10.9-x86_64-3.8/clips running build_ext generating cffi module 'build/temp.macosx-10.9-x86_64-3.8/_clips.c' creating build/temp.macosx-10.9-x86_64-3.8 building '_clips' extension creating build/temp.macosx-10.9-x86_64-3.8/build creating build/temp.macosx-10.9-x86_64-3.8/build/temp.macosx-10.9-x86_64-3.8 gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -Iclips_source -I/Library/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c build/temp.macosx-10.9-x86_64-3.8/_clips.c -o build/temp.macosx-10.9-x86_64-3.8/build/temp.macosx-10.9-x86_64-3.8/_clips.o In file included from build/temp.macosx-10.9-x86_64-3.8/_clips.c:600: /usr/local/include/clips.h:35:10: fatal error: 'setup.h' file not found #include "setup.h" ^~~~~~~~~ 1 error generated. error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-install-0938nd9m/clipspy_349f10090e3049f59c3995983c6b0475/setup.py'"'"'; __file__='"'"'/private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-install-0938nd9m/clipspy_349f10090e3049f59c3995983c6b0475/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/c6/5f3b62j10pj80nf230ypjwvnhrnrdc/T/pip-record-g_kqqipt/install-record.txt --single-version-externally-managed --compile --install-headers /Library/Frameworks/Python.framework/Versions/3.8/include/python3.8/clipspy Check the logs for full command output.
I have been working on an expert system using clipspy recently. A problem I find is whenever I build a rule, all the previous rules are lost and only one rule can be defined. This is what I have tried.
env.clear()
print("initial rule number:",len(list(env.rules()))) # show how rules when initialized
#initial rule number: 0
env.build(init_rule) # build the 1st rule
print("rule number after 1st build:",len(list(env.rules()))) # show how rules after first build
#rule number after 1st build: 1
env.build(trule) # build the 2nd rule
print("rule number after 2nd build:",len(list(env.rules()))) # show how rules after first build
#rule number after 2nd build: 1
If I also tried to merge two rule strs into one, and call env.build() once. It doesn't work.
env.clear()
print("initial rule number:",len(list(env.rules()))) # show how rules when initialized
#initial rule number: 0
two_rules = '\n'.join([init_rule,trule]) # merge two rule strs
env.build(two_rules)
print("rule number after build:",len(list(env.rules()))) # show how rules after build
#rule number after build: 1
I also tried to put these rules into a text file, and use env.load() function to load that file. However there is still one rule I can find.
I really run out of ways to define more than one rule. I am not sure if this is a bug, or maybe there is something I didn't do correctly. Any help is appreciated!
Hi,
I've got following error:
[root@vxe localhost clipspy-0.3.2]# pip install clipspy
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7.
Collecting clipspy
Using cached https://files.pythonhosted.org/packages/ac/ad/d7ad66a0290fbe6401219e84242be5be3cb1cdabac34ba9f4cd76f016678/clipspy-0.3.2.tar.gz
Complete output from command python setup.py egg_info:
fatal: Not a git repository (or any of the parent directories): .git
Installed /tmp/pip-install-W94xoq/clipspy/cffi-1.12.1-py2.7-linux-x86_64.egg
error in clipspy setup command: Invalid environment marker: python_version<'3'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-W94xoq/clipspy/
Why would set up even try to call git? How can I fix that?
Building through make:
make[1]: Leaving directory `/home/slozovsky/CLIPS/clipspy-git/clipspy/clips_source'
ld -G clips_source/*.o -o clips_source/libclips.so
python setup.py build_ext --include-dirs clips_source \
--library-dirs clips_source
error in clipspy setup command: Invalid environment marker: python_version<'3'
make: *** [clipspy] Error 1
Clipspy worked with Python 2.7 before...
Hey there,
I've looked at other threads addressing installation issues and didn't find an answer, probably through my own incompetence, but please stay with me..
I'm trying to install clipspy on my Mac, running os 10.14, with Python 3.7.2. Attempted running "pip install clipspy" and got this error:
build/temp.macosx-10.14-x86_64-3.7/_clips.c:523:10: fatal error: 'clips.h' file not found #include <clips.h> ^~~~~~~~~ 1 error generated. error: command 'clang' failed with exit status 1
I went to https://pypi.org/project/clipspy/#files but could not find a wheel that works.
Downloaded the .tar.gz at the above link and tried: ./pip3 install ~/Downloads/clipspy-0.3.2.tar.gz
which returned the same error as above.
I have the clips source code, I'm just not sure where to place it to circumvent that error. Here is the full terminal error.
`$ ./pip3 install ~/Downloads/clipspy-0.3.2.tar.gz
Processing /Users/paulvajda/Downloads/clipspy-0.3.2.tar.gz
Requirement already satisfied: cffi>=1.0.0 in /usr/local/lib/python3.7/site-packages (from clipspy==0.3.2) (1.12.1)
Requirement already satisfied: pycparser in /usr/local/lib/python3.7/site-packages (from cffi>=1.0.0->clipspy==0.3.2) (2.19)
Building wheels for collected packages: clipspy
Building wheel for clipspy (setup.py) ... error
Complete output from command /usr/local/opt/python/bin/python3.7 -u -c "import setuptools, tokenize;file='/private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-req-build-_yvyr_53/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-wheel-ystgkg_s --python-tag cp37:
fatal: not a git repository (or any of the parent directories): .git
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.14-x86_64-3.7
creating build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/functions.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/facts.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/agenda.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/error.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/init.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/clips_build.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/common.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/environment.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/modules.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/classes.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/router.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/data.py -> build/lib.macosx-10.14-x86_64-3.7/clips
running build_ext
generating cffi module 'build/temp.macosx-10.14-x86_64-3.7/_clips.c'
creating build/temp.macosx-10.14-x86_64-3.7
building '_clips' extension
creating build/temp.macosx-10.14-x86_64-3.7/build
creating build/temp.macosx-10.14-x86_64-3.7/build/temp.macosx-10.14-x86_64-3.7
clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c build/temp.macosx-10.14-x86_64-3.7/_clips.c -o build/temp.macosx-10.14-x86_64-3.7/build/temp.macosx-10.14-x86_64-3.7/_clips.o
build/temp.macosx-10.14-x86_64-3.7/_clips.c:523:10: fatal error: 'clips.h' file not found
#include <clips.h>
^~~~~~~~~
1 error generated.
error: command 'clang' failed with exit status 1
Failed building wheel for clipspy
Running setup.py clean for clipspy
Failed to build clipspy
Installing collected packages: clipspy
Running setup.py install for clipspy ... error
Complete output from command /usr/local/opt/python/bin/python3.7 -u -c "import setuptools, tokenize;file='/private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-req-build-_yvyr_53/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-record-mgouyx3m/install-record.txt --single-version-externally-managed --compile:
fatal: not a git repository (or any of the parent directories): .git
running install
running build
running build_py
creating build
creating build/lib.macosx-10.14-x86_64-3.7
creating build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/functions.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/facts.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/agenda.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/error.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/init.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/clips_build.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/common.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/environment.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/modules.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/classes.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/router.py -> build/lib.macosx-10.14-x86_64-3.7/clips
copying clips/data.py -> build/lib.macosx-10.14-x86_64-3.7/clips
running build_ext
generating cffi module 'build/temp.macosx-10.14-x86_64-3.7/_clips.c'
creating build/temp.macosx-10.14-x86_64-3.7
building '_clips' extension
creating build/temp.macosx-10.14-x86_64-3.7/build
creating build/temp.macosx-10.14-x86_64-3.7/build/temp.macosx-10.14-x86_64-3.7
clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c build/temp.macosx-10.14-x86_64-3.7/_clips.c -o build/temp.macosx-10.14-x86_64-3.7/build/temp.macosx-10.14-x86_64-3.7/_clips.o
build/temp.macosx-10.14-x86_64-3.7/_clips.c:523:10: fatal error: 'clips.h' file not found
#include <clips.h>
^~~~~~~~~
1 error generated.
error: command 'clang' failed with exit status 1
----------------------------------------
Command "/usr/local/opt/python/bin/python3.7 -u -c "import setuptools, tokenize;file='/private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-req-build-_yvyr_53/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-record-mgouyx3m/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/fg/wcnyz_gn7ndb5yf8b26b4dw80000gn/T/pip-req-build-_yvyr_53/
`
Help is much appreciated,
Cheers
if fact1, fact2, fact3 are asserted at the same time, then while using PyCLIPS depending on the order of declaration of rules in my .clp file, rule1 was fired.(because it precedes rule2)
(defrule rule1
(fact 1)
(fact 2)
=> printout t"rule1")
(defrule rule2
(fact 1)
(fact 3)
=> printout t"rule2")
but clipspy
fires both the rules at the same time. This messes up the expert system as there are two ouputs on the screen.
I understand I'll have to (declare (salience __)) in each rule to prioritze rules. This is an extra burden as when my rules increase in number, its hard to keep track of salience numbers.
Is there a way to prioritize rules based on their order in the .clp file.
(clipspy) dwood@dw7470u:~/dev/clipspy$ sudo make install make -f makefile -C clips_source \ CFLAGS="-std=c99 -O3 -fno-strict-aliasing -fPIC" \ LDLIBS="-lm -lrt" make[1]: Entering directory '/home/dwood/dev/clipspy/clips_source' gcc -o clips main.o -L. -lclips -lm -lrt make[1]: Leaving directory '/home/dwood/dev/clipspy/clips_source' ld -G clips_source/*.o -o clips_source/libclips.so python setup.py build_ext Traceback (most recent call last): File "setup.py", line 32, in <module> from setuptools import find_packages, setup ImportError: No module named setuptools make: *** [Makefile:35: clipspy] Error 1
running python setup.py build_ext outside of sudo works without issue.
Hello,
I would like to install clipspy via pip.
Unfortunately it does not work for me with Python 3.10.
With 3.9 it works.
Thanks in advance.
Many greetings!
My installed packages for 3.10. are:
cffi 1.15.1
pip 22.1.2
pycparser 2.21
setuptools 63.2.0
wheel 0.37.1
where setuptools was upgraded with pip before trying to install clipspy.
This is what the console says (VS code with Git Bash):
Collecting clipspy
Using cached clipspy-1.0.0.tar.gz (27 kB)
Preparing metadata (setup.py) ... done
Requirement already satisfied: cffi>=1.0.0 in c:\users...\desktop\test\testing310\lib\site-packages (from clipspy) (1.15.1)
Requirement already satisfied: pycparser in c:\users...\desktop\test\testing310\lib\site-packages (from cffi>=1.0.0->clipspy) (2.21)
Building wheels for collected packages: clipspy
Building wheel for clipspy (setup.py) ... error
error: subprocess-exited-with-error
× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─> [29 lines of output]
running bdist_wheel
running build
running build_py
creating build
creating build\lib.win-amd64-cpython-310
creating build\lib.win-amd64-cpython-310\clips
copying clips\agenda.py -> build\lib.win-amd64-cpython-310\clips
copying clips\classes.py -> build\lib.win-amd64-cpython-310\clips
copying clips\clips_build.py -> build\lib.win-amd64-cpython-310\clips
copying clips\common.py -> build\lib.win-amd64-cpython-310\clips
copying clips\environment.py -> build\lib.win-amd64-cpython-310\clips
copying clips\facts.py -> build\lib.win-amd64-cpython-310\clips
copying clips\functions.py -> build\lib.win-amd64-cpython-310\clips
copying clips\modules.py -> build\lib.win-amd64-cpython-310\clips
copying clips\routers.py -> build\lib.win-amd64-cpython-310\clips
copying clips\values.py -> build\lib.win-amd64-cpython-310\clips
copying clips_init_.py -> build\lib.win-amd64-cpython-310\clips
running build_ext
generating cffi module 'build\temp.win-amd64-cpython-310\Release\_clips.c'
creating build\temp.win-amd64-cpython-310
creating build\temp.win-amd64-cpython-310\Release
building '_clips' extension
creating build\temp.win-amd64-cpython-310\Release\build
creating build\temp.win-amd64-cpython-310\Release\build\temp.win-amd64-cpython-310
creating build\temp.win-amd64-cpython-310\Release\build\temp.win-amd64-cpython-310\Release
"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Iclips_source -IC:\Users...\Desktop\test\testing310\include -IC:\Users...\AppData\Local\Programs\Python\Python310\include -IC:\Users...\AppData\Local\Programs\Python\Python310\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" /Tcbuild\temp.win-amd64-cpython-310\Release_clips.c /Fobuild\temp.win-amd64-cpython-310\Release\build\temp.win-amd64-cpython-310\Release_clips.obj
_clips.c
build\temp.win-amd64-cpython-310\Release_clips.c(570): fatal error C1083: Datei
(Include) kann nicht ge”ffnet werden: "clips.h": No such file or directory
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe' failed with exit code 2
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for clipspy
Running setup.py clean for clipspy
Failed to build clipspy
Installing collected packages: clipspy
Running setup.py install for clipspy ... error
error: subprocess-exited-with-error
× Running setup.py install for clipspy did not run successfully.
│ exit code: 1
╰─> [31 lines of output]
running install
C:\Users...\Desktop\test\testing310\lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running build
running build_py
creating build
creating build\lib.win-amd64-cpython-310
creating build\lib.win-amd64-cpython-310\clips
copying clips\agenda.py -> build\lib.win-amd64-cpython-310\clips
copying clips\classes.py -> build\lib.win-amd64-cpython-310\clips
copying clips\clips_build.py -> build\lib.win-amd64-cpython-310\clips
copying clips\common.py -> build\lib.win-amd64-cpython-310\clips
copying clips\environment.py -> build\lib.win-amd64-cpython-310\clips
copying clips\facts.py -> build\lib.win-amd64-cpython-310\clips
copying clips\functions.py -> build\lib.win-amd64-cpython-310\clips
copying clips\modules.py -> build\lib.win-amd64-cpython-310\clips
copying clips\routers.py -> build\lib.win-amd64-cpython-310\clips
copying clips\values.py -> build\lib.win-amd64-cpython-310\clips
copying clips_init_.py -> build\lib.win-amd64-cpython-310\clips
running build_ext
generating cffi module 'build\temp.win-amd64-cpython-310\Release\_clips.c'
creating build\temp.win-amd64-cpython-310
creating build\temp.win-amd64-cpython-310\Release
building '_clips' extension
creating build\temp.win-amd64-cpython-310\Release\build
creating build\temp.win-amd64-cpython-310\Release\build\temp.win-amd64-cpython-310
creating build\temp.win-amd64-cpython-310\Release\build\temp.win-amd64-cpython-310\Release
"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Iclips_source -IC:\Users...\Desktop\test\testing310\include -IC:\Users...\AppData\Local\Programs\Python\Python310\include -IC:\Users...\AppData\Local\Programs\Python\Python310\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\cppwinrt" /Tcbuild\temp.win-amd64-cpython-310\Release_clips.c /Fobuild\temp.win-amd64-cpython-310\Release\build\temp.win-amd64-cpython-310\Release_clips.obj
_clips.c
build\temp.win-amd64-cpython-310\Release_clips.c(570): fatal error C1083: Datei (Include) kann nicht ge”ffnet werden: "clips.h": No such file or directory
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe' failed with exit code 2
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
× Encountered error while trying to install package.
╰─> clipspy
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.