aluriak / clyngor Goto Github PK
View Code? Open in Web Editor NEWHandy python wrapper around Potassco's Clingo ASP solver.
License: GNU General Public License v3.0
Handy python wrapper around Potassco's Clingo ASP solver.
License: GNU General Public License v3.0
Example:
import clyngor
clyngor.use_clingo_module()
for m in clyngor.solve(inline='b(X):- c(X).'):
print(m)
If I have soft constraints, this library gives me multiple results and also does not return the penalty for the different optimizations.
I saw yield_stats
but it's not passed through from clyngor.solve
.
Hi, when I run the following program as given as an official example
from clyngor import solve
answers = solve(inline="""
rel(a,(c;d)). rel(b,(d;e)).
obj(X):- rel(X,_) ; rel(X,Y): att(Y).
att(Y):- rel(_,Y) ; rel(X,Y): obj(X).
:- not obj(X):obj(X).
:- not att(Y):att(Y).
""")
for answer in answers:
print(answer)
I get the following error
Traceback (most recent call last):
File "clyngor_example.py", line 11, in <module>
for answer in answers:
File "/home/theo/.local/lib/python3.8/site-packages/clyngor/answers.py", line 205, in __iter__
for answer_set, optimization, optimality, answer_number in self._answers:
File "/home/theo/.local/lib/python3.8/site-packages/clyngor/answers.py", line 327, in __compute_answers
with self._solver.solve(**kwargs) as models:
TypeError: solve() got an unexpected keyword argument 'async'
I've tried setting use_clingo_module=False
and specifying clingo_bin_path
as suggested in another issue, but this gives me the error
Traceback (most recent call last):
File "/home/theo/.local/lib/python3.8/site-packages/clyngor/parsing.py", line 197, in parse_clasp_output
line = next(output)
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "clyngor_example.py", line 11, in <module>
for answer in answers:
File "/home/theo/.local/lib/python3.8/site-packages/clyngor/answers.py", line 205, in __iter__
for answer_set, optimization, optimality, answer_number in self._answers:
File "/home/theo/.local/lib/python3.8/site-packages/clyngor/solving.py", line 208, in _gen_answers
for ptype, payload in parse_clasp_output(stdout, yield_stats=True):
RuntimeError: generator raised StopIteration
Please let me know if you have any suggestions on how I can get this example working. Thank you in advance
Platform:
Clyngor version: f3f38b7 (head of master at time of writing)
Clingo version: clingo 3.0.5 (clasp 1.3.10)
Python version: Python 3.8.10
This is the error I get while using it. The have_clingo_module is infact present in the clyngor library but still python pops this error out. Besides there are other bugs like Raise(error) command has string written outside of inverted commas, and this gives error when I initally tried to import clyngor. I manually corrected each raise error.
Traceback (most recent call last):
File "<ipython-input-19-705a45273486>", line 7, in <module>
""")
File "C:\Users\HARSHIT\Anaconda3\lib\site-packages\clyngor\inline.py", line 17, in ASP
return solve(inline=source_code, stats=False, **kwargs)
File "C:\Users\HARSHIT\Anaconda3\lib\site-packages\clyngor\solving.py", line 66, in solve
use_clingo_module = use_clingo_module and clyngor.have_clingo_module() and not return_raw_output
AttributeError: module 'clyngor' has no attribute 'have_clingo_module'
Careful parsing should be the default choice in 0.4.0
In 0.3.x though, it could be activated if:
(
is followed by a (
, not a )
)The former is easy to test. The latter is harder,
but together will match most cases where the naive parsing is not enough.
Pyasp supports having a str and a int as arguments for an atom (Term). Apparently clyngor.as_pyasp does not. Here is a MWE:
from pyasp import *
from clyngor.as_pyasp import TermSet, Atom
elem = 'plop'
weight = 2
cofactors_pyasp = Term('cofactor', ["\""+elem+"\"",+weight])
cofactors_clyngor = Atom('cofactor', ["\""+elem+"\"",+weight])
print(cofactors_pyasp)
print(cofactors_clyngor)
gives the following error for the clyngor version:
Traceback (most recent call last):
File "../menetools/test_print.py", line 10, in <module>
print(cofactors_clyngor)
File "/Users/cfrioux/wd/scripts/MeneTools/venv_clyngor/lib/python3.7/site-packages/clyngor/as_pyasp.py", line 32, in __str__
return '{}({})'.format(self.predicate, ','.join(self.arguments))
TypeError: sequence item 1: expected str instance, int found
whereas the pyasp version gives:
cofactor("plop",2)
The following interface should be implemented:
model = next(models.by_predicate)
# currently, to access atom/2 atoms, we need that:
for args in model['atom']:
if len(args) == 2: print(args)
# a more direct access would be
print(model['atom', 2])
# or
print(model['atom/2'])
Something like:
import clyngor
gringo_output = clyngor.ground('a.')
clyngor.solve_from_grounded(gringo_output)
gringo_output
could probably only be a string.
Hello, I tried running your example use for clyngor and it raised this error. Its weird since if I try to use clingo python API example it also raises an error for clingo.Control()
Any ideas? Im really looking forward to use clyngor in a production enviroment
Why doesn't this library parse the JSON output rather than the raw string output from clingo?
When providing an unsatisfiable problem, the statistics
property appears to be an empty dictionary, despite clasp returning them.
For example, here's an example output:
Models : 0
Calls : 1
Time : 0.346s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.346s
Choices : 0
Conflicts : 1 (Analyzed: 0)
Restarts : 0
Problems : 0 (Average Length: 0.00 Splits: 0)
Lemmas : 0 (Deleted: 0)
Binary : 0 (Ratio: 0.00%)
Ternary : 0 (Ratio: 0.00%)
Conflict : 0 (Average Length: 0.0 Ratio: 0.00%)
Loop : 0 (Average Length: 0.0 Ratio: 0.00%)
Other : 0 (Average Length: 0.0 Ratio: 0.00%)
Backjumps : 0 (Average: 0.00 Max: 0 Sum: 0)
Executed : 0 (Average: 0.00 Max: 0 Sum: 0 Ratio: 0.00%)
Bounded : 0 (Average: 0.00 Max: 0 Sum: 0 Ratio: 100.00%)
Rules : 136938 (Original: 87956)
Choice : 1081
Atoms : 56052 (Original: 50148 Auxiliary: 5904)
Bodies : 73042 (Original: 68196)
Count : 2616 (Original: 3818)
Equivalences : 15751 (Atom=Atom: 2795 Body=Body: 2737 Other: 10219)
Tight : Yes
Variables : 10544 (Eliminated: 0 Frozen: 3404)
Constraints : 0 (Binary: 0.0% Ternary: 0.0% Other: 0.0%)
It would be interesting to keep them, so we could know when a problem has no solutions because of timeout (when providing a time limit) or because of unsatisfiability.
The MANIFEST.in
makes reference to a license file, but that file is not in the repository. There is currently an effort underway to package clyngor
on conda-forge (conda-forge/staged-recipes#11306), and it would be helpful, if possible to:
Allowing to call program with CLINGO_PATH=./clingo python script-that-uses-clyngor.py
asp = '_rel(a,b).'
import clyngor
models = clyngor.solve(inline=asp).careful_parsing
model = next(models)
assert next(models, None) is None
assert len(model) == 1, model
assert model == {('_rel', ('a', 'b'))}
Clingo binary is currently expected to be installed by the end-user.
Whatabout:
clyngor-clingo
package that is just pushing a stored clingo binary to /bin
?python -m clyngor install-clingo
or something alike ?Hello,
when the clingo package is installed in python, Clyngor will use the propagator and the ClingoAnswers by default. This is because the use_clingo_module variable in solving.py is by default set to True and the clingo package check with have_clingo_module() wil return something because "import clingo" raises no error.
Then when we use Clyngor to solve and parse answers, the script will return results without applying the answer functions (like int_not_parsed
or with_optimization
) because the script uses the class ClingoAnswers instead of the class Answers. And the __iter__
function of ClingoAnswers have a different behaviour than the function of Answers.
I think this happens when a user install Clingo with the conda command: conda install -c potassco clingo
And encapsulation:
import clyngor
example_solver = clyngor.solve(inline='a(1). e(X):- a(X).')
for answer in example_solver.sorted.atoms_as_string:
print(answer)
Results are (with clingo installed):
(('a', (1,)), ('e', (1,)))
Results are (after deleting clingo so deleting /path/to/lib/python3.6/site-packages/clingo.cpython-36m-x86_64-linux-gnu.so
):
('a(1)', 'e(1)')
We see that the atoms_as_string function was not applied with clingo python package installed.
One way to solve this is by setting the variable use_clingo_module
to False when calling the solver.
Describe the bug
When I run an example from the official website, I get the error:
Traceback (most recent call last):
File "/home/axiong/PycharmProjects/ASP/clyngor/test1.py", line 1, in
from clyngor import ASP,solve
File "/home/axiong/PycharmProjects/ASP/venv/lib/python3.5/site-packages/clyngor/init.py", line 5, in
from clyngor.answers import Answers, ClingoAnswers
File "/home/axiong/PycharmProjects/ASP/venv/lib/python3.5/site-packages/clyngor/answers.py", line 293
mapping[f'{pred}/{len(args)}'].add(args)
^
SyntaxError: invalid syntax
To Reproduce
I used pycharm and created a new python file:
from clyngor import ASP,solve
answers = ASP("""
rel(a,(c;d)). rel(b,(d;e)).
obj(X):- rel(X,_) ; rel(X,Y): att(Y).
att(Y):- rel(_,Y) ; rel(X,Y): obj(X).
:- not obj(X):obj(X).
:- not att(Y):att(Y).
""")
for answer in answers:
print(answer)
My Platform
ubuntu16.04; python3.5;pycharm.
Additional context
I found the following: ~/site-packages/clyngor/answers.py.
Question code on line 293:
mapping[f'{pred}/{len(args)}'].add(args)
I changed the code to:
mapping['{pred}/{len(args)}'].add(args)
.
This will run the code. But I'm a freshman, and I don't know what the consequences will be.
Hello,
I have an issue while using Clyngor to encapsulate ASP files (which also use python implementation). The python implementation in ASP is used to select some atoms in the answer and to write these atoms in a file. The ASP encoding and fact have been tested with Clingo (version 5.2.2 compiled with Python) and it works, the file is created.
Clyngor achieves to create the file but there is a delay in the creation of the file. Indeed the file is not accessible right after the solver call. If I try to use the file, I have an error saying that the file doesn't exist. But when the script ends, the file exists.
I write a simple example, with encoding and fact files (which are working with my Clingo) and a python script with Clyngor which creates the file but runs into an error when trying to access the file with the print(file.read())
.
The ASP encoding extracts a number from a predicate with two numbers, assign it to another predicate and then write the new predicate in a file.
Example:
Python script:
import clyngor
clyngor.solve(('test.lp', 'data.lp'))
print(open('resultfile.lp').read())
Encoding file:
#script (python)
import clingo
def on_model(answer, output_file):
atoms=answer.symbols(atoms=True)
for atom in atoms:
if atom.name == "count" and len(atom.arguments) == 1:
output_file.write( "count("+str(atom.arguments[0])+").\n")
def main(prg):
output_file = open("resultfile.lp", "w")
prg.ground([("base", [])])
for answer_number, answer in enumerate(prg.solve(yield_=True, async=True), start=1):
print(answer)
on_model(answer, output_file)
output_file.close()
#end.
count(X) :- query(X, A).
data.lp
:
query(1,2).
query(2,3).
query(4,5).
As shown here, statistics access is different whether clyngor is using clingo module or just parsing its output.
This is due to the fact that using the clingo module, clyngor uses the API objects encapsulating the final statistics, whereas without the clingo module it parses the output, building the model.statistics
dictionnary using clingo's stdout.
In order to clyngor to reach production-grade concerning that aspect of clingo, we need to choose a data structure to encapsulate the statistics data (either a dict, or something looking like the object of clingo's API, or something else), and convert the obtained statistics to that data structure.
When using answers.atom_as_string.sorted
atoms are still put into a frozenset, as if the sorted flag was ignored. Bad.
It would be nice if clyngor was available as a conda package through https://conda-forge.org/. Clingo has a conda package.
The function "to_file" in file as_pysasp use module tempfile which is not imported.
The program can be passed via stdin if there are no other files needed. It would be nice to support this to speed up solving.
When using both options, only atom as string is considered.
Dear Lucas
This is brilliant. Thank you very much for making it open-source!
Is there a way to get an indication of the number of models generated? If I run clingo on the commandline with a set number of models, clingo will tell me if there are more models available, e.g.:
$ clingo -n 500 program.lp
clingo version 5.4.0
Reading from program.lp
Solving...
...
SATISFIABLE
Models : 500+
Calls : 1
Time : 0.002s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time : 0.002s
The "+" in "Models: 500+" tells me there are more than 500 possibilities. Can I access that kind of info via Clyngor?
Thanks again
Ivan
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.