Skip to content

clingo.control

Module containing the Control class responsible for grounding and solving.

Example

The example shows the most straightforward way to ground and solve a small test program:

>>> from clingo.core import Library
>>> from clingo.control import Control
>>>
>>> lib = Library()
>>> ctl = Control(lib)
>>> ctl.parse_string("1 { a; b }.")
>>> ctl.ground()
>>> print(ctl.solve(on_model=print))
a
SAT

ControlMode

Bases: IntEnum

Available control modes.

Ground class-attribute instance-attribute

Ground = 2

Parse class-attribute instance-attribute

Parse = 0

Rewrite class-attribute instance-attribute

Rewrite = 1

Solve class-attribute instance-attribute

Solve = 3

Control

Control(lib: Library, options: Sequence[str] = [])

A control object for grounding and solving.

Construct a control object.

Parameters:

Name Type Description Default
lib Library

The library storing symbols and scripts.

required
options Sequence[str]

The command line options to initialize the control object.

[]

backend property

backend: BackendManager

Get a backend manager to extend the ground program.

base property

base: Base

Get the atom/term bases of the program.

buffer property

buffer: str

The content of the output buffer.

config property

config: Config

Get the solver config.

const_map property

const_map: Mapping[str, Symbol]

Get the map of constants defined by #const directives.

mode property

Get the application mode.

parts property writable

parts: Sequence[tuple[str, Sequence[Symbol]]] | None

Get/set the program parts to ground.

profile property

profile: list

Get the profiling information as a list of profile nodes.

Each node is a dictionary with keys such as "type", "key", "depth", "nested", "children", etc. Returns a list of top-level profile nodes representing the profiling tree.

The result is directly convertible to JSON using Python's json module.

stats property

stats: StatsView

Get the solver stats.

discard

discard(
    minimize: bool = False, project: bool = False
) -> None

Discard statements of the selected types.

Parameters:

Name Type Description Default
minimize bool

Discard all minimize and weak constraints (default: False).

False
project bool

Discard all previously added project statements (default: False).

False

ground

ground(
    parts: (
        Sequence[tuple[str, Sequence[Symbol]]] | None
    ) = None,
    context: Any = None,
) -> None

Ground the given program parts.

Non-ground logic programs must be added before calling this function. Programs can define named sections using #program. directives. These sections can be selectively grounded by specifying their name and binding parameters to symbols.

Parameters:

Name Type Description Default
parts Sequence[tuple[str, Sequence[Symbol]]] | None

A sequence of tuples, each containing a section name and a sequence of symbols. The name identifies the program section to ground, and the symbols bind its parameters. If None, the implicit base section without arguments is grounded.

None
context Any

An optional object providing functions that can be called during grounding.

None

interrupt

interrupt() -> None

Interrupt the active solve call.

This function is thread-safe. Prefer using cancel if possible.

join

join(program: Program) -> None

Join with the given non-ground logic program.

Parameters:

Name Type Description Default
program Program

A non-ground logic program.

required

main

main() -> None

Ground and solve a logic program based on the current control mode.

This function serves as a high-level entry point for the default ground-and-solve process. It considers the current ControlMode and can dispatch execution to a script's main function if defined.

If solving, the function proceeds as follows:

  1. Each set of program parts in parts is grounded sequentially.
  2. After grounding each set, solving is performed immediately.

Before calling main(), the control object can be prepared by parsing programs, registering propagators, or performing other setup steps.

observe

observe(
    observer: Observer, preprocess: bool = True
) -> None

Inspect the ground program of the current step.

Parameters:

Name Type Description Default
observer Observer

The program observer to inspect the program.

required
preprocess bool

Whether the program should be preprocessed first (default: True).

True

parse_files

parse_files(files: Sequence[str]) -> None

Parses the logic programs in the given files

Parameters:

Name Type Description Default
files Sequence[str]

A list of file paths to parse.

required

parse_string

parse_string(program: str) -> None

Parses a logic program given as a string.

Parameters:

Name Type Description Default
program str

The logic program as a string.

required

register_propagator

register_propagator(propagator: Propagator) -> None

Register the given propagator for theory propagation.

See the propagate module for an example.

Parameters:

Name Type Description Default
propagator Propagator

The propagator.

required

solve

solve(
    assumptions: Sequence[tuple[Symbol, bool] | int] = [],
    on_model: Callable[[Model], bool | None] | None = None,
    on_unsat: Callable[[Sequence[int]], None] | None = None,
    on_stats: Callable[[Stats, Stats], None] | None = None,
    on_finish: Callable[[SolveResult], None] | None = None,
) -> SolveResult

