API Reference

Curated, task-grouped mirror of __all__ + the API stability statement + the term hierarchy.

API stability

The surfaces you build programs with are stable: the program verbs (fact, when, forbid, choose, solve, optimize, and their relatives), the result types they return, and the predicate-declaration surface. The hierarchy types block is exported so your annotations work, and carries weaker guarantees: these appear in public signatures and return types — annotate with them; you rarely construct them directly. Docstrings are the per-symbol source of truth; this page is the map, not the territory. Changes land version by version in the changelog.

The sections below mirror the categories of aspalchemy.__all__, in order. Each entry is one line — when you reach for this — plus a link to the guide section that teaches it.

The program and its results

  • ASPProgram — the program you build and solve: every verb hangs off it. Taught end to end in Your First Program; the verbs are cataloged in Statements and Terms.
  • Segment — a named slice of a program for organizing large builds; every building verb also lives on a segment. Organizing output.
  • When — the builder when(...) returns; close it with derive(), choose(), forbid(), require(), or penalize(). Rules: when().derive().
  • GroundedProgramground()’s immutable snapshot, for asking many questions of one grounding (assumptions, lazy verbs, inspection). Ground once, solve many.
  • SignatureGrounding — one row of grounding_profile(): a signature’s ground-atom count and the Python lines that derive it. Profiling grounding.
  • StatementGrounding — one row of statement_profile(): a statement’s ground instantiation count and its authoring line; constraints included. Profiling by statement.
  • RecursiveComponent — one row of recursion_profile(): signatures whose derivations depend on each other, the statements in the cycle, and whether the recursion passes through negation. Profiling recursion.
  • SolveResult — the lazy, unbounded model stream solve() returns; iterate it, or take first(). The model stream.
  • Model — one answer set; read typed atoms out with atoms(Cls). Reading models.
  • CostedModel — a model paired with its cost, emitted by optimize_iter() as the search descends. Optimization.
  • AtomCollection — the shared typed-atom reading surface behind models and consequences; subclasses say what their atoms mean. Reading models.
  • Consequences — the common shape of brave/cautious answers: the atoms, .path (every approximation), .complete (proof of exhaustion). Brave and cautious.
  • BraveConsequencesbrave()’s answer: what is possible — atoms true in at least one answer set. Brave and cautious.
  • CautiousConsequencescautious()’s answer: what is certain — atoms true in every answer set. Brave and cautious.
  • RefinementSteps — the lazy handle from brave_iter()/ cautious_iter(): successive approximations, break when satisfied. Brave and cautious.
  • OptimizeSteps — the lazy handle from optimize_iter(): each improvement as it is found, every one a real solution. Optimization.
  • Optimumoptimize()’s answer: the best model found, its cost, and .proven — whether optimality was proved or the search was cut short. Optimization.
  • OptStrategy — how the optimizer searches: BB (branch and bound, the default, anytime) or USC (unsatisfiable cores, often faster on hard optima). Optimization.
  • Search — the abstract lifecycle SolveResult, RefinementSteps, and OptimizeSteps share (close(), with-blocks, the finalized flags); annotate with it to accept any handle.
  • LogLevel — clingo message severities; stop_on_log_level= sets how loud a message must be to abort. Clingo’s messages.
  • ClingoMessage — one structured clingo diagnostic, carrying its severity and the “generated by file:line” pointer back to your source. Clingo’s messages.
  • ASPAlchemyError — the root of ASPAlchemy’s dedicated exceptions; validation and misuse failures deliberately stay on Python builtins. Errors that teach.
  • GroundingError — clingo rejected the rendered program; the message and .messages carry the diagnostics, each mapped to the authoring Python line. Clingo’s messages.
  • UnsatisfiableError — no answer set where one was required (first() and the eager verbs); .unsat_core carries the conflicting assumptions when there are any. Unsat cores.
  • RenderedLine — one line of Segment.render_lines() output: the text plus the element that produced it (None for framing lines). Seeing the ASP.

Source locations

All five are taught in Source locations.

  • SourceLocation — the file:line record every statement is stamped with; what diagnostics and render(annotate=True) display.
  • capture_location() — grab the current user-code location explicitly, to hand to location_override() later.
  • register_skip_package() — declare a package (or dotted module prefix) as plumbing, so statements it emits attribute to its callers.
  • attribute_to_caller — decorator for one helper function that emits rules on its caller’s behalf.
  • location_override() — context manager attributing everything built in the block to a location you captured earlier, for code with no honest stack frame.

Declaring predicates

  • Predicate — the base class every predicate extends; also Predicate.define() for runtime-built schemas. Declaring predicates and Dynamic predicates.
  • NegatedSignature — what -P on a predicate class builds: a declaration of the classically negated signature, for raw_asp()’s predicates= seatbelt. The predicates= seatbelt.
  • Field — typed field annotations: Field[int], Field[str], Field[SomePredicate]; validated writes, plain typed reads. Declaring predicates.
  • PredicateArg — the “any predicate argument” union; the polymorphic field is spelled Field[PredicateArg], so every field is a Field[...]. It reads plain like any field, but skips the ground-type gate and static narrowing — it reads as the value union, not a specific ground type (it still validates int range, string content, and rejects bool/tuple). Declaring predicates.

