# 7. API Documentation¶

## 7.1. problog.logic - Basic logic¶

This module contains basic logic constructs.

A Term can be:
Four functions are handled separately:

Syntactic sugar

Prolog Python English
:- << clause
, & and
; | or
\+ ~ not

Warning

Due to Python’s operator priorities, the body of the clause has to be between parentheses.

Example:

from problog.logic import Var, Term

# Functors (arguments will be added later)
ancestor = Term('anc')
parent = Term('par')

# Literals
leo3 = Term('leo3')
al2 = Term('al2')
phil = Term('phil')

# Variables
X = Var('X')
Y = Var('Y')
Z = Var('Z')

# Clauses
c1 = ( ancestor(X,Y) << parent(X,Y) )
c2 = ( ancestor(X,Y) << ( parent(X,Z) & ancestor(Z,Y) ) )
c3 = ( parent( leo3, al2 ) )
c4 = ( parent( al2, phil ) )

term2str(term)[source]

Convert a term argument to string.

Parameters: term (Term | None | int) – the term to convert string representation of the given term where None is converted to ‘_’. str
list2term(lst)[source]

Transform a Python list of terms in to a Prolog Term.

Parameters: lst (list of Term) – list of Terms Term representing a Prolog list Term
term2list(term)[source]

Transform a Prolog list to a Python list of terms.

Parameters: term (Term) – term representing a fixed length Prolog list ValueError – given term is not a valid fixed length Prolog list Python list containing the elements from the Prolog list list of Term
is_ground(*terms)[source]

Test whether a any of given terms contains a variable. :param terms: list of terms to test for the presence of variables :param terms: tuple of (Term | int | None) :return: True if none of the arguments contains any variables.

is_variable(term)[source]

Test whether a Term represents a variable.

Parameters: term – term to check True if the expression is a variable
is_list(term)[source]

Test whether a Term is a list.

Parameters: term – term to check True if the term is a list.
class Term(functor, *args, **kwdargs)[source]

Bases: object

A first order term, for example ‘p(X,Y)’. :param functor: the functor of the term (‘p’ in the example) :type functor: str :param args: the arguments of the Term (‘X’ and ‘Y’ in the example) :type args: tuple of (Term | None | int) :param kwdargs: additional arguments; currently ‘p’ (probability) and ‘location’ (character position in input)

functor

Term functor

args

Term arguments

arity

Number of arguments

value

Value of the Term obtained by computing the function is represents

compute_value(functions=None)[source]

Compute value of the Term by computing the function it represents.

Parameters: functions – dictionary of user-defined functions value of the Term
signature

Term’s signature functor/arity

apply(subst)[source]

Apply the given substitution to the variables in the term.

Parameters: subst (an object with a __getitem__ method) – A mapping from variable names to something else whatever subst.__getitem__ raises a new Term with all variables replaced by their values from the given substitution Term
apply_term(subst)[source]

Apply the given substitution to all (sub)terms in the term.

Parameters: subst (an object with a __getitem__ method) – A mapping from variable names to something else whatever subst.__getitem__ raises a new Term with all variables replaced by their values from the given substitution Term
with_args(*args, **kwdargs)[source]

Creates a new Term with the same functor and the given arguments.

Parameters: args (tuple of (Term | int | None)) – new arguments for the term kwdargs (p=Constant | p=Var | p=float) – keyword arguments for the term a new term with the given arguments Term
with_probability(p=None)[source]

Creates a new Term with the same functor and arguments but with a different probability.

Parameters: p – new probability (None clears the probability) copy of the Term
is_var()[source]

Checks whether this Term represents a variable.

is_constant()[source]

Checks whether this Term represents a constant.

is_ground()[source]

Checks whether the term contains any variables.

is_negated()[source]

Checks whether the term represent a negated term.

variables(exclude_local=False)[source]

Extract the variables present in the term.

Returns: set of variables problog.util.OrderedSet
class Var(name, location=None, **kwdargs)[source]

A Term representing a variable.

Parameters: name (str) – name of the variable
name

Name of the variable

class Constant(value, location=None, **kwdargs)[source]

A constant.

Parameters: value (str, float or int.) – the value of the constant
is_string()[source]

Check whether this constant is a string.

Returns: true if the value represents a string bool
is_float()[source]

Check whether this constant is a float.

Returns: true if the value represents a float bool
is_integer()[source]

Check whether this constant is an integer.

Returns: true if the value represents an integer bool
class Clause(head, body, **kwdargs)[source]

A clause.

class AnnotatedDisjunction(heads, body, **kwdargs)[source]

An annotated disjunction.

class Or(op1, op2, **kwdargs)[source]
classmethod from_list(lst)[source]

Create a disjunction based on the terms in the list.

Parameters: lst – list of terms disjunction over the given terms
to_list()[source]

Extract the terms of the disjunction into the list.

Returns: list of disjuncts
class And(op1, op2, location=None, **kwdargs)[source]
classmethod from_list(lst)[source]

Create a conjunction based on the terms in the list.

Parameters: lst – list of terms conjunction over the given terms
to_list()[source]

Extract the terms of the conjunction into the list.

Returns: list of disjuncts
class Not(functor, child, location=None, **kwdargs)[source]
unquote(s)[source]

Strip single quotes from the string.

Parameters: s – string to remove quotes from string with quotes removed
compute_function(func, args, extra_functions=None)[source]

Compute the result of an arithmetic function given by a functor and a list of arguments.

Parameters: func – functor args ((list | tuple) of (Term | int | None)) – arguments extra_functions – additional user-defined functions basestring ArithmeticError if the function is unknown or if an error occurs while computing it result of the function Constant
exception InstantiationError(message, location=None, **extra)[source]

Bases: problog.errors.GroundingError

Error used when performing arithmetic with a non-ground term.

exception ArithmeticError(message, location=None, **extra)[source]

Bases: problog.errors.GroundingError

Error used when an error occurs during evaluation of an arithmetic expression.

## 7.2. problog.formula - Ground programs¶

Data structures for propositional logic.

class BaseFormula[source]

Defines a basic logic formula consisting of nodes in some logical relation.

Each node is represented by a key. This key has the following properties:
• None indicates false
• 0 indicates true
• a number larger than 0 indicates a positive node
• the key -a with a a number larger than 0 indicates the negation of a

