Git Product home page Git Product logo

clingo's Introduction

Clingo: A grounder and solver for logic programs

Clingo is part of the Potassco project for Answer Set Programming (ASP). ASP offers a simple and powerful modeling language to describe combinatorial problems as logic programs. The clingo system then takes such a logic program and computes answer sets representing solutions to the given problem. To get an idea, check our Getting Started page and the online version of clingo.

Please consult the following resources for further information:

Clingo is distributed under the MIT License.

clingo's People

Contributors

0x326 avatar adamjstewart avatar bartbog avatar benkaufmann avatar domoritz avatar haampie avatar horrowind avatar javier-romero avatar joshessman-llnl avatar maxostrowski avatar mgebser avatar morxa avatar pluehne avatar qyanu avatar rkaminsk avatar sthiele avatar timn avatar trws 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  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  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  avatar  avatar  avatar  avatar

Watchers

 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  avatar  avatar

clingo's Issues

Linking on Intel 32-bit fails

: && /usr/bin/clang++  -march=i686 -mtune=generic -O2 -pipe -fstack-protector-strong -fno-plt -O3 -DNDEBUG  -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now   -rdynamic clasp/app/CMakeFiles/clasp.dir/clasp_app.cpp.o clasp/app/CMakeFiles/clasp.dir/main.cpp.o  -o bin/clasp  -Wl,-rpath,:::::::: lib/libclasp.a -lpthread lib/libpotassco.a && :
lib/libclasp.a(minimize_constraint.cpp.o): In function `Clasp::SharedMinimizeData::resetBounds()':
/build/clingo/src/clingo-5.2.0/clasp/src/minimize_constraint.cpp:(.text+0x1cc): undefined reference to `__atomic_store_8'

Using g++ instead of clang++ works, most likely C++-11 atomics are missing for certain data
types in clangs C++ library.

Extend the interface to inspect the grounded program.

Some application might require to inspect the output of the grounder to obtain, e.g., dependency information. This could be implemented by registering a set of callbacks with a control object. Registration could be handled similarly like registering a propagator; the callbacks should have a similar form as the clingo_backend_* functions.

cmake shows no warning and pyclingo module is built but does not work if python3-dev is missing

I have observed this with python3 on Ubuntu 16.04, but maybe it is also true with python2 and on later versions.

If I do not have python3-dev installed (maybe the real requirement is libpython3-dev) then cmake configures nicely for python3 and the build also succeeds and make install yields a nice clingo*.so file that has no PyInit_clingo therefore any import will fail.

Installing python3-dev and rebuilding fixes the problem.

add_nogood Function

There is a add_nogood method in the propagate control class in the python interface but neither in the C or C++ interface.

Failed to build `wip` branch in CentOS 7

Build wip branch in CentOS 7 failed with following error:

[ 47%] Building CXX object libgringo/CMakeFiles/libgringo.dir/src/ground/instantiation.cc.o
cd /home/dram/potassco/clingo/build/debug/libgringo && /usr/bin/c++    -I/home/dram/potassco/clingo/libgringo -I/home/dram/potassco/clingo/build/debug/libgringo/src -I/home/dram/potassco/clingo/clasp/libpotassco -I/home/dram/potassco/clingo/libreify  -g -fPIC -fvisibility=hidden   -std=c++11 -o CMakeFiles/libgringo.dir/src/ground/instantiation.cc.o -c /home/dram/potassco/clingo/libgringo/src/ground/instantiation.cc
In file included from /home/dram/potassco/clingo/libgringo/gringo/output/statements.hh:29:0,
                 from /home/dram/potassco/clingo/libgringo/gringo/output/output.hh:29,
                 from /home/dram/potassco/clingo/libgringo/src/ground/instantiation.cc:26:
/home/dram/potassco/clingo/libgringo/gringo/output/literals.hh:504:22: error: function ‘Gringo::Output::DisjointElement& Gringo::Output::DisjointElement::operator=(Gringo::Output::DisjointElement&&)’ defaulted on its first declaration with an exception-specification that differs from the implicit declaration ‘Gringo::Output::DisjointElement& Gringo::Output::DisjointElement::operator=(Gringo::Output::DisjointElement&&)’
     DisjointElement &operator=(DisjointElement &&) noexcept = default;
                      ^
/home/dram/potassco/clingo/libgringo/gringo/output/literals.hh:524:19: error: function ‘Gringo::Output::DisjointAtom& Gringo::Output::DisjointAtom::operator=(Gringo::Output::DisjointAtom&&)’ defaulted on its first declaration with an exception-specification that differs from the implicit declaration ‘Gringo::Output::DisjointAtom& Gringo::Output::DisjointAtom::operator=(Gringo::Output::DisjointAtom&&)’
     DisjointAtom &operator=(DisjointAtom &&) noexcept = default;
                   ^
