Public API

Every name DeepLog’s public packages export, with its signature and docstring, on one page. These are the names a release keeps stable. Names appear under the package they are first exported from, so a name re-exported for convenience elsewhere is documented once. For every module, including the machinery behind these names, see the internals.

deeplog

DeepLog’s public API: stating a model, compiling it, running it and extending it.

class Aggregation(
operation: str,
binders: tuple[Symbol, ...],
params: tuple[Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode, ...],
child: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
)[source]

An aggregation over binders applying operation to child.

Unless operation is expectation, its value is its algebra’s aggregator for operation (aggregation_fns) of child and params over every assignment of binders.

Each binder is a variable. binders and params are tuples (not lists) so the node stays hashable and immutable; fold() converts binders back to a list at the factory call boundary. An expectation over binders without a distribution is given the one its binders have independently in probability: the product of a factor v(V) per binder V, where v is V’s name with its leading underscores dropped and its first letter in lowercase.

Raises:

ValueError – If a binder is not a variable.

property structure: str | None

An expectation is a value of its distribution’s algebra, or of probability without one; any other aggregation carries its child’s structure.

class AggregationBuilder(*args, **kwargs)[source]

Builds the modules computing the aggregations of one operation.

Any callable with this signature is a builder.

class AggregationOp(
operation: str,
operands: tuple[Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode, ...],
)[source]

operation applied to operands: its algebra’s aggregator over their values.

Its value is the aggregator for operation (aggregation_fns) of the algebra its operands share, over their values in order, as an Aggregation aggregates its body’s values over the assignments of its binders.

Raises:

ValueError – If there is no operand, since its operands give it its algebra.

property structure: str | None

The structure every operand shares, or None if they disagree.

class Algebra(
*,
name: str,
values: tuple[Symbol, ...] | None = None,
operator_fns: dict[str, Callable[[...], Tensor]] = ...,
aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
constant_fn: Callable[[Symbol], float | None] = ...,
product: str = 'times',
product_fn: Callable[[...], Tensor] = ...,
sum: str = 'plus',
sum_fn: Callable[[...], Tensor] = ...,
zero: Symbol = ('0',),
one: Symbol = ('1',),
negation: str = 'not',
negation_fn: Callable[[...], Tensor] = ...,
)[source]

A semiring with an involutive complement.

negation_fn() → Tensor

Default complement: one - x.

property roles: dict[str, str]

Add the complement.

class AlgebraicStructure(
*,
name: str,
values: tuple[Symbol, ...] | None = None,
operator_fns: dict[str, Callable[[...], Tensor]] = ...,
aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
constant_fn: Callable[[Symbol], float | None] = ...,
)[source]

Defines an algebraic structure: a set of values, with operators and aggregators over them.

values: tuple[Symbol, ...] | None = None

The set of labels a formula over this structure takes (Def 1’s A_R), in value order, or None when they are not finitely enumerable. A variable associated with this structure inherits these as its domain (of_structure()).

operator_fns: dict[str, Callable[[...], Tensor]]

The operators a formula over this structure applies, by name.

aggregation_fns: dict[str, Callable[[...], Tensor]]

The aggregators a formula over this structure can aggregate with (Def 1’s Agg_R), by the operation an aggregation names.

constant_fn() → float | None

Parse single-element numeric symbols as float constants.

property roles: dict[str, str]

The operator name this structure spells each of its roles with.

A role is an operator that an axiom names, so a bare structure declares none: its operator_fns are free-form. Each subclass adds the roles its axioms name, which is how one structure resolves another’s operators — the same product whether it is spelled and or times.

property identities: dict[str, Symbol]

The symbol this structure names each of its identity elements with.

What roles is for operators, this is for the constants an axiom names: an identity crosses between structures by the role it plays, not by the value it happens to have.

get_constant_value(symbol: Symbol) → float | None[source]

The value symbol names, or None when it names an atom.

See ConstantFn for the three answers a caller distinguishes.

Raises:

ValueError – If symbol names a constant this structure does not have.

property operators: frozenset[str]

Return the set of operator names for this structure.

get_operator_fn(
operator: str,
) → Callable[[...], Tensor] | None[source]

Return the torch function for the given operator, or None if not defined.

property aggregations: frozenset[str]

The operations this structure has an aggregator for.

get_aggregation_fn(
operation: str,
) → Callable[[...], Tensor] | None[source]

The aggregator for operation, or None if the structure has none.

apply_substitution(
term: Symbol,
substitution: Mapping[Symbol, Symbol],
) → Symbol[source]

Apply a substitution mapping to a symbolic term.

Parameters:
  • term – The term to perform the substitution on.

  • substitution – A dictionary {…, vi -> ti, …}.

Returns:

A new term where each instance of vi in the original term is replaced with ti.

class Atom(atom: Symbol)[source]

A leaf atom.

atom is the structure-wrapped symbol ("_", inner, (structure,)), exactly as create_atom() receives it. = is symmetric, and an = comparing a written value with a variable holds the variable first: Atom stores =(a, X) as =(X, a), so the two spellings are one atom.

property structure: str | None

The algebraic structure wrapping this atom, or None if it is bare.

class AtomBuilder(*args, **kwargs)[source]

Builds the module computing the atoms of one predicate.

A compiler registers a builder under the predicate it builds. Any callable with this signature is a builder; so is every Predicate subclass.

class BinaryOp(
operator: str,
lhs: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
rhs: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
)[source]

A binary operator combining two operands.

property structure: str | None

The structure shared by both operands, or None if they disagree.

BOOLEAN = Algebra(name='boolean', values=(('false',), ('true',)), product='and', sum='or', negation='not')

The two truth values under and / or / not, with false as zero and true as one, aggregated by exists and forall. The structure a formula is written in before any reading is put on it.

calculate_mgu(term1: Symbol, term2: Symbol) → dict[Symbol, Symbol] | None[source]

Return the most general unifier of term1 and term2, or None.

The unifier is the substitution s with apply_substitution(term1, s) == apply_substitution(term2, s) that every other such substitution refines. None means the terms do not unify. Variables are identified by name, so every _ is the same variable.

There is no occurs check. Unifying a variable with a term containing it is not supported: it may raise RecursionError, or return a substitution apply_substitution() cannot apply.

class Compiler(
variables: Mapping[Symbol, Domain] | None = None,
reification: AlgebraicStructure = Algebra(name='boolean', values=(('false',), ('true',)), product='and', sum='or', negation='not'),
structures: Mapping[str, AlgebraicStructure] | None = None,
aggregation_builders: Mapping[str, AggregationBuilder] | None = None,
atom_builders: Mapping[tuple[str, int, str], AtomBuilder] | None = None,
transformation_builders: Mapping[tuple[str, str], TransformationBuilder] | None = None,
)[source]

