API Reference
This page lists every public name in ASPAlchemy, grouped by what it’s for. Each entry says when you’d use it, and links to the page that explains it. For the details of any one name, its docstring is the place to look.
API stability
ASPAlchemy follows semantic versioning: anything that would break code written against the public API waits for the next major version. That promise doesn’t cover:
- clingo’s own parts (the
controlescape hatch, the raw statistics, and the fields ofClingoMessagethat come from clingo), - the wording of error messages and reports,
- anything whose name starts with an underscore, or that isn’t exported,
- new members being added to an enum.
What changed in each version is in the changelog.
The program and its results
ASPProgram: the program you build and solve. Every verb lives here. See Your First Program, and the list of verbs in Statements and Terms.Segment: a named part of a program, for organizing big ones. It has all the same statement verbs as the program. Organizing output and Segment groups.When: whatwhen(...)returns. Finish it withderive(),choose(),forbid(),require()orpenalize(). Rules: when().derive().GroundedProgram: whatground()returns, for asking one program lots of questions. Ground once, solve many.SignatureGrounding: one row ofgrounding_profile(): how many ground atoms a predicate has, and which lines of Python derive it. Profiling grounding.StatementGrounding: one row ofstatement_profile(): how many times a statement was grounded, and which line of Python wrote it. Profiling by statement.RecursiveComponent: one row ofrecursion_profile(): a group of predicates that depend on each other, the statements involved, and whether the loop goes through negation. Profiling recursion.SolveResult: the stream of models thatsolve()returns. Iterate over it, or callfirst(). The model stream.Model: one answer set. Read its atoms withatoms(Cls). Reading models.CostedModel: a model along with its cost, fromoptimize_iter()orsolve(cost_bound=...). Optimization.AtomCollection: the base class of every result you can read atoms from (models, consequences, optima). Use it to accept any of them. Reading models.Consequences: the base class of the results ofbrave()andcautious(), with.pathand.complete. Brave and cautious.BraveConsequences: whatbrave()returns: the atoms that are true in at least one answer set. Brave and cautious.CautiousConsequences: whatcautious()returns: the atoms that are true in every answer set. Brave and cautious.RefinementSteps: whatbrave_iter()andcautious_iter()return: each step of the refinement, as it’s found. Brave and cautious.OptimizeSteps: whatoptimize_iter()returns: each better model, as it’s found. Optimization.Optimum: whatoptimize()returns: the best model found, its cost, and.proven, which says whether it was proven optimal. Optimization.OptStrategy: which algorithm the optimizer uses:BB(the default) orUSC(often faster on hard problems). Optimization.Search: the base class ofSolveResult,RefinementStepsandOptimizeSteps, withclose(),withblocks and the status flags. Use it to accept any of them.LogLevel: the severity of a clingo message.stop_on_log_level=sets which ones are errors. Clingo’s messages.ClingoMessage: one message from clingo..locationis the line of Python responsible; the other fields come from clingo, and may change with it. Clingo’s messages.ASPAlchemyError: the base class of ASPAlchemy’s own exceptions. Mistakes in how you build a program raise ordinary Python exceptions (ValueError,TypeError) instead. Errors that teach.GroundingError: clingo reported a problem while grounding..messageshas the details, each pointing at your Python. Clingo’s messages.UnsatisfiableError: there was no answer set where one was needed (first()and the eager verbs)..unsat_coreholds the conflicting assumptions, if there were any. Unsat cores.SearchIncompleteError: the search stopped before it had an answer. Catch this to handle timeouts and interrupts alike. It says nothing about whether the program has answer sets. Timeouts and interrupts.SearchTimeoutError: the search hit itstimeout=. Timeouts and interrupts.SearchInterruptedError:control.interrupt()stopped the search. Timeouts and interrupts.
Source locations
All of these are explained in Source locations.
SourceLocation: a file and line number. Every statement records one, and diagnostics andrender(annotate=True)show it.capture_location(): get the current location, to pass tolocation_override()later.register_skip_package(): skip over a package (or some of its modules) when recording locations, so they point at whoever called it.attribute_to_caller: a decorator for a function that writes rules on behalf of whoever called it.location_override(): a context manager that attributes everything created inside it to a location you supply.
Declaring predicates
Predicate: the base class for your predicates.Predicate.define()makes one at runtime. Declaring predicates and Dynamic predicates.NegatedSignature: what-Pon a predicate class gives you, for declaring classically negated atoms toraw_asp(). The predicates= seatbelt.Field: the field annotation:Field[int],Field[str],Field[SomePredicate]orField[PredicateArg]. You can pass a variable or other rule term when you create a predicate, but reading a field always gives you a plain value. Type checkers understand this, which is why annotations have to useField. Declaring predicates.field: gives a field a default:note: Field[str] = field(default="hi"). This is the only way to write a default (a plain= "hi"is refused). The fine print.PredicateArg: useField[PredicateArg]for a field that can hold any kind of value: an int, a string, or another predicate. Declaring predicates.
Rule-building objects
Variable: an ASP variable. You can do arithmetic and comparisons with it, and bind it to a pool with.in_(pool). Variables.ANY: the don’t-care variable (clingo’s_). Variables.V: variables without declaring them:V.CellisVariable("Cell"), andV.C[1]gives you numbered names. Variables.Choice: a choice rule. Bound it with comparisons (menu >= 2,2 <= menu <= 4). Choice rules.ConditionalLiteral:p(X) : q(X), for rule bodies andshow_when(). Conditional literals.RangePool: a range of integers, like1..5. Pools and ranges.ExplicitPool: a list of alternatives, like(1;3;5). Pools and ranges.SUP/INF: clingo’s#supand#inf, which sort after and before every other term. Constants and extremes.
Aggregates
All five are explained in Aggregates. Compare one to a value to use it in a rule.
Count:#count, the number of distinct elements.Sum:#sum, the total of the weights.SumPlus:#sum+, the total of the positive weights only.Min:#min, the smallest weight.Max:#max, the largest weight.
Rule-building utilities
pool(): makes the right kind of pool from a Python range, list or tuple. Pools and ranges.Not(): default negation, the same as~. Default negation.Compl(): bitwise complement, which is~in clingo (in Python,~means default negation). Operators and precedence.
Hierarchy types
You’ll mostly use these in type annotations; you rarely need to create them yourself. Here’s how the term types fit together:
- `Term` (abstract base class)
- `ComparableTerm` (abstract: anything that can be compared with `==`, `!=`, `<`, `<=`, `>`, `>=`)
- `Value` (abstract: basic values, which are also `BasicTerm`s)
- `Variable` (e.g., `X`, `Y`)
- `Number` (e.g., `42`)
- `String` (e.g., `"hello"`)
- `DefinedConstant` (e.g., `max_size`, from define_constant())
- `Supremum` / `Infimum` (`#sup`/`#inf`; `SUP` and `INF` are the only instances)
- `Expression` (arithmetic, e.g., `X+Y*2`)
- `Aggregate` (abstract)
- `Count`, `Sum`, `SumPlus`, `Min`, `Max`
- `BasicTerm` (abstract: anything that can be a predicate argument)
- `Predicate` (e.g., `person(john, 42)`)
- `Pool` (abstract)
- `RangePool` (e.g., `1..5`)
- `ExplicitPool` (e.g., `(1;3;5)`)
- `Negatable` (abstract: anything `~` applies to)
- `Comparison` (e.g., `X < Y`, or `#count{ X : p(X) } >= 3`)
- `DefaultNegation` (e.g., `not p(X)`)
- `NegatedAtom` (`not` applied to a single atom, e.g., `not p(1)`)
- `ConditionalLiteral` (e.g., `p(X) : q(X)`)
- `ChoiceBand` (a bounded choice, e.g., `2 { p(X) : q(X) } 4`)
- `Choice` (e.g., `{ p(X) : q(X) }`)
| Symbol | Use it when |
|---|---|
ConditionType |
A parameter accepts a condition: a Predicate atom, a DefaultNegation, or a Comparison. |
ConditionedElement |
You hold one element of a choice or aggregate (what add() builds). |
TupleTermType |
A parameter accepts an aggregate element or optimization term: int, str, Value, Expression or Predicate. |
CardinalityType |
A parameter accepts a bound for a choice (the 2 in menu >= 2): int, Value or Expression. |
Term |
You accept any term at all. |
BasicTerm |
You accept anything that can be a predicate argument. |
Value |
You accept a variable or a constant. See also Atoms as values. |
ComparableTerm |
You accept anything that can appear in a comparison. |
Negatable |
You accept anything ~ applies to: atoms, comparisons and negations. |
ProgramElement |
You hold one statement of a program: a rule, a comment, or a blank line. |
Expression |
You hold arithmetic, like X + Y * 2. See Arithmetic. |
Comparison |
You hold a comparison, including one with an aggregate (Count(...) >= 3, 3 <= Count(...) < 7). See Comparisons. |
ChoiceBand |
You hold a bounded choice (menu >= 2, 2 <= menu <= 4). See Choice rules. |
ChoiceHead |
A parameter accepts what choose() takes: a Choice, with or without bounds. |
Requirable |
A parameter accepts what require() takes: a Comparison or an atom. |
CostBound |
A parameter accepts a cost bound: an int, or a {priority: value} dict. |
NegatedAtom |
You hold not atom (what ~atom and Not(atom) give you). |
AtomLiteral |
A parameter accepts an atom or a NegatedAtom: what assumptions= takes and unsat_core holds. See Ground once, solve many. |
ComparisonOperator |
You name one of the six comparison operators. |
Operation |
You name an arithmetic or bitwise operation. |
DefaultNegation |
You hold a not p(X) literal. See Default negation. |
DefinedConstant |
You hold what define_constant() returns. See Constants and extremes. |
Aggregate |
You accept any of the five aggregates. |
Pool |
You accept either kind of pool. See Pools and ranges. |
Number |
You hold an integer term (a plain int works wherever one is expected). |
String |
You hold a string term (a plain str works wherever one is expected). |
Supremum / Infimum |
You’re annotating SUP or INF. |
Interop with raw clingo symbols
Both are explained in Clingo symbol interop.
convert_predicate_to_symbol(): turns a typed atom into aclingo.Symbol.convert_symbol_to_predicate(): turns aclingo.Symbolinto a typed atom, given a mapping from(name, arity)to predicate class.
Metadata
__version__: the installed version of ASPAlchemy.