make[3]: *** [libgringo/CMakeFiles/libgringo.dir/src/ground/instantiation.cc.o] Error 1
make[3]: Leaving directory `/home/dram/potassco/clingo/build/debug'
make[2]: *** [libgringo/CMakeFiles/libgringo.dir/all] Error 2
make[2]: Leaving directory `/home/dram/potassco/clingo/build/debug'
make[1]: *** [all] Error 2
make[1]: Leaving directory `/home/dram/potassco/clingo/build/debug'
make: *** [all] Error 2

Performance Issue - Clingo in concurrent threads

Hello,
I am using Clingo 4.5.3 which is assumed to be considered as a stream reasoner. The idea is to feed the incremental ASP solver with the data that is continuously coming from a number of sensors. In order to model such system, I have implemented two concurrent threads in Java. The first thread reads the database table at each second to fetch the newly arrived data and share it with the second thread which has initialized clingo and is waiting to feed it with the data. This model works fine only during the first two minutes after running the threads. The second thread starts to get slower after about 2 minutes (~ timestampe 200) and thus causes considerable delays in reading and parsing the sensor data in real time.
However, when I run the solver alone and feed it manually (not through threads) it quickly solves the program with the given data and without getting slower even at timestamps larger than 200.

I appreciate if you let me know how to deal with the performance issue, or any hints about modeling or initializing the solver.
Best

Unexpected output in GroundProgramObserver::output_atom

Hello,

I think the following program:


#include <clingo.hh>
#include <iostream>

using namespace Clingo;

void solve(Control &ctl) {
    for (auto m : ctl.solve_iteratively()) {
        std::cout << "Model:";
        for (auto &atom : m.symbols()) {
            std::cout << " " << atom;
        }
        std::cout << "\n";
    };
}

class MyObserver: public GroundProgramObserver {
    virtual void output_atom(Clingo::Symbol symbol, atom_t atom) override {
        std:: cout <<"ATOM_ID: "<<  atom << std::endl;
        std:: cout <<"SYMBOL: " << symbol.to_string() << std::endl;
    }
};

int main(int argc, char const **argv) {
    try {
        Logger logger = [](WarningCode, char const *message) {
            std::cerr << message << std::endl;
        };

        MyObserver obs;
        Control ctl{{argv+1, size_t(argc-1)}, logger, 20};
        ctl.register_observer(obs);
        ctl.add("base", {}, "y(X) :- not b(X),p(X). b(X) :- not y(X),p(X). p(1). y(1).");
        ctl.ground({{"base", {}}});
        solve(ctl);
    }
    catch (std::exception const &e) {
        std::cerr << "example failed with: " << e.what() << std::endl;
    }
}

does not output expected atom ids in output_atom(Clingo::Symbol symbol, atom_t atom) override.

What I see is
ATOM_ID: 0
SYMBOL: p(1)
ATOM_ID: 0
SYMBOL: y(1)
Model: p(1) y(1)

So all atom_ids are 0's. I expect them to be different (and to be equal to those which I see in GroundProgramObserver::rule callback). Am I wrong?

Run time error when printing a model

Hello!

For some reason, the following code:

#include <clingo.hh>
#include <iostream>

using namespace Clingo;

Clingo::Symbol find_ex_symbol(const Control &ctl) {
    Clingo::SymbolicAtoms ats = ctl.symbolic_atoms();
    for(auto at: ats) {
        if(!strcmp(at.symbol().name(),"ex")) {
            return at.symbol();
        }
    }
    throw std::logic_error("no ex found:(");
}

int main(int argc, char const **argv) {
    try {
        Logger logger = [](WarningCode, char const *message) {
            std::cerr << message << std::endl;
        };
        Control ctl{{argv+1, size_t(argc-1)}, logger, 20};
        ctl.add("base", {}, "#external ex. a :- ex. b. ");
        ctl.ground({{"base", {}}});
        SolveIteratively solveit = ctl.solve_iteratively();
        Model m = solveit.next();
        solveit.close();
        std::cout << m << std::endl;
        Symbol ex_symb = find_ex_symbol(ctl);
        ctl.assign_external(ex_symb,TruthValue::True);
        std::cout << m << std::endl;
    }
    catch (std::exception const &e) {
        std::cerr << "example failed with: " << e.what() << std::endl;
    }
}

crashes when m is being printed for the second time with the following error:

ex: /work/plog/clingo/libclasp/clasp/enumerator.h:46: Clasp::ValueRep Clasp::Model::value(Clasp::Var) const: Assertion hasVar(v)' failed.
`

Am I am doing something wrong again?
Is there a way to keep the model intact after assigning externals/doing some other operations on the control?
Thanks!

The --outf option is not mentioned in the --help text

Hi,

The --help text does not contain information on how to obtain the answer set in a more machine-readable format. In the pdf guide, I found that I can use --outf for this :)
Something to add to --help?

Thx!
Broes

Call to Clingo::Control::symbolic_atoms() fails after replacing GroundProgramObserver?

Hello,

For some reason the following program:


#include <clingo.hh>
#include <iostream>

using namespace Clingo;