Solve the current ground program.

This function is semantically equivalent to the following start_solve call:

with self.start_solve(assumptions, on_model, on_unsat, on_stats, on_finish) as hnd:
    return hnd.get()

Parameters:

Name Type Description Default
assumptions Sequence[tuple[Symbol, bool] | int]

A list of assumptions.

[]
on_model Callable[[Model], bool | None] | None

Optional callback to intercept models.

None
on_unsat Callable[[Sequence[int]], None] | None

Optional callback to intercept lower bounds during optimization.

None
on_stats Callable[[Stats, Stats], None] | None

Optional callback extend statistics.

None
on_finish Callable[[SolveResult], None] | None

Optional callback called once search has finished.

None

Returns: A SolveResult representing the result of the search.

start_ground

start_ground(
    parts: (
        Sequence[tuple[str, Sequence[Symbol]]] | None
    ) = None,
    context: Any = None,
    on_finish: Callable[[GroundResult], None] | None = None,
) -> GroundHandle

Ground the given program parts.

Starts grounding in the background and returns a GroundHandle to the running grounding. See ground for details on grounding program parts.

Parameters:

Name Type Description Default
parts Sequence[tuple[str, Sequence[Symbol]]] | None

A sequence of parts to ground.

None
context Any

An optional object providing functions that can be called during grounding.

None
on_finish Callable[[GroundResult], None] | None

An optional callback called once grounding has finished.

None

start_solve

start_solve(
    assumptions: Sequence[tuple[Symbol, bool] | int] = [],
    on_model: Callable[[Model], bool | None] | None = None,
    on_unsat: Callable[[Sequence[int]], None] | None = None,
    on_stats: Callable[[Stats, Stats], None] | None = None,
    on_finish: Callable[[SolveResult], None] | None = None,
    yield_: bool = False,
    async_: bool = False,
) -> SolveHandle

Solve the current ground program.

This function runs the solver on the current ground program, optionally using assumptions, callbacks, or asynchronous execution. It returns a SolveHandle, allowing interaction with the solving process.

If asynchronous solving (async_) is enabled, the function returns immediately, and solving runs in the background. Otherwise, the function blocks until solving is complete.

Parameters:

Name Type Description Default
assumptions Sequence[tuple[Symbol, bool] | int]

A list of assumptions that constrain this search. Each assumption is either a tuple[clingo.symbol.Symbol, bool] indicating an atom's truth value or a program literal (see literal). For example, using [(clingo.symbol.Function(lib, "a"), True)] only admits answer sets that contain atom a.

[]
on_model Callable[[Model], bool | None] | None

Optional callback that receives a Model object when a model is found. Returning False from the callback stops solving.

None
on_unsat Callable[[Sequence[int]], None] | None

Optional callback to intercept lower bounds during optimization.

None
on_stats Callable[[Stats, Stats], None] | None

Optional callback that receives statistics updates after each step. Two Stats objects are passed: step-specific and accumulated stats.

None
on_finish Callable[[SolveResult], None] | None

Optional callback called once search has finished. A SolveResult is passed to the callback.

None
yield_ bool

If True, the returned SolveHandle is iterable, yielding Model objects during solving.

False
async_ bool

If True, solving runs asynchronously in a separate thread. Note: Callbacks (on_model, on_stats, etc.) will also be called from a separate thread.

False

Returns: A SolveHandle to control the search.

Notes

Asynchronous solving requires compiling clingo with thread support. Blocking methods on SolveHandle release the GIL but are not thread-safe.

See Also

solve

write_aspif

write_aspif(
    path: str | None = None,
    symbols: bool = False,
    append: bool = False,
    preamble: bool | None = None,
    preprocess: bool = True,
) -> None

Write the current logic programs to the given file.

If append is true, a file will be created if none exists yet. If preamble is None, then the aspif preamble is written for newly created files and omitted for existing files.

If path is None, clingo's internal output buffer is used instead of writing to a file. The buffer content is available via buffer. If preamble is None, the preamble is written only if the buffer is currently empty. In application mode, the buffer is printed to stdout and cleared after each major operation like grounding, so the preamble flag should be set explicitly in this case.

Parameters:

Name Type Description Default
path str | None

The optional path to write the program to.

None
append bool

Whether to append to an existing file.

False
preamble bool | None

Whether to write the aspif preamble.

None
preprocess bool

Whether to preprocess the program before writing.

True