Compiles formulas to one module, with the domains, algebras and builders to use.

variables declares the domain each binder ranges over; a binder it does not declare is a reification variable, ranging over the values of reification. structures names the algebras a formula may use beside the registered ones, and wins over them. atom_builders, aggregation_builders and transformation_builders add builders, keyed by predicate, operation and pair of algebras, and each wins over the default registered for its key. An aggregation whose operation has no builder is computed by reduction().

The value test =/2 is the compiler’s own: it reads a variable’s value as its position in the variable’s domain (domain()), which only the compiler knows.

An atom no builder computes is an input of the compiled module, named by the atom. Where it reads variables an aggregation binds, it is its ground atoms instead, an input each, named by substituting those variables’ values, and read at the values the aggregation gives them; such a variable must range over named values.

Every argument of an atom has a sort, the domain its predicate declares for it (domains_of()). A variable ranges over its domain in variables, or else over the named or tensor domain of the arguments it is that each of the others includes; each must include the variable’s domain, and a variable over part of a named one reaches its predicate as a position in it. An argument of sort the values takes a variable over values without names. A variable that no argument gives a domain ranges over its declared one, or, if it is bound and only = tests it, over the values of reification. A variable an aggregation binds is that aggregation’s own, so two aggregations binding one name may give it different domains; a free variable is one variable in every formula compiled together (Sorts).

Configure the compiler with the domains, algebras and builders to use.

compile(
formulas: Mapping[str | Symbol, Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode],
/,
) → DeepLogModule[source]
compile(
*formulas: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
) → DeepLogModule

Compile formulas to one module with a column per formula, in order.

Given as one mapping, each formula’s column is named by its key, a symbol or the text of one; given as formulas, the i-th column is named @i. A name is labelled with the algebra of its column, as rain_implies_wet _ probability, and equal formulas compile once, whatever their names.

Each formula is constructed bottom-up by folding it through a CircuitFactory, which rewrites every region a circuit can hold into a lump, and the results are lowered together, top-down (Lowering). Equal subformulas of all the formulas are first made one object, and construction runs under one memo, so a subformula is built once however many formulas write it, their shared atoms are one circuit leaf, and counts over one boolean circuit take one knowledge compilation. The atoms whose builder’s module reads none of their variables are computed before any aggregation, by one module per predicate, so a network fed no variable runs once per input, however many aggregations read it and however deep.

Raises:
  • TypeError – If a mapping is given beside formulas.

  • ValueError – If two formulas are given one name, or a name is labelled with an algebra its formula’s value is not in.

domain(binder: Symbol) → Domain[source]

The domain binder ranges over.

A binder the compiler declares in its variables uses that domain. Any other binder is a reification variable, and inherits the values of the compiler’s reification algebra as its domain.

Raises:

ValueError – If the binder is undeclared and the reification algebra declares no enumerable values.

algebra(name: str) → AlgebraicStructure[source]

The algebra named name: the compiler’s own, else the registered one.

Raises:

ValueError – If name is neither the compiler’s own nor registered.

atom_builder(
functor: str,
arity: int,
structure: str,
) → AtomBuilder | None[source]

The builder of the functor/arity atoms in structure, or None.

declaring(
variables: Mapping[Symbol, Domain] | None = None,
atom_builders: Mapping[tuple[str, int, str], AtomBuilder] | None = None,
) → Compiler[source]

A copy of this compiler that also declares variables and atom_builders.

For a front end that introduces binders and predicates of its own, whose caller cannot know them. Its builders shadow the compiler’s defaults, such as p/2 in probability for a program’s own p/1 extended with a binder. This compiler is left as it is.

Raises:

ValueError – If a binder is already declared with another domain, or this compiler was given a builder for one of the keys.

compose_modules(
modules: Iterable[DeepLogModule],
output_shape: Shape,
input_shape: Shape | None = None,
) → DeepLogModule[source]

Compose modules into one module taking input_shape and producing output_shape.

Each symbol is produced by at most one module. The composed module’s inputs are the symbols no module produces. input_shape lays them out, and must hold each of them and none a module produces; without it, each is a tensor of its own, in the order the modules first read them. A single module is reshaped to the requested shapes, and returned as it is when it already has them; several become a ModuleCircuit, which orders them by what each one’s inputs need and inserts the transformations between them.

A capitalised name is a variable. A module whose output holds a variable none of its inputs hold binds it, and gives its values along an axis behind its symbols. A value holding the variable then has an axis for it after its batch, and a module reading such a value runs on a row per value of it. Calling the composed module raises ValueError where a module binding a variable gives no axis for it.

Raises:

ValueError – If no module is given, two modules produce one symbol, or input_shape holds a symbol a module produces.

class DeclaresDomains(*args, **kwargs)[source]

A module that declares the domain each argument of its atoms ranges over.

Every Predicate is one, and every module an atom builder returns is: the compiler gives each variable the domain of the arguments it is (Sorts).

domains_of(arguments: tuple[Symbol, ...], /) → tuple[Domain, ...][source]

The domain each argument of an atom with arguments ranges over.

class DeepLogModule(input_shape: Shape, output_shape: Shape)[source]

A class that extends Torch modules to include information about its input and output shape.

Capture the symbolic input and output shapes for the module.

Registers shape-validation forward hooks when DEEPLOG_VALIDATE is enabled (the default). Disable via DEEPLOG_VALIDATE=0 in the environment.

Validation adds ~1.5 µs per forward call (a small constant for the input/output correct_shape checks). For typical workloads where each forward does real computation, this is well under 1% overhead; disabling matters only in tight micro-benchmarks over many trivial modules. The env var is consulted in __init__, so changing it after import only affects newly-constructed instances.

get_input_shape() → Shape[source]

Returns the input shape of this module.

get_output_shape() → Shape[source]

Returns the output shape of this module.

to_graph(graph=None)[source]

Add this module to the provided Graphviz graph and return connection nodes.

replace_input_shape(new_input_shape: Shape) → None[source]

Replace the declared input shape without adding transformations.

replace_output_shape(new_output_shape: Shape) → None[source]

Replace the declared output shape without adding transformations.

class Domain[source]

The values a variable ranges over, in value order.

static of(
values: Iterable[Symbol | str | int],
) → Domain[source]

A domain of named values, in the given order.

static of_tensor(values: Tensor) → Domain[source]

A domain whose values are the rows of values and have no names.

static of_values() → Domain[source]

The open domain of values without names, such as numbers or images.

It is never enumerated, so a variable over it is free: the caller gives it its value.