This data structure also support weights on nodes, names on nodes and constraints.

atomcount

Number of atoms in the formula.

get_weights()[source]

Get weights of the atoms in the formula.

Returns: dictionary of weights dict[int, Term]
set_weights(weights)[source]

Set weights of the atoms in the formula.

Parameters: weights (dict[int, Term]) – dictionary of weights
get_weight(key, semiring)[source]

Get actual value of the node with the given key according to the given semiring.

Parameters: key – key of the node (can be TRUE, FALSE or positive or negative) semiring (problog.evaluator.Semiring) – semiring to use to transform stored weight term into actual value actual value of the weight of the given node
extract_weights(semiring, weights=None)[source]

Extracts the positive and negative weights for all atoms in the data structure.

Parameters: semiring – semiring that determines the interpretation of the weights weights – dictionary of { node name : weight } that overrides the builtin weights dictionary { key: (positive weight, negative weight) } dict[int, tuple[any]]

Atoms with weight set to neutral will get weight (semiring.one(), semiring.one()).

If the weights argument is given, it completely replaces the formula’s weights.

All constraints are applied to the weights.

add_name(name, key, label=None)[source]

Add a name to the given node.

Parameters: name (Term) – name of the node key (int | TRUE | FALSE) – key of the node label – type of label (one of LABEL_*)
get_node_by_name(name)[source]

Get node corresponding to the given name.

Parameters: name – name of the node to find key of the node KeyError if no node with the given name was found
add_query(name, key)[source]

Same as add_name(name, key, self.LABEL_QUERY).

Parameters: name – name of the query key – key of the query node
add_evidence(name, key, value)[source]

Same as add_name(name, key, self.LABEL_EVIDENCE_???).

Parameters: name – name of the query key – key of the query node value – value of the evidence (True, False or None)
clear_evidence()[source]

Remove all evidence.

clear_queries()[source]

Remove all evidence.

clear_labeled(label)[source]

Remove all evidence.

get_names(label=None)[source]

Get a list of all node names in the formula.

Parameters: label – restrict to given label. If not set, all nodes are returned. list of all nodes names (of the requested type) as a list of tuples (name, key)
get_names_with_label()[source]

Get a list of all node names in the formula with their label type.

Returns: list of all nodes names with their type
queries()[source]

Get a list of all queries.

Returns: get_names(LABEL_QUERY)
labeled()[source]

Get a list of all query-like labels.

evidence()[source]

Get a list of all determined evidence. Keys are negated for negative evidence. Unspecified evidence (value None) is not included.

Returns: list of tuples (name, key) for positive and negative evidence
evidence_all()[source]

Get a list of all evidence (including undetermined).

Returns: list of tuples (name, key, value) where value can be -1, 0 or 1
is_true(key)[source]

Does the key represent deterministic True?

Parameters: key – key key == self.TRUE
is_false(key)[source]

Does the key represent deterministic False?

Parameters: key – key key == self.FALSE
is_probabilistic(key)[source]

Does the key represent a probabilistic node?

Parameters: key – key not is_true(key) and not is_false(key)
negate(key)[source]

Negate the key.

For TRUE, returns FALSE; For FALSE, returns TRUE; For x returns -x

Parameters: key – key to negate negation of the key
constraints()[source]

Return the list of constraints.

Returns: list of constraints
add_constraint(constraint)[source]

Parameters: constraint (problog.constraint.Constraint) – constraint to add
class LogicFormula(auto_compact=True, avoid_name_clash=False, keep_order=False, use_string_names=False, keep_all=False, propagate_weights=None, max_arity=0, keep_duplicates=False, keep_builtins=False, hide_builtins=False, **kwdargs)[source]

A logic formula is a data structure that is used to represent generic And-Or graphs. It can typically contain three types of nodes:

• atom ( or terminal)
• and (compound)
• or (compound)

The compound nodes contain a list of children which point to other nodes in the formula. These pointers can be positive or negative.

In addition to the basic logical structure of the formula, it also maintains a table of labels, which can be used to easily retrieve certain nodes. These labels typically contain the literals from the original program.

Upon addition of new nodes, the logic formula can perform certain optimizations, for example, by simplifying nodes or by reusing existing nodes.

add_name(name, key, label=None)[source]

Associates a name to the given node identifier.

Parameters: name – name of the node key – id of the node label – type of node (see LogicFormula.LABEL_*)
is_trivial()[source]

Test whether the formula contains any logical construct.

Returns: False if the formula only contains atoms.
add_atom(identifier, probability, group=None, name=None, source=None)[source]

Add an atom to the formula.

Parameters: identifier – a unique identifier for the atom probability – probability of the atom group – a group identifier that identifies mutually exclusive atoms (or None if no constraint) name – name of the new node the identifiers of the node in the formula (returns self.TRUE for deterministic atoms)

This function has the following behavior :

• If probability is set to None then the node is considered to be deterministically true and the function will return TRUE.
• If a node already exists with the given identifier, the id of that node is returned.
• If group is given, a mutual exclusivity constraint is added for all nodes sharing the same group.
• To add an explicitly present deterministic node you can set the probability to True.
add_and(components, key=None, name=None)[source]

Add a conjunction to the logic formula.

Parameters: components – a list of node identifiers that already exist in the logic formula. key – preferred key to use name – name of the node the key of the node in the formula (returns 0 for deterministic atoms)
add_or(components, key=None, readonly=True, name=None)[source]

Add a disjunction to the logic formula.

Parameters: components – a list of node identifiers that already exist in the logic formula. key – preferred key to use readonly – indicates whether the node should be modifiable. This will allow additional disjunct to be added without changing the node key. Modifiable nodes are less optimizable. name – name of the node the key of the node in the formula (returns 0 for deterministic atoms) int

By default, all nodes in the data structure are immutable (i.e. readonly). This allows the data structure to optimize nodes, but it also means that cyclic formula can not be stored because the identifiers of all descendants must be known add creation time.

By setting readonly to False, the node is made mutable and will allow adding disjunct later using the addDisjunct() method. This may cause the data structure to contain superfluous nodes.

add_disjunct(key, component)[source]

Add a component to the node with the given key.

Parameters: key – id of the node to update component – the component to add key ValueError if key points to an invalid node

This may only be called with a key that points to a disjunctive node or TRUE.

add_not(component)[source]

