Answer Set Programming in Python

Potassco is an Answer Set Solving system. There is a native library for embedding Answer Set Solving in Python. However, the library does not work under Windows.

Fortunately, the Potassco tools can output data in JSON format. One integration option is to invoke the compiled binary directly. The PyASP Python library uses this strategy.

The same effect can be achieved in just a few lines of code:

import subprocess
import json

clingo_path = 'path\\to\\bin\\clingo.exe'
clingo_options = ['--outf=2','-n 0']
clingo_command = [clingo_path] + clingo_options

def solve(program):
    input = program.encode()
    process = subprocess.Popen(clingo_command, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    output, error = process.communicate(input)
    result = json.loads(output.decode())
    if result['Result'] == 'SATISFIABLE':
        return [value['Value'] for value in result['Call'][0]['Witnesses']]
    else:
        return None

Note that the clingo_path (the third line) must be set appropriately.

The output is a list of solutions, each solution is a list of strings corresponding to terms that the ASP solver could prove.

Suppose this library is named asp.py, it may be used as follows:

import asp

solutions = asp.solve('1 { a; b } 1.')
# Print out the solutions
print(solutions)
# Output: [['b'], ['a']]

Published 11 June 2016 by Benjamin Johnston.