static of_structure(
structure: AlgebraicStructure,
) → Domain[source]

The domain a variable associated with structure inherits.

Raises:

ValueError – If structure declares no values, i.e. they are not finitely enumerable, so a variable over it needs a domain of its own.

abstractmethod as_tensor() → Tensor[source]

The values as an enumerable tensor, one row per value.

property values: tuple[Symbol, ...]

The symbol writing each value, in value order.

Raises:

ValueError – If this domain’s values have no names.

index(value: Symbol) → int[source]

The position of the value value writes.

Raises:

ValueError – If this domain’s values have no names, or value writes none of them.

enumeration(
nodes: Sequence[Aggregation],
lowering: Lowering,
) → list[tuple[DeepLogModule, int]][source]

Exact, by evaluating the body at every combination of its variables’ outcomes.

Each variable’s factor is evaluated at every value of its binders, and the body at every combination, missing outcomes included.

Raises:

ValueError – If an expectation’s body is not boolean, it has more than one param, its distribution’s algebra has no sum and product, one of its binders has no factor, or a leaf that is not boolean reads a binder that may have no value.

class EqualityPredicate(
atoms: Iterable[Symbol],
domain_of: Callable[[Symbol], Domain],
)[source]

Whether the two arguments of an atom name the same value.

Both arguments range over the domain of the variable the atom compares, so a written value compared with a variable is read as the variable’s value is. Two written values range over the names they write, so they compare by name.

Compare the arguments of each atom, domain_of giving each variable’s domain.

Raises:

ValueError – If a written value is not a value of the domain of the variable it is compared with, or two variables compared with each other range over different domains.

resolve_arguments(
arguments: tuple[Symbol, ...],
/,
) → tuple[Symbol | int | float | bool | Tensor, ...][source]

The two arguments as variables, or as the values the variables are compared with.

forward_predicate(
lhs: Tensor,
rhs: Tensor,
) → Tensor[source]

Return a tensor of equality results between the two arguments.

flatten_symbol(
symbol: Symbol,
functor: str | None = None,
) → Iterable[Symbol][source]

Flattens a tree of functor/2 symbols into an iterable.

FormulaNode = deeplog.formula.ast.Atom | deeplog.formula.ast.UnaryOp | deeplog.formula.ast.BinaryOp | deeplog.formula.ast.Transformation | deeplog.formula.ast.AggregationOp | deeplog.formula.ast.Aggregation | deeplog.formula.ast.CircuitNode

A formula node is either still-symbolic (Atom/UnaryOp/BinaryOp/ Transformation/AggregationOp/Aggregation) or a graph-backed CircuitNode, whose fine internal structure lives in the circuit rather than nested objects.

Every node exposes a .structure property (str | None) — the symbolic-layer counterpart to the module layer’s sole_structure() over a module’s output symbols. Both read a label off data rather than off an object — an AST node carries it on its atom, a module on the symbols naming its outputs.

get_all_symbols(
shape: Shape | Iterable[Shape],
) → Iterator[Symbol][source]

Yield every symbol contained in shape.

get_predicate(symbol: Symbol) → tuple[str, int][source]

Return the predicate functor and arity for the given symbol.

get_term_variables(symbol: Symbol) → Iterable[Symbol][source]

Returns an iterable of all variables that appear in Symbol. These are not unique.

GODEL = Algebra(name='godel', values=None, product='and', sum='or', negation='not')

Gödel’s fuzzy logic, truth values in [0, 1] under the minimum t-norm. and is the t-norm, or its dual conorm, the maximum, not the standard negation 1 - x, and implies the t-norm’s residuum, the greatest c with a and c <= b. forall is the t-norm over a variable’s domain and exists the conorm. The minimum distributes over the maximum, so this is an Algebra.

is_variable(symbol: Symbol) → bool[source]

Return whether symbol represents a variable.

LOGPROBABILITY = _ComplementedSemifield(name='logprobability', values=None, product='times', sum='plus', division='divide', negation='negate')

PROBABILITY in log space, where a product adds and a sum is logaddexp, so sum aggregates by log-sum-exp. Zero is -inf and one is 0.

class LogProbabilityPredicate(atoms: Iterable[Symbol])[source]

(atom, label) predicate with log-probability-space outputs.

Weigh the truth value of each atom by its label.

class Lowering(compiler: Compiler)[source]

One compile’s walk: lowers constructed formulas top-down, a level at a time.

An aggregation builder receives the walk, and lowers through lower() what its method needs, with the domains and builders of its compiler, which declares the domain of each binder of the aggregations it builds.

The walk’s handlers mirror the construction factory’s eliminators, one per AST type, but each receives every node of its type in a level, unlowered:

  • atoms go to their atom builders, one call per predicate;

  • unary and binary operators become the algebra’s operator functions, read over their operands’ columns;

  • aggregations of operands become the algebra’s aggregators, one module reading all their operands’ columns;

  • casts go to the builder registered for their pair of algebras;

  • aggregations go to the builder registered for their operation, one call per operation, apart from those where one binds a variable another reads free, or two bind one name over different domains;

  • lumps of one circuit compile into one core, apart from a lump that reads another of its circuit through a cast.

Lower with compiler’s domains, algebras and builders.

property compiler: Compiler

The compiler whose domains, algebras and builders this walk lowers with.

lower(
*nodes: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
) → DeepLogModule[source]

One module with a column per node, in the order given.

A variable free in nodes that the compiler does not declare ranges over the domain its arguments there give it, from then on.

Raises:

ValueError – If two nodes name one column.

LUKASIEWICZ = AlgebraicStructure(name='lukasiewicz', values=None)

Łukasiewicz’s fuzzy logic, GODEL’s connectives and quantifiers under the t-norm max(0, a + b - 1), whose conorm is the bounded sum min(1, a + b). As with PRODUCT, this is no Semiring.

MPE = _ComplementedSemifield(name='mpe', values=None, product='times', sum='plus', division='divide', negation='negate')

Max-product — the most probable explanation. A semiring like any other, so a knowledge-compiled formula reaches it through the ordinary transform rather than through a compile-time override — max in place of a sum keeps the single best explanation where plus would total them all, and sum aggregates by it too.

class NetworkPredicate(
atoms: Iterable[Symbol],
*,
module: Module,
domain: Domain,
)[source]

Predicate whose values are the output rows of a provided torch.nn.Module.

Always binary: the first argument is fed to the module, and the second is a value of domain, which lists the values of the module’s output rows in row order. digit(x, v) is the entry of x’s row at v’s position.