Returns the key to the negation of the node.

Parameters: component – the node to negate
get_node(key)[source]

Get the content of the node with the given key.

Parameters: key (int > 0) – key of the node content of the node
constraints()[source]

Returns a list of all constraints.

has_evidence_values()[source]

Checks whether the current formula contains information for evidence propagation.

get_evidence_values()[source]

Retrieves evidence propagation information.

get_evidence_value(key)[source]

Get value of the given node based on evidence propagation.

Parameters: key – key of the node value of the node (key, TRUE or FALSE)
set_evidence_value(key, value)[source]

Set value of the given node based on evidence propagation.

Parameters: key – key of the node value – value of the node
propagate(nodeids, current=None)[source]
Propagate the value of the given node
(true if node is positive, false if node is negative)

The propagation algorithm is not complete.

Parameters: nodeids – evidence nodes to set (> 0 means true, < 0 means false) current – current set of nodes with deterministic value dictionary of nodes with deterministic value
to_prolog()[source]

Convert the Logic Formula to a Prolog program.

To make this work correctly some flags should be set on the engine and LogicFormula prior to grounding. The following code should be used:

pl = problog.program.PrologFile(input_file)
problog.formula.LogicFormula.create_from(avoid_name_clash=True, keep_order=True, label_all=True)
prologfile = gp.to_prolog()

Returns: Prolog program str
get_name(key)[source]

Get the name of the given node.

Parameters: key – key of the node name of the node Term
enumerate_clauses(relevant_only=True)[source]
Enumerate the clauses of this logic formula.
Clauses are represented as (head, [body]).
Parameters: relevant_only – only list clauses that are part of the ground program for a query or evidence iterator of clauses
to_dot(not_as_node=True, nodeprops={})[source]

Write out in GraphViz (dot) format.

Parameters: not_as_node – represent negation as a node string containing dot representation
class LogicDAG(auto_compact=True, **kwdargs)[source]

Bases: problog.formula.LogicFormula, problog.evaluator.Evaluatable

A propositional logic formula without cycles.

class DeterministicLogicFormula(**kwdargs)[source]

A deterministic logic formula.

## 7.3. problog.cycles - Cycle-breaking¶

Cycle breaking in propositional formulae.

break_cycles(source, target, **kwdargs)[source]

Break cycles in the source logic formula.

Parameters: source – logic formula with cycles target – target logic formula without cycles kwdargs – additional arguments (ignored) target

## 7.4. problog.constraint - Propositional constraints¶

Data structures for specifying propositional constraints.

class Constraint[source]

Bases: object

A propositional constraint.

get_nodes()[source]

Get all nodes involved in this constraint.

update_weights(weights, semiring)[source]

Update the weights in the given dictionary according to the constraints.

Parameters: weights – dictionary of weights (see result of LogicFormula.extract_weights()) semiring – semiring to use for weight transformation
is_true()[source]

Checks whether the constraint is trivially true.

is_false()[source]

Checks whether the constraint is trivially false.

is_nontrivial()[source]

Checks whether the constraint is non-trivial.

as_clauses()[source]

Represent the constraint as a list of clauses (CNF form).

Returns: list of clauses where each clause is represent as a list of node keys list[list[int]]
copy(rename=None)[source]

Copy this constraint while applying the given node renaming.

Parameters: rename – node rename map (or None if no rename is required) copy of the current constraint
class ConstraintAD(group)[source]

Annotated disjunction constraint (mutually exclusive with weight update).

add(node, formula)[source]

Add a node to the constraint from the given formula.

Parameters: node – node to add formula – formula from which the node is taken value of the node after constraint propagation
check(values)[source]

Check the constraint

Parameters: values – dictionary of values for nodes True if constraint succeeds, False otherwise
propagate(values, weights, node=None)[source]

Returns - True: constraint satisfied - False: constraint violated - None: unknown

class ClauseConstraint(nodes)[source]

A constraint specifying that a given clause should be true.

class TrueConstraint(node)[source]

A constraint specifying that a given node should be true.

## 7.5. problog.evaluator - Commone interface for evaluation¶

Provides common interface for evaluation of weighted logic formulas.

class Semiring[source]

Bases: object

Interface for weight manipulation.

A semiring is a set R equipped with two binary operations ‘+’ and ‘x’.

The semiring can use different representations for internal values and external values. For example, the LogProbability semiring uses probabilities [0, 1] as external values and uses the logarithm of these probabilities as internal values.

Most methods take and return internal values. The execeptions are:

• value, pos_value, neg_value: transform an external value to an internal value
• result: transform an internal to an external value
• result_zero, result_one: return an external value
one()[source]

Returns the identity element of the multiplication.

is_one(value)[source]

Tests whether the given value is the identity element of the multiplication.

zero()[source]

Returns the identity element of the addition.

is_zero(value)[source]

Tests whether the given value is the identity element of the addition.

plus(a, b)[source]

Computes the addition of the given values.

times(a, b)[source]

Computes the multiplication of the given values.

negate(a)[source]

Returns the negation. This operation is optional. For example, for probabilities return 1-a.

Raises: OperationNotSupported – if the semiring does not support this operation
value(a)[source]

Transform the given external value into an internal value.

result(a, formula=None)[source]

Transform the given internal value into an external value.

normalize(a, z)[source]

Normalizes the given value with the given normalization constant.

For example, for probabilities, returns a/z.

Raises: OperationNotSupported – if z is not one and the semiring does not support this operation
pos_value(a, key=None)[source]

Extract the positive internal value for the given external value.

neg_value(a, key=None)[source]

Extract the negative internal value for the given external value.

result_zero()[source]

Give the external representation of the identity element of the addition.

result_one()[source]

Give the external representation of the identity element of the multiplication.

is_dsp()[source]

Indicates whether this semiring requires solving a disjoint sum problem.

is_nsp()[source]

Indicates whether this semiring requires solving a neutral sum problem.

in_domain(a)[source]

Checks whether the given (internal) value is valid.

class SemiringProbability[source]

Implementation of the semiring interface for probabilities.

is_dsp()[source]

Indicates whether this semiring requires solving a disjoint sum problem.

class SemiringLogProbability[source]

Implementation of the semiring interface for probabilities with logspace calculations.

is_dsp()[source]

Indicates whether this semiring requires solving a disjoint sum problem.

