Coder Social home page Coder Social logo

aluriak / clyngor Goto Github PK

View Code? Open in Web Editor NEW
33.0 6.0 7.0 411 KB

Handy python wrapper around Potassco's Clingo ASP solver.

License: GNU General Public License v3.0

Makefile 0.39% Python 99.61%
answer-set-programming wrapper python python-library python3

clyngor's People

Contributors

aluriak avatar arnaudbelcour avatar barreeeiroo avatar domoritz avatar marwahaha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

clyngor's Issues

Support for optimize

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.

TypeError: solve() got an unexpected keyword argument 'async'

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

Unable to get it working on my python module

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'

Autodetect when it is necessary to use careful parsing.

Careful parsing should be the default choice in 0.4.0
In 0.3.x though, it could be activated if:

  • there is nested parenthesis (i.e. ( is followed by a (, not a ))
  • there is a paren between two double-quotes

The former is easy to test. The latter is harder,
but together will match most cases where the naive parsing is not enough.

__str__ method of Atom in as_pyasp fails if arguments are of different types

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)

Access to atoms dict through name and arity

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'])

AttributeError: module 'clingo' has no attribute 'Control'

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

Use JSON output

Why doesn't this library parse the JSON output rather than the raw string output from clingo?

Keep statistics when UNSATISFIABLE

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.

Missing license file

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:

  1. Clarify which version of GPL licenses this package
  2. Add a license file so that it's included in the source distribution.

Easy installation of clingo binary

Clingo binary is currently expected to be installed by the end-user.

Whatabout:

  • a clyngor-clingo package that is just pushing a stored clingo binary to /bin ?
  • an automated installation routine callable with python -m clyngor install-clingo or something alike ?

Parsing answer difficulties when python clingo is installed

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.

When running python file: mapping[f'{pred}/{len(args)}'].add(args)

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.

Delay in file creation with Python implementation in ASP

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).

A model for clingo's statistics

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.

How to get info on number of models generated?

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.