It reads only the first arguments of the atoms it is given, and computes every value of each, running the module once per distinct first argument: asked for digit(i1, 2) and digit(i2, D), it computes digit(i1, 0) to digit(i1, 9) and digit(i2, 0) to digit(i2, 9), in that order. A second argument only asks for an atom: a written value must be one of the domain’s, written as the domain writes it (values), and a variable may stand there.

Compute every value of each first argument of atoms through module.

Raises:

ValueError – If domain does not write its values, an atom is not binary, its first argument is a written number, which names no input, or its second is a written value not in domain.

forward_predicate(inputs: Tensor) → Tensor[source]

The module’s output on inputs, a row of one entry per value for each.

Raises:

ValueError – If the module’s output does not have one row per input of one entry per value of the domain.

OPEN: Symbol = ('_',)

The term position an occurrence leaves open for the variable’s value.

parse_dimacs_cnf(
dimacs: str,
) → Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode[source]

Parse dimacs into the boolean formula of its clauses.

Variable i is the variable Vi, and the literal i its test =(Vi,true), so expectation(V1, ..., Vn): φ is the probability that the formula φ holds when each Vi is true with probability vi(true). A negative literal is the negation of its test, a clause the disjunction of its literals, and the formula the conjunction of its clauses. An empty clause is false, and a clause holding a literal and its negation true.

Raises:

ValueError – If dimacs is not well-formed DIMACS CNF.

parse_formula(
text: str,
) → Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode[source]

Parse text into a formula.

Equal subformulas are interned to one object via hash_cons(), so the formula is a value-keyed DAG rather than a tree.

parse_formula_to_module(
text: str,
compiler: Compiler | None = None,
*,
name: str | Symbol | None = None,
) → DeepLogModule[source]

Parse text and compile it: compiler.compile(parse_formula(text)).

compiler defaults to a Compiler with the default builders. With name, the module’s column is named by it, as compiler.compile({name: parse_formula(text)}) names it.

parse_symbol(
symbol_str: str,
parse_argument: Callable[[str], Symbol] | None = None,
) → Symbol[source]

Read the symbol symbol_str.

A symbol is a constant or variable a, a compound term f(a, b), a list [a, b | T], or a structure-tagged symbol a _ s, and brackets around a symbol group it. Text without brackets that is none of these, such as X is Y, is one constant.

Parameters:
  • symbol_str – The text to read.

  • parse_argument – Reads each argument, list element, side of _ and bracketed symbol; parse_symbol() itself by default.

Raises:

ValueError – If a term’s arguments are not closed, text follows the bracket closing them, or brackets enclose nothing.

class Predicate(
atoms: Iterable[Symbol],
domains: Sequence[Domain] | Callable[[tuple[Symbol, ...]], Sequence[Domain]],
*,
ignore_arguments: Iterable[int] | None = None,
)[source]

Base class for predicates backed by torch computations or constants.

A predicate computes the atoms it is given, a column named by each, from their arguments. A compiler registers it under the predicate it computes.

Subclasses parameterize the generic with the tuple of tensor types that forward_predicate() will receive — one entry per non-ignored argument position. Example: class MyPred(Predicate[torch.Tensor, torch.Tensor]): declares a binary predicate.

An argument position asks for each distinct symbol once, not once per evaluation: digit(i1,0) … digit(i1,9) are ten evaluations over one input, so the input shape holds i1 once. Positions are expanded back to one row per evaluation before forward_predicate() sees them.

Each argument ranges over a domain, its sort (domains_of()). A value written where it ranges over a named or a tensor domain is read as what a variable there holds: the domain’s element it writes (index()), its position among the domain’s names or the domain’s own number, in the domain’s dtype. So an atom reads the same whether an aggregation feeds its variable a value or the value is written into it. Where it ranges over the values (of_values()), a written argument is what resolve_argument() says: by default a number it writes, or else the name of an input.

Compute atoms, a column named by each, from their arguments.

domains gives the domain of each argument, one per argument of the atoms, or is a function giving them for one atom’s arguments (domains_of()).

Raises:

ValueError – If atoms is empty or its atoms differ in arity, domains gives an atom other than one domain per argument, or a value written where an argument ranges over a named or a tensor domain is not one of its values.

forward(*x: Tensor) → Tensor[source]

Evaluate the predicate for all provided arguments and return batched results.

A position whose input names no symbol holds only constants, and its tensor, which carries no values, is not read.

eager_eval(
tensors: Mapping[Symbol, Tensor] | None = None,
) → Tensor[source]

Evaluate eagerly, resolving any free symbols via tensors.

Free symbols (positions where resolve_argument returned a Symbol rather than a constant) are looked up in tensors and stacked into the input batch for that position. Constant positions use the buffers populated during __init__.

Returns a tensor of shape [n_evaluations, *output_shape]. Raises KeyError if a free symbol is missing from tensors.

domains_of(
arguments: tuple[Symbol, ...],
/,
) → tuple[Domain, ...][source]

The domain each argument of an atom with arguments ranges over.

Raises:

ValueError – If the predicate gives other than one domain per argument.

resolve_arguments(
arguments: tuple[Symbol, ...],
/,
) → tuple[Symbol | int | float | bool | Tensor, ...][source]

What each argument of one atom stands for.

A value written where an argument ranges over a named or a tensor domain (domains_of()) is read as what a variable there holds; a variable, and an argument written where it ranges over the values, is what resolve_argument() says. An ignored position keeps its symbol. A subclass whose reading of one argument depends on another in a way other than through its domain overrides this.

Raises:

ValueError – If a value written where an argument ranges over a named or a tensor domain is not one of its values.

resolve_argument(
symbol: Symbol,
index: int,
/,
) → Symbol | int | float | bool | Tensor[source]

What the argument symbol at position index of an atom stands for.

It is asked for a variable, and for an argument written where it ranges over the values (domains_of()). A subclass overrides this to give such arguments other constant values. By default a written number is that number, and any other argument is a variable, read from the input under its symbol.

Returns:

A symbol, which makes the argument a variable read from the input under that symbol, or a value, which makes it a constant: a tensor is used as it is, and a number or a boolean as a scalar.

abstractmethod forward_predicate(*args: Tensor) → Tensor[source]

Batched implementation of the predicate.

Receives one tensor per non-ignored argument position, in argument index order, with constants and symbol values already substituted. Concrete subclasses can still document or narrow the individual tensor argument types they expect.

PROBABILITY = _ComplementedSemifield(name='probability', values=None, product='times', sum='plus', division='divide', negation='negate')

Probabilities in [0, 1] under times and plus, with negate the complement 1 - p, aggregated by sum. Its product is invertible, which is what a conditional needs to divide by its evidence.