class SemiringSymbolic[source]

Implementation of the semiring interface for probabilities using symbolic calculations.

is_dsp()[source]

Indicates whether this semiring requires solving a disjoint sum problem.

class EvaluatableDSP[source]

Bases: problog.evaluator.Evaluatable

Interface for evaluatable formulae.

class Evaluator(formula, semiring, weights, **kwargs)[source]

Bases: object

Generic evaluator.

semiring

Semiring used by this evaluator.

propagate()[source]

Propagate changes in weight or evidence values.

evaluate(index)[source]

Compute the value of the given node.

evaluate_fact(node)[source]

Evaluate fact.

Parameters: node – fact to evaluate weight of the fact (as semiring result value)
add_evidence(node)[source]

has_evidence()[source]

Checks whether there is active evidence.

set_evidence(index, value)[source]

Set value for evidence node.

Parameters: index – index of evidence node value – value of evidence
set_weight(index, pos, neg)[source]

Set weight of a node.

Parameters: index – index of node pos – positive weight (as semiring internal value) neg – negative weight (as semiring internal value)
clear_evidence()[source]

Clear all evidence.

evidence()[source]

Iterate over evidence.

class FormulaEvaluator(formula, semiring, weights=None)[source]

Bases: object

Standard evaluator for boolean formula.

set_weights(weights)[source]

Set known weights.

Parameters: weights – dictionary of weights
get_weight(index)[source]

Get the weight of the node with the given index.

Parameters: index – integer or formula.TRUE or formula.FALSE weight of the node
compute_weight(index)[source]

Compute the weight of the node with the given index.

Parameters: index – integer or formula.TRUE or formula.FALSE weight of the node
class FormulaEvaluatorNSP(formula, semiring, weights=None)[source]

Evaluator for boolean formula that addresses the Neutral Sum Problem.

get_weight(index)[source]

Get the weight of the node with the given index.

Parameters: index – integer or formula.TRUE or formula.FALSE weight of the node
compute_weight(index)[source]

Compute the weight of the node with the given index.

Parameters: index – integer or formula.TRUE or formula.FALSE weight of the node

## 7.6. problog.cnf_formula - CNF¶

class CNF(**kwdargs)[source]

A logic formula in Conjunctive Normal Form.

add_atom(atom)[source]

Add an atom to the CNF.

Parameters: atom – name of the atom
add_comment(comment)[source]

Parameters: comment – text of the comment
add_clause(head, body)[source]

Add a clause to the CNF.

Parameters: head – head of the clause (i.e. atom it defines) body – body of the clause
add_constraint(constraint, force=False)[source]

Parameters: constraint (problog.constraint.Constraint) – constraint to add force – force constraint to be true even though none of its values are set
to_dimacs(partial=False, weighted=False, semiring=None, smart_constraints=False)[source]

Transform to a string in DIMACS format.

Parameters: partial – split variables if possibly true / certainly true weighted – created a weighted (False, int, float) semiring – semiring for weight transformation (if weighted) string in DIMACS format
to_lp(partial=False, semiring=None, smart_constraints=False)[source]

Transfrom to CPLEX lp format (MIP program). This is always weighted.

Parameters: partial – split variables in possibly true / certainly true semiring – semiring for weight transformation (if weighted) smart_constraints – only enforce constraints when variables are set string in LP format
from_partial(atoms)[source]

Translates a (complete) conjunction in the partial formula back to the complete formula.

For example: given an original formula with one atom ‘1’,
this atom is translated to two atoms ‘1’ (pt) and ‘2’ (ct).

The possible conjunctions are:

• [1, 2] => [1] certainly true (and possibly true) => true
• [-1, -2] => [-1] not possibly true (and certainly true) => false
• [1, -2] => [] possibly true but not certainly true => unknown
• [-1, 2] => INVALID certainly true but not possible => invalid (not checked)
Parameters: atoms – complete list of atoms in partial CNF partial list of atoms in full CNF
is_trivial()[source]

Checks whether the CNF is trivial (i.e. contains no clauses)

clauses

Return the list of clauses

clausecount

Return the number of clauses

clarks_completion(source, destination, **kwdargs)[source]

Transform an acyclic propositional program to a CNF using Clark’s completion.

Parameters: source – acyclic program to transform destination – target CNF kwdargs – additional options (ignored) destination

## 7.7. problog.nnf_formula - d-DNNF¶

exception DSharpError[source]

Bases: problog.errors.CompilationError

DSharp has crashed.

class NNF(**kwdargs)[source]

A d-DNNF formula.

class SimpleNNFEvaluator(formula, semiring, weights=None, **kwargs)[source]

Evaluator for d-DNNFs.

class Compiler[source]

Bases: object

Interface to CNF to d-DNNF compiler tool.

classmethod get_default()[source]

Get default compiler for this system.

classmethod get(name)[source]

Parameters: name – name of the compiler function used to call compiler
classmethod add(name, func)[source]

Parameters: name – name of the compiler func – function used to call the compiler

## 7.8. problog.dd_formula - Decision Diagrams¶

Common interface to decision diagrams (BDD, SDD).

class DD(**kwdargs)[source]

Root class for bottom-up compiled decision diagrams.

get_manager()[source]

Get the underlying manager

get_inode(index)[source]

Get the internal node corresponding to the entry at the given index.

Parameters: index – index of node to retrieve internal node corresponding to the given index
set_inode(index, node)[source]

Set the internal node for the given index.

Parameters: index (int > 0) – index at which to set the new node node – new node
get_constraint_inode()[source]

Get the internal node representing the constraints for this formula.

build_dd()[source]

Build the internal representation of the formula.

build_constraint_dd()[source]

Build the internal representation of the constraint of this formula.

class DDManager[source]

Bases: object

Manager for decision diagrams.

add_variable(label=0)[source]

Add a variable to the manager and return its label.

Parameters: label (int) – suggested label of the variable label of the new variable int
literal(label)[source]

Return an SDD node representing a literal.

Parameters: label (int) – label of the literal internal node representing the literal
is_true(node)[source]

Checks whether the SDD node represents True.

Parameters: node – node to verify True if the node represents True bool
true()[source]

Return an internal node representing True.

is_false(node)[source]

Checks whether the internal node represents False

Parameters: node (SDDNode) – node to verify False if the node represents False bool
false()[source]

