### Program Parsing and Building Example Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Demonstrates how to parse a logic program from a string and manually build AST statements using the `ProgramBuilder` in the Clingo Python API. ```APIDOC ## Program Parsing and Building Example ### Description This example shows how to parse a program from a string and pass the resulting AST to the builder. It also demonstrates manually constructing an AST rule and adding it to the builder. ### Method ```python from clingo import Control from clingo.ast import Location, ProgramBuilder, Position, parse_string c_ = Control() with ProgramBuilder(c_) as bld: # parse from string parse_string('a.', bld.add) # build rule manually pos = Position('', 1, 1) loc = Location(pos, pos) fun = ast.Function(loc, 'b', [], False) atm = ast.SymbolicAtom(fun) lit = ast.Literal(loc, ast.Sign.NoSign, atm) bld.add(ast.Rule(loc, lit, [])) c_.ground([('base', [])]) print(c_.solve(on_model=print)) ``` ### Expected Output ``` a b SAT ``` ``` -------------------------------- ### AST Transformation Example Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Illustrates how to transform ASTs using the `Transformer` class, specifically by renaming variables in a parsed logic program. ```APIDOC ## AST Transformation Example ### Description This example demonstrates how to transform ASTs using the `Transformer` class. A custom transformer `VariableRenamer` is defined to prepend an underscore to all variable names. ### Method ```python from clingo.ast import Transformer, Variable, parse_string class VariableRenamer(Transformer): def visit_Variable(self, node): return node.update(name='_' + node.name) vrt = VariableRenamer() parse_string('p(X) :- q(X).', lambda stm: print(str(vrt(stm)))) ``` ### Expected Output ``` #program base. p(_X) :- q(_X). ``` ``` -------------------------------- ### Setup Test Fixture - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/tests/test_propagator Initializes the test fixture by creating instances of _MCB and Control. _MCB is likely for model callback handling, and Control is the main Clingo interface. This method runs before each test case. ```python def setUp(self): self.mcb = _MCB() self.ctl = Control(["0"]) ``` -------------------------------- ### Setup Clingo Control and Ground Base Predicate (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/tests/test_propagator Initializes the Clingo control object, adds a base rule, and grounds it. This is typically used in test fixtures to set up the solver environment. ```python def setUp(self): self.ctl = Control(["0"]) self.ctl.add("base", [], "start. {value}. {end}.") self.ctl.ground([("base", [])]) ``` -------------------------------- ### Working with Theory Atoms in Clingo Source: https://potassco.org/clingo/python-api/5.8/clingo/theory_atoms Example demonstrating how to create and interact with theory atoms using the clingo Python API. This includes grounding atoms, iterating through them, and accessing their elements. ```python from clingo.control import Control ctl = Control() ctl.add('base', [], """ #theory example { t { }; &a/0 : t, head }. {c}. &a { t: c }. """) ctl.ground([('base', [])]) atm = next(ctl.theory_atoms) print(atm) elm = atm.elements[0] print(elm) ``` -------------------------------- ### Get Clingo Assignment Root Level (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the root level of the Clingo assignment. This integer property indicates the starting point for decisions in the solver. ```python @property def root_level(self) -> int: """ The current root level. """ return _lib.clingo_assignment_root_level(self._rep) ``` -------------------------------- ### Default Clingo Application Example Source: https://potassco.org/clingo/python-api/5.8/clingo/application This Python code demonstrates how to create a basic clingo application by extending the `Application` class. It shows how to load files, ground the program, solve, and then integrates with `clingo_main` to run the application. ```python import sys from clingo.application import Application, clingo_main class ClingoApp(Application): def __init__(self, name): self.program_name = name def main(self, ctl, files): for f in files: ctl.load(f) if not files: ctl.load("-") ctl.ground([("base", [])]) ctl.solve() clingo_main(ClingoApp(sys.argv[0]), sys.argv[1:]) ``` -------------------------------- ### Get Trail Begin Offset in Clingo Python API Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the starting offset for a specific decision level within the solver's assignment trail. This function is crucial for navigating and understanding the chronological order of assigned literals during the solving process. ```python def begin(self, level: int) -> int: """ Returns the offset of the decision literal with the given decision level in the trail. Parameters ---------- level The decision level. """ return _c_call("uint32_t", _lib.clingo_assignment_trail_begin, self._rep, level) ``` -------------------------------- ### Get Clingo Model Number Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Retrieves the running number of the Clingo model. This property directly calls the C API function clingo_model_number to get the model's sequential identifier. ```python import clingo # Assuming 'model' is an instance of clingo.model.Model # model_number: int = model.number ``` -------------------------------- ### Python: Backend Class Initialization and Context Management Source: https://potassco.org/clingo/python-api/5.8/clingo/backend Demonstrates the initialization of the Backend class and its usage as a context manager with 'with' statement. It handles the beginning and ending of the backend interface, clearing errors before and after operations. ```python class Backend(ContextManager["Backend"]): """ Backend object providing a low level interface to extend a logic program. This class allows for adding statements in ASPIF format. See Also -------- clingo.control.Control.backend Notes ----- The `Backend` is a context manager and must be used with Python's `with` statement. """ def __init__(self, rep, error): self._rep = rep self._error = error def __enter__(self): self._error.clear() _handle_error(_lib.clingo_backend_begin(self._rep), handler=self._error) return self def __exit__(self, exc_type, exc_val, exc_tb): self._error.clear() _handle_error(_lib.clingo_backend_end(self._rep), handler=self._error) return False ``` -------------------------------- ### Clingo Theory Integration Example (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/theory Demonstrates how to use the `clingo.theory.Theory` class to integrate a CFFI-based theory solver. It shows the process of initializing Clingo, registering the theory, parsing program fragments with theory atoms, grounding, solving, and retrieving model assignments using the theory's callback functions. ```python from clingo import Control from clingo.ast import parse_string, ProgramBuilder from clingo.theory import Theory from clingcon._clingcon import lib, ffi prg = '&sum { x } >= 1. &sum { x } <= 3.' thy = Theory('clingcon', lib, ffi) cyl = Control(['0']) thy.register(ctl) with ProgramBuilder(ctl) as bld: parse_string(prg, lambda ast: thy.rewrite_ast(ast, bld.add)) ctl.ground([('base', [])]) thy.prepare(ctl) with ctl.solve(yield_=True, on_model=thy.on_model) as hnd: for mdl in hnd: print([f'{key}={val}' for key, val in thy.assignment(mdl.thread_id)]) ``` -------------------------------- ### Get TheoryTerm Name in Python Source: https://potassco.org/clingo/python-api/5.8/clingo/theory_atoms Retrieves the name of a theory term, primarily used for symbols and functions. It calls the Clingo C API to get the string representation of the term's name. ```python def name(self) -> str: """ The name of the term (for symbols and functions). """ return _to_str( _c_call("char*", _lib.clingo_theory_atoms_term_name, self._rep, self._idx) ) ``` -------------------------------- ### Control Grounding and Solving with Python Context Source: https://potassco.org/clingo/python-api/5.8/clingo Demonstrates how to use the clingo Python API to control the grounding and solving process. It shows how to add logic programs, define a custom context for functions like 'inc' and 'seq', ground the program with this context, and solve it, printing the models found. This example requires the 'clingo.control' and 'clingo.symbol' modules. ```python >>> from clingo.symbol import Number >>> from clingo.control import Control >>> >>> class Context: ... def inc(self, x): ... return Number(x.number + 1) ... def seq(self, x, y): ... return [x, y] ... >>> def on_model(m): ... print (m) ... >>> ctl = Control() >>> ctl.add("base", [], """ ... p(@inc(10)). ... q(@seq(1,2)). ... """) >>> ctl.ground([("base", [])], context=Context()) >>> print(ctl.solve(on_model=on_model)) p(11) q(1) q(2) SAT ``` -------------------------------- ### Get Function Name - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/symbol Retrieves the name of a function symbol. It uses a C function call to get the name as a character pointer and then converts it to a Python string. Dependencies include '_to_str' and '_lib.clingo_symbol_name'. ```python @property def name(self) -> str: """ The name of a function. """ return _to_str(_c_call("char*", _lib.clingo_symbol_name, self._rep)) ``` -------------------------------- ### Get Clingo Model Priority Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Returns the priorities of the Clingo model's cost values. Similar to getting the cost, it first determines the size of the priority array and then retrieves the values using the C API. ```python import clingo from typing import List # Assuming 'model' is an instance of clingo.model.Model # priorities: List[int] = model.priority ``` -------------------------------- ### Construct and Add Ground Program to Control Object in Python Source: https://potassco.org/clingo/python-api/5.8/clingox/program Demonstrates using `ProgramObserver` to build a `Program` and then adding it to another `Control` object. This involves registering the observer, adding program rules, grounding, and then transferring the program to a new control object's backend. ```python from clingo.control import Control from clingox.program import Program, ProgramObserver, Remapping prg = Program() ccl_a = Control() ctl_a.register_observer(ProgramObserver(prg)) ctl_a.add('base', [], 'a. {b}. c :- b.') ctl_a.ground([('base', [])]) print(prg) ctl_b = Control(['0']) with ctl_b.backend() as backend: mapping = Remapping(backend, prg.output_atoms, prg.facts) prg.add_to_backend(backend, mapping) ctl_b.solve(on_model=print) ``` -------------------------------- ### Get Theory Atom Terms (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/theory_atoms Retrieves the tuple of terms associated with a theory atom element. It calls the Clingo C API to get the terms and converts them into `TheoryTerm` objects. The output is a list of `TheoryTerm` instances. ```python import clingo from typing import List # Assuming TheoryTerm class, _c_call2, and _lib are defined elsewhere class TheoryAtomElement: def __init__(self, rep, idx): self._rep = rep self._idx = idx @property def terms(self) -> List["TheoryTerm"]: """ The tuple of the element. """ terms, size = _c_call2( "clingo_id_t*", "size_t", _lib.clingo_theory_atoms_element_tuple, self._rep, self._idx, ) return [TheoryTerm(self._rep, terms[i]) for i in range(size)] # Example usage (requires a Clingo context and a theory atom element) # rep = ... # Representation of the theory atom container # idx = ... # Index of the element # element = TheoryAtomElement(rep, idx) # print(element.terms) ``` -------------------------------- ### ApplicationOptions Class Documentation Source: https://potassco.org/clingo/python-api/5.8/clingo/application Documentation for the ApplicationOptions class, which provides methods for adding options and flags to Clingo applications. ```APIDOC ## Class ApplicationOptions ### Description Provides methods for managing application options. ### Methods #### `add` ##### Description Adds a new option to the application. ##### Parameters - **group** (str) - Optional - Options are grouped into sections as given by this string. - **option** (str) - Required - The name of the option. - **value** (any) - Required - The value of the option. - **description** (str) - Optional - The description of the option shown in the help output. - **target** (object) - Required - The object that receives the value. #### `add_flag` ##### Description Adds a flag option to the application. ##### Parameters - **group** (str) - Optional - Options are grouped into sections as given by this string. - **name** (str) - Required - The name of the flag. - **description** (str) - Optional - The description of the flag shown in the help output. - **target** (Flag) - Required - The Flag object that receives the value. ``` -------------------------------- ### Get Statistics from Clingo Control Source: https://potassco.org/clingo/python-api/5.8/clingo/control Retrieves statistics from the clingo Control object. It accesses underlying C functions to get detailed statistics, including summary and call information. The statistics are cached and updated if new calls are made. ```python stats = _c_call( "clingo_statistics_t*", _lib.clingo_control_statistics, self._rep ) p_key = _ffi.new("uint64_t*") key_root = _c_call(p_key, _lib.clingo_statistics_root, stats) key_summary = _c_call( p_key, _lib.clingo_statistics_map_at, stats, key_root, "summary".encode() ) key_call = _c_call( p_key, _lib.clingo_statistics_map_at, stats, key_summary, "call".encode() ) call = _c_call("double", _lib.clingo_statistics_value_get, stats, key_call) if self._statistics is not None and call != self._statistics_call: self._statistics = None if self._statistics is None: self._statistics_call = call self._statistics = _statistics(stats, key_root) return cast(dict, self._statistics) ``` -------------------------------- ### Add Program to Backend (Python) Source: https://potassco.org/clingo/python-api/5.8/clingox/program Adds the program's statements (shows, facts, rules, etc.) to a specified backend. It handles optional literal remapping and ensures projects and assumptions are correctly added. The output table cannot be added directly. ```python def add_to_backend(self, backend: Backend, mapping: Optional[AtomMap] = None ) -> "Program": """ Add the program to the given backend with an optional mapping. Note that the output table cannot be added to the backend for technical reasons. This has to be taken care of by the user. See for example the `Remapping` class, which provides functionality for this. Parameters ---------- backend The backend. mapping A mapping function to remap literals. Returns ------- A reference to self. See Also -------- add_to_backend """ _add_stms_to_backend(self.shows, backend, mapping) _add_stms_to_backend(self.facts, backend, mapping) _add_stms_to_backend(self.rules, backend, mapping) _add_stms_to_backend(self.weight_rules, backend, mapping) _add_stms_to_backend(self.heuristics, backend, mapping) _add_stms_to_backend(self.edges, backend, mapping) _add_stms_to_backend(self.minimizes, backend, mapping) _add_stms_to_backend(self.externals, backend, mapping) if self.projects is not None: if self.projects: _add_stms_to_backend(self.projects, backend, mapping) else: backend.add_project([]) backend.add_assume( [_remap_lit(lit, mapping) if mapping else lit for lit in self.assumptions] ) return self ``` -------------------------------- ### Clingo Python API: Begin Solver Step Source: https://potassco.org/clingo/python-api/5.8/clingo/backend The `begin_step` function marks the beginning of a block of directives that will be passed to the Clingo solver. This is useful for organizing multiple directives before a solve call. ```python def begin_step(self) -> None: """ Marks the beginning of a block of directives passed to the solver. """ ``` -------------------------------- ### Get String Value - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/symbol Retrieves the string value of a string symbol. It calls a C function to get the string as a character pointer and converts it to a Python string using '_to_str'. Dependencies include '_to_str' and '_lib.clingo_symbol_string'. ```python @property def string(self) -> str: """ The value of a string. """ return _to_str(_c_call("char*", _lib.clingo_symbol_string, self._rep)) ``` -------------------------------- ### Python: Test Basic Solving and Observer Functions with TestBackend Source: https://potassco.org/clingo/python-api/5.8/clingo/tests/test_backend Tests the basic solving and observer functionalities of the Clingo backend. It initializes a Control object, registers a TestObserverBackend, and uses the backend context manager to add various atoms, rules, and constraints. Assertions verify that the observer methods are called correctly. ```python class TestBackend(TestCase): """ Tests basic solving and related functions. """ def test_backend(self): """ Test backend via observer. """ ctl = Control() obs = TestObserverBackend(self) ctl.register_observer(obs) with ctl.backend() as backend: self.assertIn("init_program", obs.called) self.assertIn("begin_step", obs.called) backend.add_atom() backend.add_atom(Function("a")) backend.add_rule([1], [2, 3], True) self.assertIn("rule", obs.called) backend.add_weight_rule([2], 1, [(2, 3), (4, 5)]) self.assertIn("weight_rule", obs.called) backend.add_minimize(0, [(2, 3), (4, 5)]) self.assertIn("minimize", obs.called) backend.add_project([2, 4]) self.assertIn("project", obs.called) backend.add_heuristic(2, HeuristicType.Level, 5, 7, [1, 3]) self.assertIn("heuristic", obs.called) backend.add_assume([2, 3]) self.assertIn("assume", obs.called) backend.add_acyc_edge(1, 2, [3, 4]) self.assertIn("acyc_edge", obs.called) backend.add_external(3, TruthValue.Release) self.assertIn("external", obs.called) self.assertIn("output_atom", obs.called) ctl.solve() self.assertIn("end_step", obs.called) ``` -------------------------------- ### Get Model Priority in Clingo Python API Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Retrieves the priorities of a Clingo model's cost values. Similar to getting the cost, it first determines the size of the priority array and then populates a CFFI-allocated array with the priority values. ```python @property def priority(self) -> List[int]: """ Return the priorities of the model's cost values. """ size = _c_call("size_t", _lib.clingo_model_cost_size, self._rep) p_priorities = _ffi.new("clingo_weight_t[]", size) _handle_error(_lib.clingo_model_priority(self._rep, p_priorities, size)) return list(p_priorities) ``` -------------------------------- ### Get Function Arguments - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/symbol Retrieves the arguments of a function symbol. It calls a C function to get the arguments and their size, then converts them into a list of Symbol objects. Dependencies include the '_c_call2' function and the '_lib' object from the clingo library. ```python @property def arguments(self) -> List["Symbol"]: """ The arguments of a function. """ args, size = _c_call2( "clingo_symbol_t*", "size_t", _lib.clingo_symbol_arguments, self._rep ) return [Symbol(args[i]) for i in range(size)] ``` -------------------------------- ### Clingo Python API: Initialize Program Source: https://potassco.org/clingo/python-api/5.8/clingo/backend The `init_program` function is called once at the beginning of the program execution. It takes an `incremental` flag to indicate whether multiple solve calls are expected. ```python def init_program(self, incremental: bool) -> None: """ Called once in the beginning. Parameters ---------- incremental Whether the program is incremental. If the incremental flag is true, there can be multiple calls to `clingo.control.Control.solve`. """ ``` -------------------------------- ### Get Model Cost in Clingo Python API Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Returns the list of integer cost values for a Clingo model. The values correspond to Clingo's cost output and are retrieved by first getting the size of the cost array and then populating a CFFI-allocated array with the cost values. ```python @property def cost(self) -> List[int]: """ Return the list of integer cost values of the model. The return values correspond to clasp's cost output. """ size = _c_call("size_t", _lib.clingo_model_cost_size, self._rep) p_costs = _ffi.new("int64_t[]", size) _handle_error(_lib.clingo_model_cost(self._rep, p_costs, size)) return list(p_costs) ``` -------------------------------- ### Implement Literal Remapping with Backend Integration in Python Source: https://potassco.org/clingo/python-api/5.8/clingox/program The Remapping class facilitates mapping existing literals to fresh literals generated by a backend. It initializes a mapping based on provided output atoms and facts, and provides a callable interface to remap individual atoms, introducing new ones if necessary. ```python class Remapping: """ This class maps existing literals to fresh literals as created by the backend. Parameters ---------- backend The backend used to introduce fresh atoms. output_atoms The output table to initialize the mapping with. facts A list of facts each of which will receive a fresh program atom. """ _backend: Backend _map: MutableMapping[Atom, Atom] def __init__( self, backend: Backend, output_atoms: OutputTable, facts: Iterable[Fact] = () ): self._backend = backend self._map = {} for atom, sym in output_atoms.items(): assert atom not in self._map self._map[atom] = self._backend.add_atom(sym) for fact in facts: backend.add_rule([backend.add_atom(fact.symbol)]) def __call__(self, atom: Atom) -> Atom: """ Map the given program atom to the corresponding atom in the backend. If the literal was not mapped during initialization, a new literal is associated with it. Parameters ---------- atom The atom to remap. Returns ------- The remapped program atom. """ if atom not in self._map: self._map[atom] = self._backend.add_atom() return self._map[atom] ``` -------------------------------- ### GET /propagate_control/has_watch Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Checks if a literal is watched in the current solver thread. ```APIDOC ## GET /propagate_control/has_watch ### Description Checks whether a literal is watched in the current solver thread. ### Method GET ### Endpoint /propagate_control/has_watch ### Parameters #### Query Parameters - **literal** (int) - Required - The target solver literal. ### Request Example ``` GET /propagate_control/has_watch?literal=5 ``` ### Response #### Success Response (200) - **is_watched** (bool) - Whether the literal is watched. #### Response Example ```json { "is_watched": true } ``` ``` -------------------------------- ### Parse Program String and Build AST with ProgramBuilder Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Parses a program from a string and adds it to the builder. It also demonstrates manually constructing an AST rule and adding it. The resulting AST is then grounded and solved. ```python from clingo import Control from clingo.ast import Location, ProgramBuilder, Position, parse_string ctl = Control() with ProgramBuilder(ctl) as bld: # parse from string parse_string('a.', bld.add) # build rule manually pos = Position('', 1, 1) loc = Location(pos, pos) fun = ast.Function(loc, 'b', [], False) atm = ast.SymbolicAtom(fun) lit = ast.Literal(loc, ast.Sign.NoSign, atm) bld.add(ast.Rule(loc, lit, [])) ctl.ground([('base', [])]) print(ctl.solve(on_model=print)) ``` -------------------------------- ### Basic Ground and Solve Process in Python Source: https://potassco.org/clingo/python-api/5.8/clingo/control Demonstrates the fundamental process of grounding a program and then solving it using the Control class from the clingo.control module. Requires clingo.symbol for symbol manipulation. ```python from clingo.symbol import Number from clingo.control import Control ctl = Control()ctl.add("q.") ctl.ground() print(ctl.solve(on_model=print)) ``` -------------------------------- ### Instance Variables: thread_id Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Gets the numeric ID of the current solver thread. ```APIDOC ## GET /propagate_control/thread_id ### Description Gets the numeric ID of the current solver thread. ### Method GET ### Endpoint /propagate_control/thread_id ### Parameters None ### Response #### Success Response (200) - **thread_id** (int) - The numeric ID of the current solver thread. #### Response Example ```json { "thread_id": 1 } ``` ``` -------------------------------- ### Intercept Models with Callback in Clingo Python API Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Demonstrates how to intercept Answer Set Programming (ASP) models using a callback function with the Clingo Python API. It initializes Clingo, adds a program, grounds it, and then solves, printing each model found. No external dependencies beyond the clingo library are required. ```python from clingo import Control ctl = Control(["0"])ctl.add("base", [], "1 { a; b } 1.")ctl.ground([("base", [])]) print(ctl.solve(on_model=print)) ``` -------------------------------- ### Get AST Node Keys - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Returns a list of all attribute names (keys) for an AST node. This is fundamental for accessing and manipulating the properties of an AST node. ```python def keys(self) -> List[str]: """ The list of keys of the AST node. """ cons = _lib.g_clingo_ast_constructors.constructors[self.ast_type.value] names = _lib.g_clingo_ast_attribute_names.names return [_to_str(names[cons.arguments[j].attribute]) for j in range(cons.size)] ``` -------------------------------- ### Modify Configuration to Enumerate All Models in Clingo Source: https://potassco.org/clingo/python-api/5.8/clingo/configuration This example demonstrates how to access and modify Clingo's configuration settings using the Python API. It specifically shows how to set `ctl.configuration.solve.models` to 0 to ensure all models are enumerated, and then proceeds to add, ground, and solve a simple ASP program. ```python from clingo.control import Control ctl = Control() c_keys = ctl.configuration.keys print(f"Top-level configuration keys: {c_keys}") solve_keys = ctl.configuration.solve.keys print(f"Solve configuration keys: {solve_keys}") solve_models_description = ctl.configuration.solve.description("models") print(f"Description for 'solve.models': {solve_models_description}") # Set configuration to enumerate all models ctl.configuration.solve.models = 0 # Add, ground, and solve the program ctl.add("base", [], "1 {a; b}.") ctl.ground([("base", [])]) print("Solving and printing all models:") ctl.solve(on_model=print) ``` -------------------------------- ### Get AST Node Items - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Provides a list of key-value pairs representing the attributes of an AST node. This method is useful for iterating over the properties of an AST node. ```python def items(self) -> List[Tuple[str, ASTValue]]: """ The list of items of the AST node. """ return [(name, getattr(self, name)) for name in self.keys()] ``` -------------------------------- ### Iterative and Asynchronous Solving in Clingo Python API Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Demonstrates a combined approach to solving, utilizing both iterative yielding of models and asynchronous execution in the Clingo Python API. This allows for fine-grained control over the solving process, including resuming, waiting, and retrieving models incrementally. It requires the clingo library. ```python from clingo import Control ctl = Control(["0"])ctl.add("base", [], "1 { a; b } 1.")ctl.ground([("base", [])]) with ctl.solve(yield_=True, async_=True) as hnd: while True: hnd.resume() # some computation here _ = hnd.wait() m = hnd.model() if m is None: print(hnd.get()) break print(m) ``` -------------------------------- ### Get Child Keys of AST Node - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Returns a list of attribute names that contain other AST nodes. This is useful for traversing the AST and accessing its hierarchical structure. ```python @property def child_keys(self) -> List[str]: """ List of attribute names containing ASTs. """ cons = _lib.g_clingo_ast_constructors.constructors[self.ast_type.value] names = _lib.g_clingo_ast_attribute_names.names return [ _to_str(names[cons.arguments[j].attribute]) for j in range(cons.size) if cons.arguments[j].type in ( _lib.clingo_ast_attribute_type_ast, _lib.clingo_ast_attribute_type_optional_ast, _lib.clingo_ast_attribute_type_ast_array, ) ] ``` -------------------------------- ### SymbolicBackend Class Definition and Initialization (Python) Source: https://potassco.org/clingo/python-api/5.8/clingox/backend Defines the SymbolicBackend class, which wraps clingo's Backend and uses Symbols for literals. It includes initialization and context management methods (__enter__, __exit__). ```python class SymbolicBackend: """ Backend wrapper providing an interface to extend a logic program. It mirrors the interface of clingo's Backend, but using Symbols rather than integers to represent literals. See Also -------- clingo.backend.Backend, clingo.control.Control.backend Notes -------- The `SymbolicBackend` is a context manager and must be used with Python's `with` statement or be attached to an already managed `clingo.backend.Backend` object. """ backend: Backend """ The underlying `clingo.backend.Backend` object. """ def __init__(self, backend: Backend): self.backend: Backend = backend def __enter__(self): """ Initialize the backend. Returns ------- The backend itself. Notes ----- Must be called before using the backend. """ self.backend.__enter__() return self def __exit__(self, type_, value, traceback): """ Finalize the backend. Notes ----- Follows Python's __exit__ conventions. Does not suppress exceptions. """ return self.backend.__exit__(type_, value, traceback) ``` -------------------------------- ### Get AST Node Type - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Retrieves the type of an AST node. This property is crucial for understanding the structure and behavior of the AST node, as it dictates the available attributes and methods. ```python @property def ast_type(self) -> ASTType: """ The type of the node. """ return ASTType( _c_call("clingo_ast_type_t", _lib.clingo_ast_get_type, self._rep) ) ``` -------------------------------- ### Get Assignment in Python Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the `Assignment` object that captures the top-level assignment. This property provides access to the current assignment state. ```python @property def assignment(self) -> Assignment: """ `Assignment` object capturing the top level assignment. """ return Assignment(_lib.clingo_propagate_init_assignment(self._rep)) ``` -------------------------------- ### Combine SymbolicBackend and Backend for Rules in Clingo Source: https://potassco.org/clingo/python-api/5.8/clingox/backend This example illustrates using `SymbolicBackend` in conjunction with the base `Backend` wrapper. The `Backend` is used with Python's `with` statement, and `SymbolicBackend` is instantiated with it. Rules are added using both `symbolic_backend.add_rule` and `backend.add_rule` after adding atoms. ```python >>> import clingo >>> from clingox.backend import SymbolicBackend >>> ctl = clingo.Control() >>> a = clingo.Function("a") >>> b = clingo.Function("b") >>> c = clingo.Function("c") >>> with ctl.backend() as backend: symbolic_backend = SymbolicBackend(backend) symbolic_backend.add_rule([a], [b], [c]) atom_b = backend.add_atom(b) backend.add_rule([atom_b]) >>> ctl.solve(on_model=lambda m: print("Answer: {}".format(m))) Answer: a b SAT ``` -------------------------------- ### Get Backend Interface - Python Source: https://potassco.org/clingo/python-api/5.8/clingo/control Returns a `Backend` object that provides a low-level interface for extending a logic program. Useful for advanced program manipulation. ```python def backend(self) -> Backend: """ Returns a `Backend` object providing a low level interface to extend a logic program. See Also -------- clingo.backend """ return Backend( _c_call("clingo_backend_t*", _lib.clingo_control_backend, self._rep), self._error, ) ``` -------------------------------- ### Grounding and Solving with Clingo Python API Source: https://potassco.org/clingo/python-api/5.8/clingo/tests/test_backend This snippet demonstrates how to ground a Clingo program and then solve it. It also includes assertions to verify the presence of specific theory terms and atoms with guards in the observed calls. This is typically used within a testing context. ```python ctl.ground([("base", [])]) self.assertIn("theory_term_string: a", obs.called) self.assertIn("theory_term_string: =", obs.called) self.assertIn("theory_atom_with_guard", obs.called) ctl.solve() ``` -------------------------------- ### Get Check Mode from PropagateInit Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Returns the PropagatorCheckMode that controls when the Propagator.check method is invoked. This is a property of the PropagateInit object in the Clingo Python API. ```python @property def check_mode(self) -> PropagatorCheckMode: """ `PropagatorCheckMode` controlling when to call `Propagator.check`. """ return PropagatorCheckMode(_lib.clingo_propagate_init_get_check_mode(self._rep)) ``` -------------------------------- ### Control.load() Source: https://potassco.org/clingo/python-api/5.8/clingo/control Extends the logic program with a non-ground logic program from a file. ```APIDOC ## Control.load() ### Description Extend the logic program with a (non-ground) logic program in a file. ### Method `load(self, path: str) -> None` ### Endpoint N/A (Method of a Control object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (str) - Required - The path of the file to load. ### Request Example ```python from clingo import Control c = Control() c.load("my_program.lp") ``` ### Response #### Success Response (None) This method does not return a value. #### Response Example ```json // No response body ``` ``` -------------------------------- ### Get Index of Reified Fact in Python Source: https://potassco.org/clingo/python-api/5.8/clingox/reify Returns the index of the corresponding reified fact. This is a simple getter for an internal `_idx` attribute. No external dependencies are apparent. ```python def index(self) -> int: """ The index of the corresponding reified fact. """ return self._idx ``` -------------------------------- ### Get Clingo Model Thread ID Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Retrieves the ID of the thread that found the Clingo model. This is a direct mapping to the clingo_model_thread_id C function. ```python import clingo # Assuming 'model' is an instance of clingo.model.Model # thread_id: int = model.thread_id ``` -------------------------------- ### Build AST Program Node Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Constructs an AST node of type `ASTType.Program`. It requires a location, program name, and a sequence of parameters. The implementation relies on the Clingo C API for AST building. ```python def Program(location: Location, name: str, parameters: Sequence[AST]) -> AST: """ Construct an AST node of type `ASTType.Program`. """ p_ast = _ffi.new("clingo_ast_t**") c_location = _c_location(location) _handle_error( _lib.clingo_ast_build( _lib.clingo_ast_type_program, p_ast, c_location[0], _ffi.new("char const[]", name.encode()), _ffi.new("clingo_ast_t*[]", [x._rep for x in parameters]), _ffi.cast("size_t", len(parameters)), ) ) return AST(p_ast[0]) ``` -------------------------------- ### Load Logic Program from File (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/control Extends the current logic program with a non-ground logic program from a specified file. It takes a file path as input and integrates the program content into the Clingo control object. ```python def load(self, path: str) -> None: """ Extend the logic program with a (non-ground) logic program in a file. Parameters ---------- path The path of the file to load. """ _handle_error(_lib.clingo_control_load(self._rep, path.encode())) ``` -------------------------------- ### Get Undo Mode from PropagateInit Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the PropagatorUndoMode that dictates when the Propagator.undo method is called. This property is available on the PropagateInit object in the Clingo Python API. ```python @property def undo_mode(self) -> PropagatorUndoMode: """ `PropagatorUndoMode` controlling when to call `Propagator.undo`. """ return PropagatorUndoMode(_lib.clingo_propagate_init_get_undo_mode(self._rep)) ``` -------------------------------- ### Get Number of Threads in Python Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the number of solver threads used in the corresponding solve call. This property indicates the parallelism level of the solver. ```python @property def number_of_threads(self) -> int: """ The number of solver threads used in the corresponding solve call. """ return _lib.clingo_propagate_init_number_of_threads(self._rep) ``` -------------------------------- ### Register Backend for Output (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/control Registers a backend of a specified type to handle solver output. This function is similar to `register_observer` but provides a predefined backend. It allows specifying the file for output, whether to replace existing handlers, and options for reifying strongly connected components (SCCs) and steps. ```python def register_backend( self, type: BackendType, file: str, replace: bool = False, reify_sccs: bool = False, reify_steps: bool = False, ) -> None: """ Registers a backend of the given type. This function is similar to register_observer but instead registers a predefined backend. Parameters ---------- type The type of backend to register. file: The path of the file to write to. replace If set to true, the output is just passed to the backend and no longer to the underlying solver (or any previously registered backends/observers). reify_sccs Whether to reify sccs. reify_steps Whether to reify steps. See Also -------- clingo.backend """ bitset = type.value if reify_sccs: bitset = bitset | _lib.clingo_backend_type_reify_sccs if reify_steps: bitset = bitset | _lib.clingo_backend_type_reify_steps _handle_error( _lib.clingo_control_register_backend( self._rep, bitset, file.encode(), replace ) ) ``` -------------------------------- ### Get Propagator Undo Mode in Python Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the `PropagatorUndoMode` that dictates when the `Propagator.undo` method is called. This property allows inspection of the undo behavior configuration. ```python @property def undo_mode(self) -> PropagatorUndoMode: """ `PropagatorUndoMode` controlling when to call `Propagator.undo`. """ return PropagatorUndoMode(_lib.clingo_propagate_init_get_undo_mode(self._rep)) ``` -------------------------------- ### Test Clingo Application Class Source: https://potassco.org/clingo/python-api/5.8/clingo/tests/test_application Tests the clingo's application class functionality by running a sample program and asserting the expected output sequence. This test uses the `run_app` utility to execute a `TestApp` instance in a subprocess. ```python class TestApplication(TestCase): """ Tests for clingo's application class. """ def test_app(self): """ Test application. """ ret, seq = run_app(TestApp, "1 {a; b; c(1/0)}.", "0", "--test=x", "--flag") self.assertEqual(ret, 30) self.assertEqual( seq, [ "register", ("parse", "x"), "validate", ("flag", True), "main", ( MessageCode.OperationUndefined, "1:12-15: info: operation undefined:\n (1/0)\n", ), ("models", [["a"], ["a", "b"], ["b"]]), ], ) ``` -------------------------------- ### Clingo Python API: Initialize Propagator Before Solving Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator The `init` method is invoked once before each solving step to set up the propagator. It's used for mapping program literals to solver literals, adding watches, and initializing data structures, receiving a `PropagateInit` object for configuration. ```python def init(self, init: PropagateInit) -> None: """ This function is called once before each solving step. It is used to map relevant program literals to solver literals, add watches for solver literals, and initialize the data structures used during propagation. Parameters ---------- init Object to initialize the propagator. Notes ----- This is the last point to access theory atoms. Once the search has started, they are no longer accessible. """ pass ``` -------------------------------- ### Get Propagator Check Mode in Python Source: https://potassco.org/clingo/python-api/5.8/clingo/propagator Retrieves the `PropagatorCheckMode` that controls when the `Propagator.check` method is called. This allows configuration of the propagator's checking behavior. ```python @property def check_mode(self) -> PropagatorCheckMode: """ `PropagatorCheckMode` controlling when to call `Propagator.check`. """ return PropagatorCheckMode(_lib.clingo_propagate_init_get_check_mode(self._rep)) ``` -------------------------------- ### Python: Execute Solve Asynchronously Source: https://potassco.org/clingo/python-api/5.8/clingo/control This example demonstrates asynchronous solving using `async_=True`. The `solve` method returns a `SolveHandle` immediately. The search happens in the background, and the `SolveHandle.resume()` method can be called to continue the search or retrieve results without blocking the main thread. ```python from clingo import Control c = Control() c.add("base", [], "a. a = 1.\nb = 1.") c.ground([("base", [])]) # Example usage with async_ handle = c.solve(async_=True) # ... do other work here ... # To get the result later: result = handle.get() if result.satisfiable: print(f"Satisfiable: {result.model().symbols(shown=True)}") else: print("Search did not complete successfully.") c.cleanup() ``` -------------------------------- ### Theory Version Retrieval (Python) Source: https://potassco.org/clingo/python-api/5.8/clingo/theory Retrieves the version of the theory extension. It interacts with the C library to get the major, minor, and patch version numbers. ```python def version(self) -> Tuple[int, int, int]: """ This function returns the version of the theory. Returns ------- A 3-tuple of integers representing major and minor version as well as the patch level. """ p_version = self._ffi.new("int[3]") self.__call("version", p_version, p_version + 1, p_version + 2) return p_version[0], p_version[1], p_version[2] ``` -------------------------------- ### clingo_ast_parse_files Source: https://potassco.org/clingo/python-api/5.8/clingo/ast Parses programs from the given files and returns an abstract syntax tree for each statement via a callback. It mimics the command-line file handling, treating '-' as stdin and an empty list also as stdin. An optional control object can be provided to enable parsing of ASPIF format files, adding ground statements to the control object. ```APIDOC ## clingo_ast_parse_files ### Description Parse the programs in the given files and return an abstract syntax tree for each statement via a callback. The function follows clingo's handling of files on the command line. Filename `"-"` is treated as stdin and if an empty list is given, then the parser will read from stdin. The optional control object can be added to enable parsing of files in ASPIF format. The ground statements will be added to the control object. ### Method *Not specified, likely internal or part of a class* ### Endpoint *Not applicable for this function* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python # Example usage (conceptual, actual parameters depend on context) # clingo_ast_parse_files(files, callback, control, logger, message_limit) ``` ### Response #### Success Response (200) *None (function returns None, ASTs are passed via callback)* #### Response Example *None* ## Parameters **`files`** List of file names. **`callback`** Callable taking an ast as argument. **`control`** Control object to add ground rules to. **`logger`** Function to intercept messages normally printed to standard error. **`message_limit`** The maximum number of messages passed to the logger. ## See Also `ProgramBuilder` ``` -------------------------------- ### Get Clingo Model Context Source: https://potassco.org/clingo/python-api/5.8/clingo/solving Retrieves the SolveControl object that allows for controlling the running search. This property accesses the underlying C API for clingo_model_context. ```python import clingo from clingo.control import SolveControl # Assuming 'model' is an instance of clingo.model.Model # ctl = model.context ```