class ProbabilityPredicate(atoms: Iterable[Symbol])[source]

(atom, label) predicate with probability-space outputs.

Weigh the truth value of each atom by its label.

PRODUCT = AlgebraicStructure(name='product', values=None)

Product fuzzy logic, GODEL’s connectives and quantifiers under the product t-norm, whose conorm is the probabilistic sum a + b - a * b. The product does not distribute over that sum, so this is no Semiring.

REAL = Semiring(name='real', values=None, product='times', sum='plus')

The real numbers under times and plus, aggregated by sum. A network’s pre-activation output is real, and so is a count, since the boolean -> real cast reads true as 1 and false as 0. Its values are not finitely enumerable.

reduction(
nodes: Sequence[Aggregation],
lowering: Lowering,
/,
) → list[tuple[DeepLogModule, int]][source]

Compute each aggregation by reducing its operands over its binders’ values.

The operands of the aggregations over the same binders are lowered together, each with an axis for every one of those binders free in it, which the aggregation’s algebra reduces with its aggregator for the aggregation’s operation (AggregationFn). So each subformula is evaluated once per assignment of the binders free in it, and aggregations over the same binders evaluate what they share once. An atom that holds binders at arguments of sort a named or a tensor domain is read from its ground atoms, one for each combination of those binders’ values, which its builder receives in its place; a binder whose values cannot be written, as rows of a tensor that are not numbers, is not among them. A compiler computes this way every operation it has no other builder for.

Raises:

NotImplementedError – If an aggregation’s algebra has no aggregator for its operation.

reshape(
module: DeepLogModule,
input: tuple[SymTensor, ...] | SymTensor | None = None,
output: tuple[SymTensor, ...] | SymTensor | None = None,
) → DeepLogModule[source]

Wrap module so its input and/or output shape matches the requested shapes.

Parameters:
  • module – The module whose input and/or output should be reshaped.

  • input – If provided, the new input shape for module.

  • output – If provided, the new output shape for module.

Returns:

A module that performs identically to the given module under the requested shapes.

sampling(
samples: int,
*,
gradient: Callable[[Tensor, Tensor], Tensor] = ...,
) → AggregationBuilder[source]

The builder estimating each expectation from samples drawn assignments.

An expectation whose distribution is in probability, as one without a distribution is, is sampled. Each variable’s outcome, missing included, is drawn with probability its weight divided by the total; the estimate is the mean of the body over the draws, times those totals. Expectations whose variables agree where they share binders read the same draws, so the ratio of two is estimated on one set of assignments. Every other expectation is enumerated.

gradient receives the values of the bodies at the draws and the log-probability of drawing them, both of shape (batch, samples, expectations), and returns values equal to the first whose gradient estimates the expectations’.

Raises:

ValueError – If samples is not positive.

score_function(values: Tensor, log_probability: Tensor) → Tensor[source]

The score-function estimator, with the other draws’ mean as its baseline.

values are what each expectation’s body takes at each drawn assignment and log_probability the log-probability of drawing it, both of shape (batch, samples, expectations). The result equals values, and its gradient adds each draw’s log-probability gradient, weighted by how far its value lies from the mean of the other draws. That mean does not depend on the draw, so the estimate stays unbiased; a single draw has no baseline.

class Semifield(
*,
name: str,
values: tuple[Symbol, ...] | None = None,
operator_fns: dict[str, Callable[[...], Tensor]] = ...,
aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
constant_fn: Callable[[Symbol], float | None] = ...,
product: str = 'times',
product_fn: Callable[[...], Tensor] = ...,
sum: str = 'plus',
sum_fn: Callable[[...], Tensor] = ...,
zero: Symbol = ('0',),
one: Symbol = ('1',),
division: str = 'divide',
division_fn: Callable[[...], Tensor] = ...,
)[source]

A semiring whose product is invertible, so division is defined.

Independent of Algebra: an invertible product says nothing about a complement. An algebra that divides differently supplies its own division_fn.

division_fn(b: Tensor) → Tensor

Default division, flooring the denominator at the smallest normal value.

Derived per dtype, not pinned: a constant 1e-12 stores as exactly zero in float16, where the clamp would silently do nothing. Bounds the forward pass only — the gradient still overflows just above the floor.

property roles: dict[str, str]

Add the division.

class Semiring(
*,
name: str,
values: tuple[Symbol, ...] | None = None,
operator_fns: dict[str, Callable[[...], Tensor]] = ...,
aggregation_fns: dict[str, Callable[[...], Tensor]] = ...,
constant_fn: Callable[[Symbol], float | None] = ...,
product: str = 'times',
product_fn: Callable[[...], Tensor] = ...,
sum: str = 'plus',
sum_fn: Callable[[...], Tensor] = ...,
zero: Symbol = ('0',),
one: Symbol = ('1',),
)[source]

A semiring: a product and a sum with their identities.

product_fn(b: Tensor) → Tensor

Default semiring product: ordinary multiplication.

sum_fn(b: Tensor) → Tensor

Default semiring sum: ordinary addition.

property roles: dict[str, str]

Add the product and the sum.

property identities: dict[str, Symbol]

Add the sum’s and the product’s identities.

class Sequential(*submodules: DeepLogModule)[source]

Chains multiple DeepLogModules so each submodule consumes the previous output. Functions similarly to torch.nn.Sequential.

Chain the provided submodules, flattening nested Sequential containers.

to_graph(graph=None)[source]

Render the composed modules into a graph, chaining edges in order.

forward(*inputs)[source]

Run the input tensors through each submodule sequentially.

Shape = Shape

What a module declares it reads and writes — one SymTensor naming a single tensor’s symbols, or a tuple of them, one per tensor.

class ShapeMismatchException(
shape: Shape,
args: tuple[Tensor],
location: object = None,
)[source]

Raised when tensors do not conform to the shape that named them.

Build the message: what shape named, what args were, and where.

location is whatever identifies the site for a reader of the message; a module reports (module, "input") or (module, "output").

structure_of(symbol: Symbol) → str | None[source]

Return the algebraic structure symbol is labelled with, or None.

The total read of the ("_", inner, (structure,)) tag: a bare symbol names a value that lives in no algebra, which is a legitimate state outside the formula layer, so absence is reported rather than raised. Counterpart of with_structure().

Symbol = Symbol

A term as a nested tuple — a functor followed by its arguments, each a symbol in turn. ("digit", ("i1",), ("3",)) is digit(i1,3), and a bare ("a",) is the constant a.

symbol_to_pretty_string(symbol: Symbol) → str[source]

Format symbol for a human reader, infixing the functors that read better.

Not the inverse of parse_symbol(); symbol_to_str() is the form that parses back.