Rule-building objects

  • Variable — an ASP variable; supports arithmetic, comparisons, and .in_(pool) binding. Variables.
  • ANY — the don’t-care variable (clingo’s _), for slots whose value is irrelevant. Variables.
  • V — variables by attribute: V.Cell is Variable("Cell"), no declaration needed. Variables.
  • Vars — the class behind V: variables by attribute access, with V.C[1] for indexed names. Variables.
  • Choice — the choice-rule builder: the solver’s decision space, with exactly()/at_least()/at_most() bounds. Choice rules.
  • ConditionalLiteralp(X) : q(X) for rule bodies and show_when(). Conditional literals.
  • RangePool — a contiguous range, rendering 1..5. Pools and ranges.
  • ExplicitPool — an explicit alternative set, rendering (1;3;5). Pools and ranges.
  • SUP / INF — clingo’s #sup/#inf, the greatest and least elements of the term ordering. Constants and extremes.

Aggregates

All five are taught in Aggregates; put one in a comparison to make a guard — Guards done right.

  • Count#count: how many distinct elements hold.
  • Sum#sum: the total of weighted elements.
  • SumPlus#sum+: the total counting positive weights only.
  • Min#min: the least weight among elements that hold.
  • Max#max: the greatest weight among elements that hold.

Rule-building utilities

  • pool() — build the right pool automatically from a Python range, list, or tuple. Pools and ranges.
  • Not() — default negation as a function (the ~ operator’s spelling for expressions); on a plain comparison it builds the complement. Default negation.
  • Compl() — bitwise complement, rendering clingo’s ~ (the Python ~ operator is reserved for negation). Doubled, it collapses and hands back the inner term. Operator table, doubled unary operators.

Hierarchy types

The weaker-guarantee block: annotate with these, rarely construct them. The library is built around a hierarchy of term types representing different ASP constructs:

- `Term` (abstract base class)
  - `ComparableTerm` (abstract: usable in comparisons; provides `==`, `!=`, `<`, `<=`, `>`, `>=`)
    - `Value` (abstract, for basic values — also a `BasicTerm`)
      - `Variable` (e.g., `X`, `Y`)
      - `ConstantBase` (abstract)
        - `Number` (numeric constants, e.g., `42`)
        - `String` (string literals, e.g., `"hello"`)
        - `DefinedConstant` (#const-defined constants, e.g., `max_size`)
        - `Supremum` / `Infimum` (`#sup`/`#inf`, the ordering's end markers; `SUP` and `INF` are the singletons)
    - `Expression` (arithmetic expressions, e.g., `X+Y*2`)
    - `AggregateBase` (abstract marker so core can recognize aggregates)
      - `Aggregate` (abstract)
        - `Count`, `Sum`, `SumPlus`, `Min`, `Max`
  - `BasicTerm` (abstract, can be direct predicate arguments: `Value`, `Predicate`, `Pool`)
    - `Predicate` (e.g., `person(john, 42)`)
    - `Pool` (abstract)
      - `RangePool` (e.g., `1..5`)
      - `ExplicitPool` (e.g., `(1;3;5)`)
  - `Negatable` (abstract mixin: `~` builds `not term` on atoms; on plain comparisons it builds the complement — see `Not`)
    - `Comparison` (comparisons, e.g., `X < Y`)
    - `DefaultNegation` (default negation, e.g., `not p(X)`)
  - `ConditionalLiteral` (e.g., `p(X) : q(X)`)
  - `Choice` (e.g., `{ p(X) : q(X) }`)

One line per exported symbol, in __all__ order:

Symbol Annotate with it when
ConditionType A parameter accepts a condition: a Predicate atom, a DefaultNegation, or a Comparison.
ConditionedElement You hold one head-plus-conditions 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 choice bound (exactly()/at_least()/at_most()): int, Value, or Expression.
PredicateTypes You pass the (name, arity) → predicate-class mapping that convert_symbol_to_predicate decodes with.
FieldAsTermType A parameter accepts what a predicate field holds: Value, Predicate, Expression, or Pool.
PredicateOccurrence You consume occurrence collection: a (class, negated, is_atom) triple.
Term You accept any term at all — the hierarchy’s abstract root.
BasicTerm You accept anything usable directly as a predicate argument.
Value You accept a basic value (a variable or constant); equal live values are the same object — see Atoms as values.
ConstantBase You accept any constant but not a variable.
ComparableTerm You accept anything that may appear in a comparison.
Negatable You accept anything ~ applies to.
ProgramElement You hold one rendered statement of a program — a rule, comment, or blank line (see RenderedLine).
Expression You hold arithmetic built from operators on values, like X + Y * 2 — see Arithmetic.
Comparison You hold what a comparison operator on terms builds — see Comparisons.
ComparisonOperator You name one of the six comparison operators.
Operation You name an arithmetic or bitwise operation.
RenderingContext You call a term’s render() yourself and must say where its output lands.
DefaultNegation You hold a not p(X) literal, built by Not()/~ — 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 pool kind — see Pools and ranges.
Number You hold an integer constant term (plain ints auto-coerce on write).
String You hold a quoted-string constant term (plain strs auto-coerce on write).
Supremum / Infimum You annotate the types of the SUP and INF singletons.

Interop with raw clingo symbols

Both are taught in Clingo symbol interop.

  • convert_predicate_to_symbol() — a typed atom → a clingo.Symbol, recursively, sign included, for driving the clingo API directly.
  • convert_symbol_to_predicate() — a clingo.Symbol → a typed atom, given a PredicateTypes mapping to decode with.

Metadata

  • __version__ — the installed package version string (pyproject.toml is the source of truth; version.py reads the installed metadata at runtime).