Return an internal node representing False.

conjoin2(a, b)[source]

Base method for conjoining two internal nodes.

Parameters: a – first internal node b – second internal node conjunction of given nodes
disjoin2(a, b)[source]

Base method for disjoining two internal nodes.

Parameters: a – first internal node b – second internal node disjunction of given nodes
conjoin(*nodes)[source]

Create the conjunction of the given nodes.

Parameters: nodes – nodes to conjoin conjunction of the given nodes

This method handles node reference counting, that is, all intermediate results are marked for garbage collection, and the output node has a reference count greater than one. Reference count on input nodes is not touched (unless one of the inputs becomes the output).

disjoin(*nodes)[source]

Create the disjunction of the given nodes.

Parameters: nodes – nodes to conjoin disjunction of the given nodes

This method handles node reference counting, that is, all intermediate results are marked for garbage collection, and the output node has a reference count greater than one. Reference count on input nodes is not touched (unless one of the inputs becomes the output).

equiv(node1, node2)[source]

Enforce the equivalence between node1 and node2.

Parameters: node1 – node2 –
negate(node)[source]

Create the negation of the given node.

This method handles node reference counting, that is, all intermediate results are marked for garbage collection, and the output node has a reference count greater than one. Reference count on input nodes is not touched (unless one of the inputs becomes the output).

Parameters: node – negation of the given node negation of the given node
same(node1, node2)[source]

Checks whether two SDD nodes are equivalent.

Parameters: node1 – first node node2 – second node True if the given nodes are equivalent, False otherwise. bool
ref(*nodes)[source]

Increase the reference count for the given nodes.

Parameters: nodes (tuple of SDDNode) – nodes to increase count on
deref(*nodes)[source]

Decrease the reference count for the given nodes.

Parameters: nodes (tuple of SDDNode) – nodes to decrease count on
write_to_dot(node, filename)[source]

Write SDD node to a DOT file.

Parameters: node (SDDNode) – SDD node to output filename (basestring) – filename to write to
wmc(node, weights, semiring)[source]

Perform Weighted Model Count on the given node.

Parameters: node – node to evaluate weights – weights for the variables in the node semiring – use the operations defined by this semiring weighted model count
wmc_literal(node, weights, semiring, literal)[source]

Evaluate a literal in the decision diagram.

Parameters: node – root of the decision diagram weights – weights for the variables in the node semiring – use the operations defined by this semiring literal – literal to evaluate weighted model count
wmc_true(weights, semiring)[source]

Perform weighted model count on a true node. This can be used to obtain a normalization constant.

Parameters: weights – weights for the variables in the node semiring – use the operations defined by this semiring weighted model count
class DDEvaluator(formula, semiring, weights=None, **kwargs)[source]

Generic evaluator for bottom-up compiled decision diagrams.

Parameters: formula – semiring – weights – DD
build_dd(source, destination, **kwdargs)[source]

Build a DD from another formula.

Parameters: source – source formula destination – destination formula kwdargs – extra arguments destination

## 7.9. problog.bdd_formula - Binary Decision Diagrams¶

class BDD(**kwdargs)[source]

A propositional logic formula consisting of and, or, not and atoms represented as an BDD.

get_atom_from_inode(node)[source]

Get the original atom given an internal node.

Parameters: node – internal node atom represented by the internal node
classmethod is_available()[source]

Checks whether the BDD library is available.

class BDDManager(varcount=0, auto_gc=True)[source]

Manager for BDDs. It wraps around the pyeda BDD module

get_variable(node)[source]

Get the variable represented by the given node.

Parameters: node – internal node original node
build_bdd(source, destination, **kwdargs)[source]

Build an SDD from another formula.

Parameters: source – source formula destination – destination formula kwdargs – extra arguments destination

## 7.10. problog.sdd_formula - Sentential Decision Diagrams¶

Interface to Sentential Decision Diagrams (SDD)

class SDD(sdd_auto_gc=False, **kwdargs)[source]

A propositional logic formula consisting of and, or, not and atoms represented as an SDD.

This class has two restrictions with respect to the default LogicFormula:

• The number of atoms in the SDD should be known at construction time.
• It does not support updatable nodes.

This means that this class can not be used directly during grounding. It can be used as a target for the makeAcyclic method.

classmethod is_available()[source]

Checks whether the SDD library is available.

to_formula()[source]

Extracts a LogicFormula from the SDD.

class SDDManager(varcount=0, auto_gc=True)[source]

Manager for SDDs. It wraps around the SDD library and offers some additional methods.

get_manager()[source]

Get the underlying sdd manager.

build_sdd(source, destination, **kwdargs)[source]

Build an SDD from another formula.

Parameters: source – source formula destination – destination formula kwdargs – extra arguments destination

## 7.11. problog.core - Binary Decision Diagrams¶

Provides core functionality of ProbLog.

class ProbLog[source]

Bases: object

Static class containing transformation information

classmethod register_transformation(src, target, action=None)[source]

Register a transformation from class src to class target using function action.

Parameters: src – source function target – target function action – transformation function
classmethod register_create_as(repl, orig)[source]

Register that we can create objects of class repl in the same way as objects of class orig.

Parameters: repl – object we want to create orig – object construction we can use instead
classmethod register_allow_subclass(orig)[source]

Register that we can create objects of class repl by creating an object of a subclass.

Parameters: orig –
classmethod find_paths(src, target, stack=())[source]

Find all possible paths to transform the src object into the target class.

Parameters: src – object to transform target – class to tranform the object to stack – stack of intermediate classes list of class, action, class, action, ..., class
classmethod convert(src, target, **kwdargs)[source]

Convert the source object into an object of the target class.

Parameters: src – source object target – target class kwdargs – additional arguments passed to transformation functions
exception TransformationUnavailable[source]

Exception thrown when no valid transformation between two ProbLogObjects can be found.

class ProbLogObject[source]

Bases: object

Root class for all convertible objects in the ProbLog system.

classmethod create_from(obj, **kwdargs)[source]

Transform the given object into an object of the current class using transformations.

Parameters: obj – obj to transform kwdargs – additional options object of current class
classmethod createFrom(obj, **kwdargs)[source]

Transform the given object into an object of the current class using transformations.

Parameters: obj – obj to transform kwdargs – additional options object of current class
classmethod create_from_default_action(src)[source]