symbol_to_str(symbol: Symbol) → str[source]

Format symbol as the text parse_symbol() reads back.

A compound term is f(a,b), whatever its functor, so is(X,Y) for X is Y, and a structure tag is a _ s. Brackets group an operand that would read otherwise: a side of a tag that is itself tagged, as in (a _ s) _ t, and an argument whose functor holds a comma, as in f((,(a,b))). A functor holding a bracket does not read back.

Use symbol_to_pretty_string() for human-readable output.

class SymbolDict[source]

A {Symbol: tensor} mapping that prints symbols and scalars compactly.

A plain dict in every other respect; to_dict() returns one so interactive readouts (print(to_dict(module(x), shape))) stay legible.

class SymTensor(symtensor_like: SymTensorLike, subtensor_shape: tuple[int, ...] | None = None)[source]

Numpy-backed container that represents symbolic tensor indices.

Creates a symbolic tensor from a SymTensor-like input. If an array-like input of strings is given, then parse_symbol will be used to construct symbols. This flexibility can lead to an ambiguous cases, e.g. with symtensor_like = (‘a’,) which can be interpreted as scalar SymTensor of the constant a, or parsed into a 1-dimensionsal symtensor [a]. In these cases, it will first consider the input to be an array-like of symbols. To avoid this ambiguity, use nested lists instead of tuples as input.

Parameters:
  • symtensor_like – An object that can be cast to a SymTensor.

  • subtensor_shape – The shape of the sub-tensors.

property array: NDArray[object_]

The underlying numpy array of symbols.

is_empty() → bool[source]

Return True if this SymTensor contains no symbolic entries.

SymTensorLike = SymTensorLike

Anything SymTensor accepts as its symbols — a SymTensor, a symbol, a string parsed as one, a nested sequence of those, or a numpy object array.

to_dict(
tensors: Tensor | Sequence[Tensor],
shape: Shape,
) → SymbolDict[source]

Split result tensors into a per-symbol dict following shape.

The read-out counterpart of shape validation: shape (typically a module’s get_output_shape()) names every entry of tensors, and each symbol maps to its entry with the batch dimension preserved — to_dict(module(x), module.get_output_shape()) reads a module’s output by name. The result is a SymbolDict, a plain dict that prints readably.

Raises ShapeMismatchException when the tensors do not conform to shape and ValueError when shape names the same symbol twice.

to_symbol(arg: Symbol) → Symbol[source]
to_symbol(arg: str) → Symbol
to_symbol(arg: list[str] | list[Symbol]) → list[Symbol]

Turn the given argument into a symbol (or list of symbols).

class Transformation(
structure: str,
child: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
)[source]

A structure-conversion node mapping child into structure.

class TransformationBuilder(*args, **kwargs)[source]

Builds the module casting values between the pair of algebras it is keyed by.

Any callable with this signature is a builder.

class TransformationNotPossible(
in_shape: SymTensor | tuple[SymTensor, ...],
out_shape: SymTensor | tuple[SymTensor, ...],
)[source]

This exception is raised when a requested transformation is not possible.

Record the incompatible input/output shapes that triggered the failure.

class UnaryOp(
operator: str,
operand: Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode,
)[source]

A unary operator applied to a single operand.

property structure: str | None

A unary operator carries its operand’s structure.

class Variable(name: Symbol, domain: Domain)[source]

A model variable and the domain it ranges over.

A variable owns no atoms. An atom is a predicate applied to terms, and a term may be a variable, so a variable is linked to an atom by occurring in it – see VariableAtoms. Nothing pairs a value with an atom: the atom asserting a value is what substituting that value into an occurrence yields.

VariableAtoms = VariableAtoms

Where each variable occurs — the atoms it appears in, with its own term position left OPEN. digit(i1,_) is the occurrence of the variable digit(i1) over 0 ... 9, and digit(i1,3) – the atom asserting the value 3 – is what substituting yields.

A variable may occur in several atoms and an atom may be an occurrence of several variables, so neither direction is a function. In the degenerate case the occurrence is OPEN: the whole atom is the variable’s position, so the values are the atoms, which is what a disjunction over unrelated atoms declares.

weighted_model_count(
nodes: Sequence[Aggregation],
lowering: Lowering,
) → list[tuple[DeepLogModule, int]][source]

Exact: knowledge-compile each group’s bodies into their distribution’s algebra.

An expectation is counted when its body is a boolean circuit lump, every leaf of which tests one of its binders for a named value of the binder’s domain, and its distribution, in probability or log-probability, is a product of atoms, one for each binder and mentioning only that binder, as an argument. The leaf testing V for v then weighs as V’s factor with v substituted, which its predicate reads as V holding v, since the argument’s sort is V’s domain. Expectations over one circuit, counted into one algebra, whose factors agree on the binders they share, are one group, and each group takes one knowledge compilation. A group reaching two values of one binder compiles with mv-sdd, which pydeeplog[mvsdd] installs. Every other expectation, and every one in a group whose knowledge compiler is not installed, is enumerated (enumeration()).

with_structure(atom: Symbol, structure: str) → Symbol[source]

Return atom wrapped with structure, replacing any existing wrapper.

without_structure(symbol: Symbol) → Symbol[source]

Return symbol with any structure tag removed.

The tolerant counterpart of unwrap_structure(): a bare symbol is returned unchanged. Used when re-minting a name from a labelled one, so the tag is re-applied to the outside rather than buried in the new symbol.

class WrappedModule(
module: Callable,
input_shape: Shape,
output_shape: Shape,
name: str | None = None,
vmap: bool = False,
)[source]

Wrap an arbitrary callable with DeepLogModule shape semantics.

Wrap a callable with declared shapes and optional vmap execution.

name defaults to the callable’s own __name__ when it has one (a function or a class), and to its type name otherwise — an nn.Module instance is a callable without a __name__, so wrapping one must not force the caller to invent a label.

forward(*args, **kwargs)[source]

Delegate execution to the wrapped callable.

deeplog.circuit

Algebraic circuits: build one, knowledge-compile it, move it into another algebra, and evaluate it as a torch module.

class Circuit(structure: str | AlgebraicStructure)[source]

Circuit implementation using an internal graph for efficient construction.

Conversion to torch modules happens via to_module(), which evaluates the circuit as written — in the semiring Klay implements for its structure, or node by node through the structure’s own operator_fns.

Create a circuit configured for the given structure.

The circuit is evaluated as written: its operators mean what the structure’s operator_fns say they mean.

Parameters:

structure – The algebraic structure (name or AlgebraicStructure instance).

property structure: AlgebraicStructure

Return the algebraic structure of this circuit.