class MyObserver: public GroundProgramObserver {
    virtual void output_atom(Clingo::Symbol symbol, atom_t atom) override {
        std:: cout <<"ATOM_ID: "<<  atom << std::endl;
        std:: cout <<"SYMBOL: " << symbol.to_string() << std::endl;
    }
};

int main(int argc, char const **argv) {
    try {
        Logger logger = [](WarningCode, char const *message) {
            std::cerr << message << std::endl;
        };

        MyObserver obs;
        Control ctl{{argv+1, size_t(argc-1)}, logger, 20};
        ctl.register_observer(obs);
        ctl.add("base", {}, " q(a). p(a).");
        ctl.ground({{"base", {}}});
        ctl.solve();
        ctl.symbolic_atoms();
        std:: cout << "OK1" << std::endl;
        GroundProgramObserver dummy_obs2;
        ctl.register_observer(dummy_obs2, true);
        ctl.symbolic_atoms();
        std::cout << "OK2";
    }
    catch (std::exception const &e) {
        std::cerr << "example failed with: " << e.what() << std::endl;
    }
}

crashes when reaching the second occurrence of

ctl.symbolic_atoms();

(So I don't see "OK2" printed)
The exception message is as follows:
domain introspection only supported in clingo mode

Is this an intended behavior?
Is there a way I can look at symbolic atoms after updating the observer?

Thanks!

confusing result of weak constraint

results of programs with weak constraints confuse me, for example:

a | b .
:~ a. [2@1]
:~ b. [1@1]

according to semantics of weak constraints, the optimal answer sets should be {b}, but output of clingo is
lwoc j 5 9 o zwg_4

the command line I used is clingo file

Segfault caused by some exceptions in Python

The following program works nicely, also exceptions test1 and test2 behave as expected (they are passed through and arrive again at the toplevel Python where they abort the program).

However, if I activate exception test3 this causes a segfault instead of passing on and printing the exception.

#!/usr/bin/python3

import clingo

def main(prg):
    def on_model(m):
        print("on_model got model "+str(m))
        #raise Exception("test1")

    class GroundProgramObserver:
      def begin_step(self):
        print("gpo begin")
        #raise Exception("test2")
      def end_step(self):
        print("gpo end")
        #raise Exception("test3")

    prg.configuration.solve.models = 0 
    prg.add("base", [], "2 { a; b; c; d }.")
    obs = GroundProgramObserver()
    prg.register_observer(obs)
    prg.ground([("base", [])])
    prg.solve(on_model=on_model)

main(clingo.Control())

The backtrace in gdb is as follows (built using clingo release 5.2.0 package and Python 3.5.2 on Ubuntu 16.04):

gpo begin
gpo end

Program received signal SIGSEGV, Segmentation fault.
0x00000000005bb65a in PyErr_Fetch ()
(gdb) bt
#0  0x00000000005bb65a in PyErr_Fetch ()
#1  0x00007ffff636133f in (anonymous namespace)::handle_cxx_error_(std::__cxx11::basic_ostringstream<char, std::char_traits<char>, std::allocator<char> >&) [clone .constprop.550] () from /home/ps/.hexlite/lib/libpyclingo.so.1
#2  0x00007ffff6361a90 in (anonymous namespace)::handle_cxx_error(char const*, char const*) ()
   from /home/ps/.hexlite/lib/libpyclingo.so.1
#3  0x00007ffff637c40f in (anonymous namespace)::observer_end_step(void*) () from /home/ps/.hexlite/lib/libpyclingo.so.1
#4  0x00007ffff5e3b528 in (anonymous namespace)::Observer::endStep() () from /home/ps/.hexlite/lib/libclingo.so.1
#5  0x00007ffff5ed5301 in Gringo::Output::(anonymous namespace)::BackendTee::endStep() ()
   from /home/ps/.hexlite/lib/libclingo.so.1
#6  0x00007ffff5edbb56 in Gringo::Output::OutputBase::endStep(bool, Gringo::Logger&) ()
   from /home/ps/.hexlite/lib/libclingo.so.1
#7  0x00007ffff5e32197 in Gringo::ClingoControl::prepare(std::vector<std::pair<Gringo::Symbol, bool>, std::allocator<std::pair<Gringo::Symbol, bool> > >&&) () from /home/ps/.hexlite/lib/libclingo.so.1

With Python 2 I also observe such segfaults, I did not test if they occur in the same functions, though. But in some places, throwing exceptions clearly works, in some places it clearly does not.

Python: Problems narrowing answer set when grounding incrementally

Introduction

I am currently working on an answer set programming project. For the project, I would like to assert facts over time into an ASP model and incrementally solve for an answer. For a simple use case example, consider a Mastermind game:

Example of problem

The game consists of a player and a score-keeper. In the game, a solution is generated by the score-keeper and the player makes guesses as to what the solution is. For each guess, the player is given feedback on his guess, where he uses it to sharpen his vision of the answer and makes another guess.

Presently, we have this game played between two computers in the following form:

  1. Computer A generates a solution and Computer B makes a random guess.
  2. Computer A computes the proper feedback of the first guess
  3. Computer B receives the feedback and solves with clingo with the Python API
    • Computer B creates a new instance of the clingo.Control class
    • Computer B loads the ASP model for mastermind via clingo.Control.load(filename: str) -> None
    • Computer B asserts the previous guess and its feedback as ASP facts via clingo.Control.add(program_name: str, program_arguments: tuple, asp_code_snippet: str) -> None
    • Computer B grounds via clingo.Control.ground(programs: list) -> None
    • Computer B solves via clingo.Control.solve(on_model=lambda model: None) -> None
    • Computer B inspects the answer set via the on_model callback
    • Computer B sends another guess based on what clingo predicts the solution is
  4. Computer A computes feedback
  5. Computer B destroys the previous clingo.Control instance, creates a new one, and continues with all of the steps in item 3.

However, looking at item 5, we thought that destroying a clingo instance just to recreate it is inefficient. I am trying to figure out how to maintain one instance of clingo.

Steps taken to resolve problem

So, to replace item 5, I configured Computer B to add the next guess and its feedback via clingo.Control.add(program_name: str, program_arguments: tuple, asp_code_snippet: str) -> None and to ground everything again so that the assertions could be realized by clingo. However when I do this, I get ambiguous RuntimeError errors with the message redefinition of atom <'_', 20>. I have narrowed its cause to a generative clause like the one below.

After encountering this, it occurred to me that I was grounding too much and cut back to grounding everything only once. However, when doing this, the clingo model becomes stupid in response to the second guess and its feedback. It begins to think that every possible permutation is a valid guess and ignores the constraints put in place, which leads to believe I am now not grounding enough.

However, I cannot find a happy medium. I figure I am not understanding something about the grounding fully. Do any of you know what's up with this?

Steps to reproduce errors

Errors of the form: RuntimeError: redefinition of atom <'XXX', YYY>

Given the clingo test file:

#program program_a.
foo(1..3).

#program program_b.
bar(1..3).

#program program_c.
1 { foobar(Foo, Bar) : bar(Bar) } 1 :- foo(Foo).

#program program_d.
:- foobar(1, 1).

#program program_e.
barbar(A, B) :- foobar(A, B).

Run the following Python 3 script:

#!/usr/bin/python3
"""
Tests which ASP programs cause problems when grounding twice.
This program grounds all ASP programs once, then tests every
combination of ASP programs with further grounding.

Note: this script uses Python 3.

``clingo --version``::

    clingo version 5.2.0
    Address model: 64-bit
    
    libgringo version 5.2.0
    Configuration: with Python 3.5.2, with Lua 5.3.1
    
    libclasp version 3.3.0 (libpotassco version 1.0.0)
    Configuration: WITH_THREADS=1
    Copyright (C) Benjamin Kaufmann
    
    License: The MIT License <https://opensource.org/licenses/MIT>

"""

import itertools
import logging
import os
from collections import namedtuple

import clingo

ASPProgram = namedtuple('ASPProgram', 'name, arguments')
logging.basicConfig(level=logging.INFO, filename='clingo.log')

def log_answer_set(clingo_model):
    # type: (clingo.Model) -> None
    logging.info('New model')
    answer_set = model.symbols(shown=True)
    logging.debug('Answer set: %s', answer_set)
    for answer in answer_set:
        logging.debug(answer)
    
if __name__ == '__main__':
    logging.info('=====Start of test=====')
    asp_programs = (
        ASPProgram(name='program_a', arguments=tuple()),
        ASPProgram(name='program_b', arguments=tuple()),
        ASPProgram(name='program_c', arguments=tuple()),
        ASPProgram(name='program_d', arguments=tuple()),
        ASPProgram(name='program_e', arguments=tuple()),
    )
    
    program_combinations_that_yield_no_errors = list()
    for combination_length in reversed(range(1, len(asp_programs) + 1)):
        print('Trying combinations of length %d' % combination_length)
        for programs in itertools.combinations(asp_programs, combination_length):
        
            try:
                logging.info('Grounding once')
                clingo_control = clingo.Control(['-t %d' % os.cpu_count()])
                clingo_control.load('./path/to/test_clingo_file.lp')
                clingo_control.ground(asp_programs)  # Ground all programs first time
                logging.info('Grounded once without crashing!')
                clingo_control.solve(on_model=log_answer_set)
                try:
                    logging.info('Grounding twice')
                    clingo_control.ground(programs)
                    logging.info('Grounded twice without crashing!')
                    clingo_control.solve(on_model=log_answer_set)
                    program_combinations_that_yield_no_errors.append(programs)
                except RuntimeError as error:
                    logging.info('Failed on second grounding with %s', programs)
                    logging.exception(error)
            except RuntimeError as error:
                logging.error('Failed on first grounding with %s!' % asp_programs)
                raise error
                
        if len(program_combinations_that_yield_no_errors) > 0:
            print('Found combination of ASP programs that did not yield errors!')
            break
    
    best_program_combination = tuple()
    
    print()
    for combination_number, combination in enumerate(program_combinations_that_yield_no_errors):
        logging.info('Working combination %d: %s', combination_number + 1, combination)
        
        print('Combination %d:' % (combination_number + 1))
        for asp_program in combination:
            print(asp_program.name)
        print()
        
        if len(combination) > len(best_program_combination):
            best_program_combination = combination
    
    logging.info('Longest combination: %s', best_program_combination)
    logging.info('=====End of test=====')

The above script can ground program_a, program_b, and program_d a second time without errors. If grounding all of them twice, the following error is raised:

RuntimeError: redefinition of atom <'barbar(1,2)',12>

Bug in parse_program function with #inf and #sup

Hola!

At
clingo/examples/gringo/ast
If I add the line to example.lp:
a(#inf,#sup).
Then with
gringo --text visitor.lp
I get at the output:
a(#sup,#inf,0). a(#sup,#inf,1). a(#sup,#inf,2).
The terms #sup and #inf are switched.

Cheers,
Javier

Intermediate Question: Grounding different ASP #program blocks by commandline

I was wondering if there was a way to ground multiple #program blocks from the clingo commandline.

For the given file:

#program foo(constant_1, constant_2).
a(constant_1, constant_2).

#program bar.
b.

How can I ground both program foo and bar (in addition to the implicit program `base)?

In Python, this can be accomplished in the following snippet:

from collections import namedtuple
import clingo

ASPProgram = namedtuple('ASPProgram', 'name, arguments')

if __name__ == '__main__':
    clingo_control = clingo.Control()
    clingo_control.load('./path/to/asp_file.lp')
    asp_programs = (
        ASPProgram(name='foo', arguments=(4, 5)),
        ASPProgram(name='foo', arguments=(66, 1)),
        ASPProgram(name='bar', arguments=tuple())
    )
    clingo_control.ground(asp_programs)
    clingo_control.solve()

Upon solving, I could investigate that my answer set is a(4, 5), a(66, 1), and b.

Infinite looping with incremental solving

Hello,
I am a newbie with ASP and Clingo and I am trying to develop a clingo program for airport-cargo problem (from Russell Norvig cap 10.1).
I tried to follow the Blocks World Planning from the guide-2.0, but I failed.
This is what I wrote until now.
If I try to run that, Clingo will loop forever, and output is "Solving...".
There are also a PDDL definition of the problem, maybe can be useful.
You can ignore comment.
Can someone point me in the right direction? It is from two days that I am trying to solve this problem.
Thanks for you answer.

Grounding of silent variables leads to missing answer sets

I tested the following code using clingo 5. Comments explain expected and found answer sets
(note that all answer sets contain obj/1 and att/1 atoms).

% run: clingo -n 0 concept.lp
% Context described by:
%   e f h
% b   x
% c x x x
% d x x

rel(b,f).
rel(c,(e;f;h)).
rel(d,(e;f)).

% Generating the concepts.
obj(X):- rel(X,_) ; rel(X,Y): att(Y).
att(Y):- rel(_,Y) ; rel(X,Y): obj(X).

% The following constraint is not correctly grounded.
:- not obj(_).
%:- not obj(X):obj(X).  % this one is correctly grounded

#show obj/1.
#show att/1.

For reference, this is the expected answer sets (found with clingo -n 0 concept.lp) and clingo 5:

clingo version 5.2.0
Reading from simple.lp
Solving...
Answer: 1
att(f) obj(c) att(h) att(e)
Answer: 2
att(f) obj(c) obj(d) obj(b)
Answer: 3
att(f) obj(c) att(e) obj(d)
SATISFIABLE

And here is the result of the non-correctly grounded program:

clingo version 5.2.0
Solving...
Answer: 1
att(f) obj(d) obj(c) att(e)
Answer: 2
att(f) obj(d) obj(c) obj(b)
SATISFIABLE

In other word: with the first constraint enable, 1 answer sets are unexpectedly discarded.
This holds for clingo 5.
In case of clingo 4.5.3 and 4.5.4, 2 answer sets are discarded.

This unexpected behaviors can be fixed (whatever the clasp version)
by avoiding the use of silent variables in constraint:

:- not obj(X):obj(X).

Watching all literals results in segfault

I was trying to reimplement the dot propagator using Haskell bindings that I have been writing and ran into a segfault. Upon writing an equivalent C implementation the segfault still exists, and it occurs independently of the propagate and undo methods, so I have omitted these from the code snippet below.

The code iterates over the symbolic atoms during the init method of the propagator and sets a watch on all of them. However, setting a watch to literal 30 or higher (1 indexed) triggers the problem. It works fine when omitting those higher literals. I have not been able to find any notable difference between literals <30 and >=30.

I am not completely sure whether the problem is on my end or not, but this should constitute a 1:1 translation of the init method from the Python example.

I have attached both the source causing the problem, and the test file below (althoiugh github does not accept the correct filetypes for some reason).

dot-segfault.txt

test.txt

Equivalent Fact Atoms in Incremental Propagators

Currently, clasp's equivalence preprocessor always associates fact atoms with the same solver literal. Because this literal is propagated on level zero, it is only propagated in the first solving step. While other atoms might be assigned to existing literals, too, they are guaranteed to always be propagated (if assigned). This makes it necessary to implement special treatment for factual theory atoms when writing incremental propagators, which is cumbersome with the current interface.

It would be much more convenient to introduce a fresh fact literal with every solving step. This way it should be easier to implement propagators because the special case above does not have to be handled. As an optimization a fresh literal should only be introduced if there are fresh fact atoms to avoid unnecessary literals.

Doesn't run on Windows

Launching any exe file (clingo.exe, gringo.exe, ...) results in "... is not a valid Win32 application" error message in a pop-up window and "no access" in the console. Tried versions 5.2.1-64 and 5.1-32. Windows is 64 bit.

Minor change to metaD.lp

In the file metaD.lp of the reify part of clingo, the definition of step/2 can be changed from:
steps(C,Z) :- scc(C,), Z = { scc(C,A) : not fact(A) }.
to
steps(C,Z-1) :- scc(C,
), Z = { scc(C,A) : not fact(A) }.

All atoms are not generated

I recently came across the following behavior (clingo 5 and clingo 4.5.4).

% Input data: a context containing two concepts.
rel((a;b;c;d),(e;f)).  % first concept
rel((a;b),(g;h)).  % second concept (overlapping the first on {a,b})

% Generation of formal concepts (1 concept = 1 answer set).
obj(X):- rel(X,_) ; rel(X,Y): att(Y).
att(Y):- rel(_,Y) ; rel(X,Y): obj(X).

% Outsiders are objects in the concept that are linked to non-attribute values.
outsider(X):- obj(X) ; rel(X,Z) ; not att(Z).
% This line should, for the first answer set, yield outsider(a) and outsider(b).
% Observation: it doesn't.

#show.
#show obj/1.
#show att/1.
#show outsider/1.

Using clingo -n 0 file.lp, i got the following answer sets:

Answer: 1
att(f) att(e) obj(b) obj(a) obj(d) obj(c)
Answer: 2
att(f) att(e) obj(b) obj(a) att(h) att(g)
SATISFIABLE

The second one is missing the atoms outsider(a) and outsider(b) (since both are in obj/1, and linked to g which is not in att/1).

I found two way to retrieve correctly these missing atoms.

1. By changing a little the definition of outsider/1, using an intermediary object:

not_att(Z):- not att(Z) ; rel(_,Z).
outsider(X):- obj(X) ; rel(X,Z) ; not_att(Z).
% This time, outsider(a) and outsider(b) are generated.

2 .By replacing the concept generation by the expected obj/1 and att/1:

% Obviously, only one answer set remains, but at least we got the outsider/1 atoms correctly.
att(f). att(e). obj(b). obj(a). obj(d). obj(c).

atom in disjunction visible in answer set although it is not visible in grounding (and should not be true)

In the attached minimal.lp there is a fact
sequence (0,"Volkstheater").
and a rule with the disjunctive head
sequence(I,L) | nsequence (I,L)

There is no other rule defining sequence/2 or nsequence/2.

Therefore nsequence(0,"Volkstheater") can never become true.

However if I run minimal.lp with clingo 5.2.0 or with clingo 01dffb (quite recent master branch hash) then some answer sets contain this atom. If I pipe gringo output into clasp directly this also happens.

If I use gringo --text on minimal.lp then the rule with nsequence(0,"Volkstheater") in the head is not even shown, it seems to be optimized away (which is correct, because it is satisfied by the fact).

minimal.zip

Changing Heuristics Between Solutions

I'm currently modeling an optimization problem using the domain heuristics.
If I understood correctly this will only influence the search while looking for a solution. Is there a way to influence the search between solutions? E.g. changing heuristics after the solver has encountered N solutions to try to get out of a local Optimum.

Signal Handling is Inconsistent in clingo

When having a (python) main function inside your encoding,
Ctrl+C can be handled differently depending on the exact moment when it was triggered.
It can either end the process, in clasp_app.cpp ll 229 with exit(getExitCode());
or it can report INTERRUPT as a result of the solve call in the python script,
which has to be handled manually (if not the solving continues normally, and further signals will be queued ? ).

Request: update tutorial/manual and example comments

Hello,
I am trying to get familiar with clingo, but I am struggling to find good resources.
The manual available at http://wp.doc.ic.ac.uk/arusso/wp-content/uploads/sites/47/2015/01/clingo_guide.pdf is for version 3.x, using version 5.2 I am unable to even run some of the examples there.
Alternatively, more verbose commentary for the examples such as https://github.com/potassco/clingo/tree/master/examples/clingo/opt would be greatly appreciated.

Range example from guide throws error

I took this example from the potassco guide.

#script (python)

def rng(a, b):
    return range(a, b+1)

#end.

p(1,3).
p(5,10).
rng(X,Y,@rng(X,Y)) :- p(X,Y).

When I run it, I get the following error.

clingo version 5.2.1
Reading from experiments/range-py.lp
*** ERROR: (clingo): experiments/range-py.lp:10:9-18: error: error calling python function:
  Traceback (most recent call last):
    File "<experiments/range-py.lp:1:1-6:6>", line 4, in rng
  TypeError: unsupported operand type(s) for +: 'clingo.Symbol' and 'int'

UNKNOWN

Models       : 0+
Calls        : 1
Time         : 0.051s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.036s

Unsafe facts?

Hi,

I was experimenting a bit more with clingo and have a question about facts. In my logic program new.lp is the following line of code:

fluent(POI).

Once I compile my program, I get the following error message:

error: unsafe variables in:
(fluent(POI)) :- [#inc_base].
note: 'POI' is unsafe.

In clingo 5.1 I never had any issues with facts. Since 5.2 I've gotten this message.
My questions are:

  • Why is POI unsafe, despite it being inside a fact?
  • What does the [#inc_base] mean?

Note: I do know what unsafe variables are.

Beginner question: Python Support

Hi,

I've recently started to work with Clingo and I have a question.
I've never worked with Python before and I wonder how to run a python script with clingo.

I already have Python in my PATH variable but clingo still tells me, that it has been "built without python support". What else do I need to do?

The aggregation function sum has some problems.

Look at the code:

#sum+{1: one; 1 : another_one; 2 : two}=3.

It should have two models: {one, two}, and {another_one, two}, but it actually get three models. The extra one is {one, another_one, two}. I found that if two keys with the same weight, like one and another_one, then it will cause problem. Also, if we change the code to

#sum+{1: one; 1 : another_one; 2 : two}=4.

Then it has no model. But it should have one model {one, another_one, two}.
I tested the program with gringo and clasp, it has the same problem. It would be great if this bug can be fixed.

How to build python API documentation examples/clingo/pydoc

There are two commands given to build the Python API documentation:
https://github.com/potassco/clingo/tree/wip/examples/clingo/pydoc

According to PYTHONPATH and PATH these will yield results that might not be the documentation for the current checkout. A warning about this could be added.

Also only one of these is required to build the documentation.

(Also, building this documentation automatically for the right version when building with -DCLINGO_BUILD_PY_SHARED=ON would be great.)

Grounding with context fails in Python 3.6

Hello,
I am facing a RuntimeError that is produced while working with the clingo Python API. Using previous clingo versions and Python 2, I was able to define a class, pass it to grounding via the named argument "context", and thereby use its methods from within a logic program through the @-syntax. Once I updated to clingo 5.2.1 and Python 3.6 this fails with a RuntimeError.
Here is a toy example of the problem.

import clingo
import sys
print(clingo.__version__)
print(sys.version)

def on_model(m):
    print(m)

class context_provider:
    def ausgeber(self,x):
        print('function call:',x)
        return clingo.Number(2)

context=context_provider()
prg=clingo.Control(['-n0'])
prg.add("base", [], "a(@ausgeber(1)).")
prg.ground([("base", [])],context=context)
prg.solve(on_model=on_model)

Under previous versions, running this Python script would return the expected output:

5.1.0
2.7.11 |Anaconda 2.2.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
('function call:', 1)
a(2)

Under Python 3.6 it no longer works:

5.2.1
3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 13:51:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
~/Desktop/steady_ready_projects/circuit_enumeration/ASP_files/taking_control/context_function_module.py in <module>()
     20 prg=clingo.Control(['-n0'])
     21 prg.add("base", [], "a(@ausgeber(1)).")
---> 22 prg.ground([("base", [])],context=context)
     23 prg.solve(on_model=on_model)
     24 

RuntimeError: <block>:1:3-15: error: error in context:
  SystemError: Objects/tupleobject.c:81: bad argument to internal function

Is there any way to overcome this problem? Thanks.

Best,
Torsten

Colum number in lexer errors

Hi,

When prompting a lexer error, clingo gives a number corresponding to the last character in the token,
while it would be nicer for the user if it pointed to the first one. See the example below:

$ echo "#" | clingo -
clingo version 5.1.0
Reading from -
-:1:2: error: lexer error, unexpected #

*** ERROR: (clingo): parsing failed
UNKNOWN

Danke, Chao!
J

cmake could fail if incompatible GCC is detected

INSTALL.md states that at least gcc 4.9 is required.

cmake detects gcc 4.8 and does not stop, but tries to compile, which leads to compiler errors.

Why not fail hard for gcc versions below 4.9?

Packaging for Inclusion in Fedora Linux

Hi!

This package is a candidate for inclusion as an official package in Fedora Linux! Per Fedora packaging guidelines, there are some issues that should be addressed before the package can be officially reviewed, built, and made available in the Fedora RPM repositories.

Since this package is part of a group of packages, I have been prototyping the packages in a Fedora Copr repository [1]. The preliminary sources for this package can be accessed in a Git repository [2].

Here are the initial issues which should be addressed:

  • Upstream package(s)
    Since this package needs libpotassco and clasp, we should prioritize addressing issues with those packages first [3] [4].
  • .SO Name Versioning
    Fedora guidelines strongly suggest that the version be included in any shared object libraries distributed in the package [5]. Some packages in this collection appear to be setting the SONAME value, though the value doesn't match the version of the package.
  • Installation Directory Override
    Any files installed by the packages must conform to Fedora's filesystem hierarchy. In order for this package to install the files as such, it must not override CMake's default install locations without any mechanism to change them. I have sketched out a preliminary patch to address this [6]. Please feel free to use those changes as you see fit.
  • Shared Library By Default
    When CMake is invoked during Fedora packaging, CMake is configured to build shared libraries instead of static ones by default. It appears that this breaks a couple of the libraries in this package, which I believe are intended to always be static, and not distributed in the package. Assuming this is the case, I made a patch to specifically build those libraries as static [7].
  • Unbundle from clasp
    From what I can tell, efforts were made such that clasp can be built separately from libpotassco. Those same patterns weren't used in this package, but I was able to apply the same technique to achieve this [8].
  • Build API documentation
    It would be great to package the API documentation for offline consumption like clasp does. It looks like this is an easy thing to enable [9].
  • Python and Lua Dependencies
    I haven't had a chance to fully investigate this, but it appears that when I build clingo with Lua and Python modules enabled, the core application is linked against those libraries. It should be possible to build those modules, but install them optionally. Right now, installing clingo without the modules still pulls Lua and Python as dependencies. I suspect this isn't intentional, and could be addressed by a change to the CMakeLists.txt.

Once we have at least acknowledged each of the above issues, I'll initiate the review. If there is a valid reason that any of the issues can't be addressed, please let me know and we'll talk about an FPC exemption. If you have any further questions, or if there is anything I can do to help, please reach out.

Thanks very much!

--scott

[1] https://copr.fedorainfracloud.org/coprs/cottsay/potassco
[2] http://copr-dist-git.fedorainfracloud.org/cgit/cottsay/potassco/clingo.git/tree/
[3] potassco/libpotassco#1
[4] potassco/clasp#12
[5] https://fedoraproject.org/wiki/Packaging:Guidelines#Downstream_.so_name_versioning
[6] http://copr-dist-git.fedorainfracloud.org/cgit/cottsay/potassco/clingo.git/tree/clingo-5.2.1-install_dir.patch
[7] http://copr-dist-git.fedorainfracloud.org/cgit/cottsay/potassco/clingo.git/tree/clingo-5.2.1-default_shared.patch
[8] http://copr-dist-git.fedorainfracloud.org/cgit/cottsay/potassco/clingo.git/tree/clingo-5.2.1-unbundle_clasp.patch
[9] http://copr-dist-git.fedorainfracloud.org/cgit/cottsay/potassco/clingo.git/tree/clingo-5.2.1-doc_clingo.patch

asprin.py:1:1-222:6: error: python support not available

I was trying to run the examples in the encodings at https://sites.google.com/site/aspseqmining/ijcai-2016.
Everyhting runs fine till the "maximal sequences"
The error is thrown for the "preferences" example


**Error message
asprin.py:1:1-222:6: error: python support not available
*** ERROR: (clingo): fatal error

__________**
Python version in my machine
[manati]s1779550: python
Python 2.7.5 (default, Aug 2 2017, 11:05:32)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.


OS: Scientific Linux


Version of clingo downloaded
[manati]s1779550: ./clingo
clingo version 5.2.1


Command line argument (as below) or while trying to run the command ./asprin 0 -c k=2 instance.lp frequent.lp preference.lp asprin.lib (from the URL https://sites.google.com/site/aspseqmining/ijcai-2016)
[manati]s1779550: ./asprin
asprin version 1.1.1
/afs/inf.ed.ac.uk/user/s17/s1779550/Documents/Himan/Kaj/UoEResearch/MScResearch_09OCT2017/IRDSProject_15OCT2017/Potassco/potassco-asp-executables/asprin.py:1:1-222:6: error: python support not available

*** ERROR: (clingo): fatal error

Script implemented functions within disjunctive heads

I have noticed an issue where scripted functions appear as terms within the heads of disjunctive rules.
The following code illustrates the problem:

#script(python)
def v( x ):
	return x
#end.
a(i).
c ; u(@v(X)) :- a(X).

clingo 5.2.0 reports

tiny.lp:5:1-13: error: unsafe variables in:
 u(#Script0)::;c::
tiny.lp:5:7-12: note: '#Script0' is unsafe

As a workaround, a suitable variable can be assigned in the rule body:

c ; u(Y) :- a(X), Y=@v(X).

The error also occurs when the function is implemented using the Lua language.

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.