Create object of this class from given source object using default action.

Parameters: src – source object to transform transformed object
transform_create_as(cls1, cls2)[source]

Informs the system that cls1 can be used instead of cls2 in any transformations.

Parameters: cls1 – cls2 –
class transform(cls1, cls2, func=None)[source]

Bases: object

Decorator for registering a transformation between two classes.

Parameters: cls1 – source class cls2 – target class func – transformation function (for direct use instead of decorator)
list_transformations()[source]

Print an overview of available transformations.

## 7.12. problog.engine - Grounding engine¶

Grounding engine to transform a ProbLog program into a propositional formula.

ground(model, target=None, queries=None, evidence=None, propagate_evidence=False, labels=None, engine=None, **kwdargs)[source]

Ground a given model.

Parameters: model (LogicProgram) – logic program to ground target (LogicFormula) – formula in which to store ground program queries – list of queries to override the default evidence – list of evidence atoms to override the default the ground program LogicFormula
class GenericEngine[source]

Bases: object

Generic interface to a grounding engine.

prepare(db)[source]
Prepare the given database for querying.
Calling this method is optional.
Parameters: db – logic program logic program in optimized format where builtins are initialized and directives have been evaluated
query(db, term)[source]

Evaluate a query without generating a ground program.

Parameters: db – logic program term – term to query; variables should be represented as None list of tuples of argument for which the query succeeds.
ground(db, term, target=None, label=None)[source]

Ground a given query term and store the result in the given ground program.

Parameters: db – logic program term – term to ground; variables should be represented as None target – target logic formula to store grounding in (a new one is created if none is given) label – optional label (query, evidence, ...) logic formula (target if given)
ground_all(db, target=None, queries=None, evidence=None)[source]

Ground all queries and evidence found in the the given database.

Parameters: db – logic program target – logic formula to ground into queries – list of queries to evaluate instead of the ones in the logic program evidence – list of evidence to evaluate instead of the ones in the logic program ground program
class ClauseDBEngine(builtins=True, **kwdargs)[source]

Parent class for all Python ClauseDB-based engines.

load_builtins()[source]

get_builtin(index)[source]

Get builtin’s evaluation function based on its identifier. :param index: index of the builtin :return: function that evaluates the builtin

add_builtin(predicate, arity, function)[source]

Parameters: predicate – name of builtin predicate arity – arity of builtin predicate function – function to execute builtin
get_builtins()[source]

Get the list of builtins.

prepare(db)[source]

Convert given logic program to suitable format for this engine. Calling this method is optional, but it allows to perform multiple operations on the same database. This also executes any directives in the input model.

Parameters: db (LogicProgram) – logic program to prepare for evaluation logic program in a suitable format for this engine ClauseDB
get_non_cache_functor()[source]

Get a unique functor that is excluded from caching.

Returns: unique functor that is excluded from caching basestring
create_context(content, define=None)[source]

Create a variable context.

query(db, term, **kwdargs)[source]
Parameters: db – term – kwdargs –
ground(db, term, target=None, label=None, **kwdargs)[source]

Ground a query on the given database.

Parameters: db (LogicProgram) – logic program term (Term) – query term gp (LogicFormula) – output data structure (for incremental grounding) label (str) – type of query (e.g. query, evidence or -evidence) kwdargs – additional arguments ground program containing the query LogicFormula
ground_step(db, term, gp=None, silent_fail=True, assume_prepared=False, **kwdargs)[source]
Parameters: db (LogicProgram) – term – gp – silent_fail – assume_prepared – kwdargs –
exception UnknownClauseInternal[source]

Undefined clause in call used internally.

exception NonGroundProbabilisticClause(location)[source]

Bases: problog.errors.GroundingError

Encountered a non-ground probabilistic clause.

exception UnknownClause(signature, location)[source]

Bases: problog.errors.GroundingError

Undefined clause in call.

class ClauseDB(builtins=None, parent=None)[source]

Compiled logic program.

A logic program is compiled into a table of instructions. The types of instructions are:

define( functor, arity, defs )
Pointer to all definitions of functor/arity. Definitions can be: fact, clause or adc.
clause( functor, arguments, bodynode, varcount )
Single clause. Functor is the head functor, Arguments are the head arguments. Body node is a pointer to the node representing the body. Var count is the number of variables in head and body.
fact( functor, arguments, probability )
Single fact.
adc( functor, arguments, bodynode, varcount, parent )
Single annotated disjunction choice. Fields have same meaning as with clause, parent_node points to the parent ad node.
Annotated disjunction group. Child nodes point to the adc nodes of the clause.
call( functor, arguments, defnode )
Body literal with call to clause or builtin. Arguments contains the call arguments, definition node is the pointer to the definition node of the given functor/arity.
conj( childnodes )
Logical and. Currently, only 2 children are supported.
disj( childnodes )
Logical or. Currently, only 2 children are supported.
neg( childnode )
Logical not.
get_node(index)[source]

Get the instruction node at the given index.

Parameters: index (int) – index of the node to retrieve requested node tuple IndexError – the given index does not point to a node
find(head)[source]

Find the define node corresponding to the given head.

Parameters: head (basic.Term) – clause head to match location of the clause node in the database, returns None if no such node exists int or None
add_clause(clause)[source]

Add a clause to the database.

Parameters: clause (Clause) – Clause to add location of the definition node in the database int
add_fact(term)[source]

Add a fact to the database. :param term: fact to add :type term: Term :return: position of the definition node in the database :rtype: int

iter_raw()[source]

Iterate over clauses of model as represented in the database i.e. with choice facts and without annotated disjunctions.

create_function(functor, arity)[source]

Create a Python function that can be used to query a specific predicate on this database.