Callers wanting the registry name use circuit.structure.name.

property leaf_nodes: dict[Symbol, int]

Mapping of leaf symbols to node IDs, keyed by their tagged name.

Leaves are stored bare; the keys here carry the circuit’s structure tag re-appended (_tagged_leaf_name()), so a predicate leaf appears under its wrapped name — the spelling the module boundary matches on.

get_leaf_name(node_id: int) → Symbol | None[source]

Return the bare canonical leaf symbol for a node ID, or None.

This is the leaf’s identity with its redundant structure tag stripped. For the structure-tagged boundary spelling use get_symbol_name() or leaf_nodes.

get_symbol_name(node_id: int) → Symbol | None[source]

Return the formula symbol represented by a leaf or constant node.

Both are stored bare and returned with the circuit’s tag re-appended, so formula-level views expose leaves and constants uniformly as atoms.

reachable_leaf_names(roots: list[int]) → list[Symbol][source]

Named leaves reachable from roots, in topological order (no constants).

The leaves-only boundary view as plain symbols. Contrast reachable_symbol_names(), which also yields constants.

reachable_symbol_names(roots: list[int]) → list[Symbol][source]

Leaf and constant symbols reachable from roots, in topological order.

The generic boundary walk for formula-level views (CircuitNode children): every named leaf and constant once. Contrast reachable_leaf_names(), which omits constants.

get_leaf_node(name: Symbol) → int[source]

Return a node ID for the given symbol, creating it if needed.

A structure-wrapped name (("_", inner, (structure,))) must carry this circuit’s own structure, or ValueError is raised. The tag is then stripped and the bare inner symbol stored as the canonical leaf identity, so both spellings of an atom resolve to one shared node. Boundary views re-append the tag (_tagged_leaf_name()), so the module input shape still matches its predicate modules.

get_operator(operator: str) → Callable[[...], int][source]

Return a callable that applies the requested operator.

Parameters:

operator – The operator name (e.g., “and”, “or”, “not”).

Returns:

A callable that takes node IDs and returns a new node ID.

property constant_values: dict[int, float]

Mapping of node IDs to their constant float values.

property zero_node: int | None

Node ID of the additive identity, or None if not materialized.

property one_node: int | None

Node ID of the multiplicative identity, or None if not materialized.

operation(node_id: int) → tuple[str, tuple[int, ...]][source]

What the node with the given ID is, and the nodes it applies to.

The first is an operator of the circuit’s structure, or leaf or constant, which apply to no node.

to_module(
roots: dict[int, Symbol],
) → DeepLogModule[source]

Convert the circuit to a DeepLog module, evaluating it as written.

Parameters:

roots – A dictionary mapping node IDs to output names.

Returns:

A DeepLogModule wrapping the circuit as a torch module.

class CircuitNode(
circuit: Circuit,
node: int,
feeders: tuple[tuple[Symbol, FormulaNode], ...] = (),
)[source]

A graph-backed formula node — a handle into a circuit graph.

Pairs a circuit with the node id of one of its roots; this is the compressed counterpart to symbolic UnaryOp / BinaryOp structure. It lives in the AST (a member of FormulaNode) but its fine internal structure — the boolean and/or/not graph — lives in the circuit, not as nested dataclass objects.

The compressed chunk has a boundary: the leaf / constant symbols reachable from node. Each boundary symbol feeds a child formula, and feeders records the non-trivial ones as a name → child mapping. A symbol absent from feeders feeds itself as Atom(name) — so the default empty feeders is the identity boundary (every leaf feeds its own atom), reproducing the plain leaf view. A non-identity entry makes the boundary symbolic: a leaf can be fed by an arbitrary sub-formula — including one in a different algebraic structure — without re-materializing the circuit.

Pure, frozen, value-keyed data like its symbolic siblings: the boundary map is part of value identity (feeders is a hashable tuple of pairs), so two lumps over the same circuit node with different feeders are distinct nodes.

property structure: str

The algebraic structure name of the backing circuit.

property children: tuple[Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode, ...]

Boundary children of this compressed AST chunk.

A CircuitNode compresses a whole circuit subgraph, so its formula children are what feeds that subgraph’s boundary, in boundary’s order, not the direct graph-node successors.

property boundary: tuple[tuple[Symbol, Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode], ...]

Each leaf / constant symbol reachable from node, with the child feeding it.

The symbols come in the circuit’s deterministic topological order, each fed by its feeders override or, by default, its identity Atom, which may name it otherwise: an Atom holds = with the variable first.

Cached: computing it walks the whole reachable subgraph and allocates an Atom per boundary symbol, yet it is read by every walk that reaches the lump through children(), the lowering’s among them. Caching also keeps the identity of those Atom``s stable for as long as the lump lives, which the lowering's identity-keyed bookkeeping relies on. Reachability from a fixed node never changes — a circuit only ever grows new nodes — so the cache cannot go stale. (``cached_property writes straight into __dict__, so it works on this frozen dataclass, and neither __eq__ nor __hash__ consults it.)

knowledge_compile(
circuit: Circuit,
roots: list[int],
*,
variables: VariableAtoms | None = None,
structure: str | AlgebraicStructure | None = None,
leaf_mapping: Callable[[Symbol], Symbol] | None = None,
) → tuple[Circuit, dict[int, int]][source]

Rewrite roots into a deterministic, decomposable circuit.

Returns (new_circuit, node_map) — the same contract as transform_circuit(), and composable with it. All roots are compiled together, so what they share stays shared.

structure is the algebra to emit into, the source’s own by default. The rewrite preserves roles, so emitting into another algebra applies that algebra’s product, sum and complement to the same diagram — which is what transforming the compiled circuit afterwards would have done, without building it. leaf_mapping renames each atom on the way, as that transform would have.

variables says where each variable occurs. The compiler follows from that rather than from a caller’s choice: a plain SDD has only two-valued variables, so a variable two or more of whose values the formula reaches needs the multi-valued one, or two of those atoms could hold at once. A variable the formula reaches at most one value of is a plain SDD variable, its remaining values being the one residual an SDD already reads as the complement.

transform_circuit(
source: Circuit,
target_structure: str | AlgebraicStructure,
roots: list[int],
*,
operator_mapping: dict[str, str] | None = None,
leaf_mapping: Callable[[Symbol], Symbol] | None = None,
into: tuple[Circuit, dict[int, int]] | None = None,
) → tuple[Circuit, dict[int, int]][source]

Transform a circuit to a different algebraic structure.

Creates a new circuit with the target structure by traversing the source circuit and rebuilding each node with mapped operators, leaves, and constants.

The map is exact only insofar as the source’s operators mean in the target what they meant at home. Reading a logical circuit’s or as a semiring sum requires the source to be deterministic and decomposable, which is what knowledge_compile() produces.

Parameters:
  • source – The circuit to transform.

  • target_structure – The target algebraic structure (name or instance).

  • roots – Root node IDs defining the subgraph to transform.

  • operator_mapping – Explicit mapping from source operator names to target operator names, replacing the inferred one. If None, the mapping is inferred from the roles both structures declare (product→product, sum→sum, negation→negation, division→division); an operator the target has no role for raises when a node uses it.

  • leaf_mapping – Optional callable to remap leaf symbols.

  • into – An existing (target_circuit, node_map) to continue transforming into, instead of allocating a fresh target. Source nodes already in node_map are skipped, so repeated calls sharing one target accumulate and deduplicate exactly as a single multi-root call would. The node_map is mutated in place and returned. Its target structure must match target_structure.

Returns:

A tuple of (new_circuit, node_map) where node_map maps source node IDs to their corresponding IDs in the new circuit.

deeplog.grounding.prolog

The Prolog grounder: programs, the grounders that prove them, and Prolog terms.

Builtin = Builtin

A builtin enumerates answer substitutions for a goal’s arguments.

create_fact(atom: Symbol | str) → RuleType[source]

Create a plain fact atom :- true.

create_query(body_atoms: list[str] | list[Symbol]) → RuleType[source]

Create a query false ?- b1 , ... , bm.

create_rule(
head_atoms: list[str] | list[Symbol],
body_atoms: list[str] | list[Symbol],
functor: str = ':-',
) → RuleType[source]

Create a rule h1 ; ... ; hn <functor> b1 , ... , bm.

An empty head folds to FalseSymbol and an empty body to TrueSymbol, so facts (empty body) and constraints (empty head) are just special cases.

get_constraint_body(rule: RuleType) → Symbol[source]

Return the body of an integrity constraint :- body.

is_constraint(symbol: Symbol) → bool[source]

Return true if symbol is a rule with a false head.

is_fact(symbol: Symbol) → bool[source]

Return true if symbol is a rule with an empty (true) body.

is_query(symbol: Symbol) → bool[source]

Return true if symbol is a ?- directive with a false head.

class JanusGrounder[source]

A Prolog grounder based on a meta-prover implemented with SWI-Prolog Janus.

Initialize a Janus-backed grounder and ensure the Prolog code is loaded.

ground(
program: Program,
goal: Symbol,
open_predicates: OpenPredicates = frozenset({}),
) → dict[Symbol, Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode][source]

Prove goal in program to one proof formula per ground answer.

The proof tables the goals it proves, and drops the tables when it ends, with every other private table of the calling Prolog thread.

static is_available() → bool[source]

Return true if janus_swi is available and the class can be instantiated.

add_builtin(functor: str, arity: int, builtin_function: Builtin) → None[source]

Register a builtin for the goals this grounder proves.

class JanusNotAvailableException[source]

Raised when a Janus prover is built but janus_swi is unavailable.

class JanusProver(module_file: Path)[source]

A prover written as an SWI-Prolog module, run through Janus.

Load the prover in module_file, unless it is loaded already.

The file is an SWI-Prolog module. It reaches DeepLog’s Prolog library with :- use_module(deeplog(grounding)).

Raises:

JanusNotAvailableException – janus_swi cannot be imported.

add_builtin(functor: str, arity: int, builtin_function: Builtin) → None[source]

Make functor/arity a builtin of the goals this prover runs.

consult(clauses: Iterable[str]) → str[source]

Load clauses, in order, into a module of their own, and return its name.

The module is named after the clauses, so the same clauses load once. Loading them reports no singleton variables.

query(
goal: str,
bindings: Mapping[str, object],
) → Iterator[dict[str, Any]][source]

The solutions of goal, run in the prover’s module.

A goal that reaches unknown_predicate/1 raises UnknownPredicateException, one that reaches non_ground_open_predicate/1 raises ValueError, and one that runs out of Prolog’s memory, such as its stack limit, raises MemoryError.

OpenPredicates = OpenPredicates

The set of open (leaf) predicates, keyed by (functor, arity).

Program = Program

The clauses a grounder proves against, in the order they were written.

class PrologGrounder[source]

Abstract plain-Prolog grounder: proves a goal to a per-answer proof formula.

abstractmethod ground(
program: Program,
goal: Symbol,
open_predicates: OpenPredicates = frozenset({}),
) → dict[Symbol, FormulaNode][source]

Prove goal in program and return one proof formula per ground answer.

A proof formula is a boolean formula of and / or / not over leaf atoms, and true for an answer proven without one. open_predicates names the predicates whose facts become leaf atoms rather than resolving to true.

abstractmethod add_builtin(functor: str, arity: int, builtin_function: Builtin) → None[source]

Register an additional builtin predicate.

RuleType = RuleType

A clause as a (functor, head, body) triple, the functor saying whether it is a rule, a query or a constraint.

class SimpleGrounder[source]

A simple memoizing Prolog grounder without any dependencies.

Create an in-process Prolog-like grounder.

ground(
program: Program,
goal: Symbol,
open_predicates: OpenPredicates = frozenset({}),
) → dict[Symbol, Atom | UnaryOp | BinaryOp | Transformation | AggregationOp | Aggregation | CircuitNode][source]

Prove goal in program to one proof formula per ground answer.

Raises:

RecursionError – If a goal calls a variant of itself, as the goals of e(X,Y) :- e(X,Z), e(Z,Y). do. Resolution alone cannot prove such a program; JanusGrounder tables its calls and proves it.

add_builtin(functor: str, arity: int, builtin_function: Builtin) → None[source]

Register an additional builtin predicate for this grounder instance.

split_list(term: Symbol) → tuple[list[Symbol], Symbol][source]

Return the elements of the list term and the tail they end in.

A list is a cons/nil chain, so [a, b] is ([a, b], nil), [a | T] is ([a], T), and a term that is not a list is ([], term).

str_to_rule(line: str) → RuleType[source]

Parse a single plain-Prolog clause line.

str_to_rules(code: str) → Iterable[RuleType][source]

Parse a plain-Prolog program; clauses may share a line.

symbol_to_prolog_str(symbol: Symbol) → str[source]

Convert a Symbol to a valid Prolog term string using strict prefix notation.

Translates cons/nil chains (deeplog’s internal list encoding) to Prolog list syntax [h1, h2, ... | tail] so SWI list builtins like nth0/3 and member/2 operate on them.

class UnknownPredicateException[source]

Raised when a goal’s predicate has no clauses, builtin, or open declaration.