Parameters: functor – functor of the predicate arity – arity of the predicate (the function will take arity - 1 arguments a Python callable

## 7.13. problog.engine_builtin - Grounding engine builtins¶

Implementation of Prolog / ProbLog builtins.

exception CallModeError(functor, args, accepted=None, message=None, location=None)[source]

Bases: problog.errors.GroundingError

Represents an error in builtin argument types.

exception ConsultError(message, location)[source]

Bases: problog.errors.GroundingError

Error during consult

exception IndirectCallCycleError(location=None)[source]

Bases: problog.errors.GroundingError

Cycle should not pass through indirect calls (e.g. call/1, findall/3).

class StructSort(obj, *args)[source]

Bases: object

Comparator of terms based on structure.

add_standard_builtins(engine, b=None, s=None, sp=None)[source]

Adds standard builtins to the given engine.

Parameters: engine (ClauseDBEngine) – engine to add builtins to b – wrapper for boolean builtins (returning True/False) s – wrapper for simple builtins (return deterministic results) sp – wrapper for probabilistic builtins (return probabilistic results)
check_mode(args, accepted, functor=None, location=None, database=None, **kwdargs)[source]

Checks the arguments against a list of accepted types.

Parameters: args (tuple of Term) – arguments to check accepted (list of str) – list of accepted combination of types (see mode_types) functor – functor of the call (used for error message) location – location of the call (used for error message) database – database (used for error message) kwdargs – additional arguments (not used) the index of the first mode in accepted that matches the arguments int
list_elements(term)[source]

Extract elements from a List term. Ignores the list tail.

Parameters: term (Term) – term representing a list elements of the list list of Term
list_tail(term)[source]

Extract the tail of the list.

Parameters: term (Term) – Term representing a list tail of the list Term

## 7.14. problog.engine_stack - Stack-based implementation of grounding engine¶

Default implementation of the ProbLog grounding engine.

exception NegativeCycle(location=None)[source]

Bases: problog.errors.GroundingError

The engine does not support negative cycles.

results_to_actions(resultlist, engine, node, context, target, parent, identifier, transform, is_root, database, **kwdargs)[source]

Translates a list of results to actions.

Parameters: results – node – context – target – parent – identifier – transform – is_root – database – kwdargs –
class MessageQueue[source]

Bases: object

A queue of messages.

append(message)[source]

Add a message to the queue.

Parameters: message –
cycle_exhausted()[source]

Check whether there are messages inside the cycle.

pop()[source]

Pop a message from the queue.

class BooleanBuiltIn(base_function)[source]

Bases: object

Simple builtin that consist of a check without unification. (e.g. var(X), integer(X), ... ).

class SimpleBuiltIn(base_function)[source]

Bases: object

Simple builtin that does cannot be involved in a cycle or require engine information and has 0 or more results.

class SimpleProbabilisticBuiltIn(base_function)[source]

Bases: object

Simple builtin that does cannot be involved in a cycle or require engine information and has 0 or more results.

## 7.15. problog.engine_unify - Unification¶

Implementation of unification for the grounding engine.

exception UnifyError[source]

Unification error (used and handled internally).

substitute_all(terms, subst, wrapped=False)[source]
Parameters: terms – subst –
instantiate(term, context)[source]

Replace variables in Term by values based on context lookup table.

Parameters: term – context –
unify_value(value1, value2, source_values)[source]

Unify two values that exist in the same context. :param value1: :param value2: :param source_values: :return:

unify_value_dc(value1, value2, source_values, target_values)[source]

Unify two values that exist in different contexts. Updates the mapping of variables from value1 to values from value2.

Parameters: value1 – value2 – source_values – mapping of source variable to target value target_values – mapping of target variable to TARGET value
substitute_call_args(terms, context, min_var)[source]
Parameters: terms – context –
substitute_head_args(terms, context)[source]

Extract the clause head arguments from the clause context. :param terms: head arguments. These can contain variables >0. :param context: clause context. These can contain variable <0. :return: input terms where variables are substituted by their values in the context

substitute_simple(term, context)[source]
Parameters: term – context –
unify_call_head(call_args, head_args, target_context)[source]

Unify argument list from clause call and clause head. :param call_args: arguments of the call :param head_args: arguments of the head :param target_context: list of values of variables in the clause :raise UnifyError: unification failed

unify_call_return(result, call_args, context, var_translate, min_var, mask=None)[source]

Transforms the result returned by a call into the calling context.

Parameters: result – result returned by call call_args – arguments used in the call context – calling context var_translate – variable translation for local variables from call context to

calling context :param min_var: number of local variables currently in calling context :param mask: mask indicating whether call_args are non-ground (ground can be skipped in unification)

## 7.16. problog.extern - Calling Python from ProbLog¶

Interface for calling Python from ProbLog.

## 7.17. problog.forward - Forward compilation and evaluation¶

Forward compilation using TP-operator.

class ForwardEvaluator(formula, semiring, fdd, weights=None, verbose=None, **kwargs)[source]

An evaluator using anytime forward compilation.

evaluate(index)[source]

Compute the value of the given node.

## 7.18. problog.kbest - K-Best inference using MaxSat¶

Anytime evaluation using best proofs.

## 7.19. problog.maxsat - Interface to MaxSAT solvers¶

Interface to MaxSAT solvers.

## 7.20. problog.parser - Parser for Prolog programs¶

Efficient low-level parser for Prolog programs.

class Factory[source]

Bases: object

Factory object for creating suitable objects from the parse tree.

## 7.21. problog.program - Representation of Logic Programs¶

class LogicProgram(source_root='.', source_files=None, line_info=None, **extra_info)[source]

Bases: object

add_clause(clause)[source]

Add a clause to the logic program.

Parameters: clause – add a clause
add_fact(fact)[source]

Add a fact to the logic program.

Parameters: fact – add a fact
classmethod create_from(src, force_copy=False, **extra)[source]

Create a LogicProgram of the current class from another LogicProgram.

Parameters: src (LogicProgram) – logic program to convert force_copy (bool) – default False, If true, always create a copy of the original logic program. extra – additional arguments passed to all constructors and action functions LogicProgram that is (externally) identical to given one object of the class on which this method is invoked

If the original LogicProgram already has the right class and force_copy is False, then the original program is returned.

classmethod createFrom(src, force_copy=False, **extra)[source]

Create a LogicProgram of the current class from another LogicProgram.

Parameters: src (LogicProgram) – logic program to convert force_copy (bool) – default False, If true, always create a copy of the original logic program. extra – additional arguments passed to all constructors and action functions LogicProgram that is (externally) identical to given one object of the class on which this method is invoked

If the original LogicProgram already has the right class and force_copy is False, then the original program is returned.

lineno(char, force_filename=False)[source]

Transform character position to line:column format.

Parameters: char – character position force_filename – always add filename even for top-level file line, column (or None if information is not available)
class SimpleProgram[source]

LogicProgram implementation as a list of clauses.

add_clause(clause)[source]

Add a clause to the logic program.

Parameters: clause – add a clause
add_fact(fact)[source]

Add a fact to the logic program.

Parameters: fact – add a fact
class PrologString(string, parser=None, factory=None, source_root='.', source_files=None, identifier=0)[source]

Read a logic program from a string of ProbLog code.

add_clause(clause)[source]

Add a clause to the logic program.

Parameters: clause – add a clause
add_fact(fact)[source]

Add a fact to the logic program.

Parameters: fact – add a fact
class PrologFile(filename, parser=None, factory=None, identifier=0)[source]

LogicProgram implementation as a pointer to a Prolog file.

Parameters: filename (string) – filename of the Prolog file (optional) identifier – index of the file (in case of multiple files)
add_clause(clause)[source]

Add a clause to the logic program.

Parameters: clause – add a clause
add_fact(fact)[source]

Add a fact to the logic program.

Parameters: fact – add a fact
class PrologFactory(identifier=0)[source]

Factory object for creating suitable objects from the parse tree.

class ExtendedPrologFactory(identifier=0)[source]

Prolog with some extra syntactic sugar.

Non-standard syntax: - Negative head literals [Meert and Vennekens, PGM 2014]: 0.5::+a :- b.

build_program(clauses)[source]

Update functor f that appear as a negative head literal to f_p and :param clauses: :return:

neg_head_literal_to_pos_literal(literal)[source]

Translate a negated literal into a positive literal and remember the literal to update the complete program later (in build_program). :param literal: :return:

build_probabilistic(operand1, operand2, location=None, **extra)[source]

Detect probabilistic negated head literal and translate to positive literal :param operand1: :param operand2: :param location: :param extra: :return:

build_clause(functor, operand1, operand2, location=None, **extra)[source]

Detect deterministic head literal and translate to positive literal :param functor: :param operand1: :param operand2: :param location: :param extra: :return:

DefaultPrologFactory

alias of ExtendedPrologFactory

## 7.22. problog.setup - Installation tools¶

Provides an installer for ProbLog dependencies.

set_environment()[source]

get_binary_paths()[source]

Get a list of additional binary search paths.

get_module_paths()[source]

Get a list of additional module search paths.

gather_info()[source]

Collect info about the system and its installed software.

## 7.23. problog.util - Useful utilities¶

Provides useful utilities functions and classes.

class OrderedSet(iterable=None)[source]

Bases: _abcoll.MutableSet

Provides an ordered version of a set which keeps elements in the order they are added.

Parameters: iterable (Sequence) – add elements from this iterable (default: None)
add(key)[source]

Parameters: key – element to add
discard(key)[source]

Parameters: key – element to remove
pop(last=True)[source]

Remove and return first or last element.

Parameters: last – remove last element last element
class Timer(msg, output=None, logger='problog')[source]

Bases: object

Report timing information for a block of code. To be used as a with block.

Parameters: msg (str) – message to print output (file) – file object to write to (default: write to logger problog)
class UHeap(key=None)[source]

Bases: object

Updatable heap.

Each element is represented as a pair (key, item). The operation pop() always returns the item with the smallest key. The operation push(item) either adds item (returns True) or updates its key (return False) A function for computing an item’s key can be passed.

Parameters: key – function for computing the sort key of an item
peek()[source]

Returns the element with the smallest key without removing it.

Returns: item with the smallest key
pop()[source]

Removes and returns the element with the smallest key.

Returns: item with the smallest key
pop_with_key()[source]

Removes and returns the smallest element and its key.

Returns: smallest element (key, element)
push(item)[source]

Add the item or update it’s key in case it already exists.

Parameters: item – item to add True is item was not in the collection
format_dictionary(data, precision=8, keysep=':', columnsep='\t')[source]

Pretty print a given dictionary.

Parameters: data (dict) – data to format precision (int) – max. number of digits keysep (str) – separator between key and value (default: ;) columnsep (str) – column separator (default: tab) pretty printed result str
format_tuple(data, precision=8, columnsep='\t')[source]

Pretty print a given tuple (or single value).

Parameters: data – data to format precision (int) – max. number of digits columnsep (str) – column separator pretty printed result str
format_value(data, precision=8)[source]

Pretty print a given value.

Parameters: data – data to format precision (int) – max. number of digits pretty printed result str
init_logger(verbose=None, name='problog', out=None)[source]

Initialize default logger.

Parameters: verbose (int) – verbosity level (0: WARNING, 1: INFO, 2: DEBUG) name (str) – name of the logger (default: problog) result of logging.getLogger(name) logging.Logger
kill_proc_tree(process, including_parent=True)[source]

Recursively kill a subprocess. Useful when the subprocess is a script. Requires psutil but silently fails when it is not present.

Parameters: process (subprocess.Popen) – process including_parent (bool) – also kill process itself (default: True)
load_module(filename)[source]

Load a Python module from a filename or qualified module name.

If filename ends with .py, the module is loaded from the given file. Otherwise it is taken to be a module name reachable from the path.

Example:

Parameters: filename (str) – location of the module loaded module module
mktempfile(suffix='')[source]

Create a temporary file with the given name suffix.

Parameters: suffix (str) – extension of the file name of the temporary file
start_timer(timeout=0)[source]

Start a global timeout timer.

Parameters: timeout (int) – timeout in seconds
stop_timer()[source]

Stop the global timeout timer.

subprocess_call(*popenargs, **kwargs)[source]

Wrapper for subprocess.call that recursively kills subprocesses when Python is interrupted.

Additionally expands executable name to full path.

Parameters: popenargs – positional arguments of subprocess.call kwargs – keyword arguments of subprocess.call result of subprocess.call
subprocess_check_call(*popenargs, **kwargs)[source]

Wrapper for subprocess.check_call that recursively kills subprocesses when Python is interrupted.

Additionally expands executable name to full path.

Parameters: popenargs – positional arguments of subprocess.call kwargs – keyword arguments of subprocess.call result of subprocess.call
subprocess_check_output(*popenargs, **kwargs)[source]

Wrapper for subprocess.check_output that recursively kills subprocesses when Python is interrupted.

Additionally expands executable name to full path.

Parameters: popenargs – positional arguments of subprocess.call kwargs – keyword arguments of subprocess.call result of subprocess.call