Answer Set Programming (Draft) : Vladimir Lifschitz University of Texas at Austin April 5, 2019
Answer Set Programming (Draft) : Vladimir Lifschitz University of Texas at Austin April 5, 2019
(Draft)
Vladimir Lifschitz
University of Texas at Austin
April 5, 2019
2
Preface
Answer set programming is a programming methodology rooted in research on artificial
intelligence and computational logic. It was created at the turn of the century, and it is
now used in many areas of science and technology.
This book is about the art of programming for clingo—one of the most efficient and
widely used answer set programming systems available today, and about the mathematics
of answer set programming. It is based on an undergraduate class taught at the University
of Texas at Austin. The book is self-contained; the only prerequisite is some familiarity
with programming and discrete mathematics.
Chapter 1 discusses the main ideas of answer set programming and its place in the world
of programming languages. Chapter 2 explains, in an informal way, several constructs
available in the input language of clingo, and Chapter 3 shows how they can be used
to solve a number of computational problems. Chapters 4 and 5 put the discussion of
answer set programming on a firm mathematical foundation. Chapter 6 describes a few
more programming constructs and gives examples of their use. In Chapter 7, answer set
programming is applied to the problem of representing actions and generating plans.
Many examples in this book are framed as exercises, and their solutions are presented
in the appendix. This organization gives the reader an opportunity to look for a solution
on his own, and then compare his ideas with the solution proposed in the book.
This book, as well as everything else I have written, owes much to my wife Elena, who
heroically accompanied me in long travels around the world in search for an ideal academic
environment. Eventually I found it in the Computer Science Department of the University
of Texas at Austin.
In my younger years, I was fortunate to meet a few outstanding scientists and to have an
opportunity to take their classes and talk to them. I learned logic from Nikolai Shanin (1919–
2011), Sergei Maslov (1939–1982) and Grigori Mints (1939–2014), and artificial intelligence
from John McCarthy (1927–2011) and Raymond Reiter (1939–2002). The most important
influence on my professional work, next to that of my teachers, came from Michael Gelfond,
an old friend and one of the founding fathers of answer set programming. Michael has read
a draft of this book and suggested many ways to improve it. Useful comments have been
provided also by Amelia Harrison, Roland Kaminski, Joohyung Lee, and Alfred Zhong.
Finally, thanks to Susan Evans, Senior Editor with the Springer Nature’s Computer
Science team, who gave me the idea of converting lecture notes into a textbook.
4
Contents
1 Introduction 9
1.1 Declarative Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2 Logic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Answer Set Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Bibliographical and Historical Remarks . . . . . . . . . . . . . . . . . . . . 12
3 Combinatorial Search 35
3.1 Seating Arrangements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.2 Who Owns the Jackal? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.3 Schur Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.4 Digression on Grounding and Solving . . . . . . . . . . . . . . . . . . . . . . 41
3.5 Permutation Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.6 Sequence Covering Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.7 Partner Units Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.8 Set Packing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.9 Search in Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
3.10 Search in Two Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
3.11 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
3.12 Bibliographical and Historical Remarks . . . . . . . . . . . . . . . . . . . . 58
5
6 CONTENTS
Listings 182
Bibliography 184
Index 194
8 CONTENTS
Chapter 1
Introduction
9
10 CHAPTER 1. INTRODUCTION
countries inhabited by more people than the United Kingdom. Let us call such countries
“large.” This list can be generated by the logic program consisting of a single rule:
The head and body of a rule are similar to the consequent and antecedent of an im-
plication. But their order in a rule is different from what is common in logic: instead
of
if · · · then C is large
we say
C is large if · · · .
Commas separating the expressions in the body of a rule are similar to the conjunction
symbol ∧ (“and”) in logical formulas.
To generate the list of large countries using rule (1.1), we encode the input—Table 1.1—
as a collection of additional rules:
A system implementing the logic programming language Prolog will load a file consisting
of rules (1.1) and (1.2), in any order, and display the prompt ?- that invites the user to
submit “queries”—questions that can be answered on the basis of the given information.
The query large(C) would be understood as the request to find a value of C that has the
property large, and the system would respond:
C = france.
If the user requests another value of C with this property, the answer will be
C = germany.
To a request for a third solution the system will reply no (no more large countries).
To write or understand Prolog programs, one has to think not only about their meaning
as specifications, but also about Prolog’s search strategy. In that sense, Prolog is not fully
declarative; it has an “operational semantics.” Answer set programming (ASP)—the form
of logic programming described in this book—is closer to the ideal of declarativism. ASP
became possible after the invention of the concept of a stable model and the creation of
software systems that generate stable models. These systems are called answer set solvers,
and their operation is described in many articles, dissertations, and books. But if your goal
is to use answer set solvers, rather than design a new system of this kind, then you do not
need to know much about how they operate. This book, in fact, will tell you almost nothing
about what happens “under the hood.” (Section 3.4 and a passage in Section 2.8 are the
only places where the operation of an answer set solver is discussed in any detail.) Answer
set programming has no operational semantics.
its functionality is similar: it implements reasoning in default logic, which is closely related
to stable models (see Sections 5.12 and 6.7).
That early work was followed by creating the answer set solver dlv [26, 31, 75], clingo,
and several others. The computational methods that clingo uses for generating stable
models are discussed in Chapters 4 and 6 of the book [44] written by its designers.
Two papers published in 1999 [88, 97] argued that stable models can serve as the basis
of a new programming paradigm, and the term “answer set programming” was introduced
in the volume where the first of those papers appeared. In that sense, ASP was born in
1999. But the fact that Smodels can be used for planning was demonstrated two years
earlier [30]. Biannual ASP competitions are organized now to assess the state of the art [45].
The relationship between ASP and artificial intelligence is emphasized in two books on
ASP with the words “knowledge representation” in their titles [10, 49]. The Handbook of
Knowledge Representation includes a chapter on answer set programming [48], and the AI
Magazine has published a special issue on ASP [1].
14 CHAPTER 1. INTRODUCTION
Chapter 2
clingo is the centerpiece of the collection of ASP-related tools created at the University of
Potsdam in Germany, called Potassco (for Potsdam Answer Set Solving Collection). Useful
documentation and teaching materials, including information on downloading the latest
clingo release and on running clingo in your browser, are available at the website of the
Potassco project, https://potassco.org.
The description of the language of clingo in this chapter is sufficient for understand-
ing and writing many interesting programs, but it is informal and incomplete. A precise
definition of a number of clingo constructs is given in Chapters 4 and 5. In Chapter 6 we
talk about several elements of the language that are not described in this chapter.
Files containing logic programs are usually given the extension lp. The command
% clingo myfile.lp
(a) How would you translate this rule into English? (b) If we run clingo on the program
consisting of rule (2.1) and the rules
15
16 CHAPTER 2. INPUT LANGUAGE OF CLINGO
2.1 Rules
As discussed in Section 1.2, a typical rule, such as (1.1) or (2.1), consists of a head and a
body separated by the “if” symbol :- and with a period at the end. Rules (1.2) and (2.2)
do not contain “if”; such a rule is viewed as the head without a body.
The heads and bodies of rules (1.1), (1.2) are formed from atoms
and one expression of another kind—a comparison, S1 > S2. Within an atom or compari-
son, we see elements of three types: symbolic constants, numeric constants, and variables.
They can be distinguished by looking at the first character. A numeric constant is an inte-
ger in decimal notation, so that its first character is a digit or the minus sign. A symbolic
constant is a string of letters, digits, and underscores that begins with a lower-case letter. A
variable is a string of letters, digits, and underscores that begins with an upper-case letter.
An atom consists of a predicate symbol—a symbolic constant representing a property
or a relation—and an optional list of arguments in parentheses. A comparison consists of
two arguments separated by one of the symbols
Expressions that can serve as arguments in an atom or comparison are called terms.
The terms that we see in rules (1.1), (1.2), (2.1), (2.2) are constants and variables, but
in Section 2.3 we will encounter also complex terms that are formed from constants and
variables using arithmetic operations. In Section 6.6 we will talk about one more way of
forming terms—the use of symbolic functions.
An atom, a rule, or another syntactic expression is ground if it does not contain variables.
We talked above about “facts” informally; now we can say that a fact is a ground atom.
In Section 1.3 we explained why clingo produces facts (1.3) in response to rules (1.1),
(1.2) by saying that these are the facts that can be derived using these rules. The first four
of these facts are simply part of the program, but what about the other two—in what sense
can they be “derived”?
This can be clarified by considering instances of rule (1.1)—the ground rules that can
be obtained from it by substituting constants for variables. The presence of the atom
large(france) in the stable model generated by clingo can be justified by the instance
C, S1, and S2
2.1. RULES 17
respectively. Both atoms in the body of this instance are among the given facts, and the
comparison in the body is true. Consequently this instance justifies including its head
large(france) in the stable model.
Exercise 2.3. (a) Which instance of rule (1.1) justifies including large(germany)
in the stable model of the program? (b) Which instance of rule (2.1) justifies including
child(dan,bob) in the stable model of program (2.1), (2.2)?
Exercise 2.4. Which of the following ground rules are instances of rule (1.1)?
The last four among the relation symbols (2.3) are usually applied to numbers, but
clingo allows us to apply them to symbolic constants as well. It so happens that according
to the total order used by clingo for such comparisons, the symbol abracadabra is greater
than 7. We can verify this assertion by running clingo on the one-rule program
p :- abracadabra > 7.
The stable model of this program, according to clingo, includes the atom p. The stable
model of
p :- abracadabra < 7.
is empty.
The total order chosen by the designers of clingo has a minimal element and a maximal
element. They are denoted by #inf and #sup.
Stable models of some programs are infinite. Consider, for instance, the one-rule pro-
gram
p(X) :- X > 7. (2.4)
The instance
p(8) :- 8 > 7.
of this rule justifies including p(8) in the stable model; the instance
p(9) :- 9 > 7.
justifies including p(9); and so on. The algorithms used by answer set solvers for generating
stable models are not applicable to programs that contain rules like this. In response to
rule (2.4) clingo produces an error message saying that there are “unsafe variables” in
it—an indication of the fact that a program containing this rule is likely to have an infinite
stable model. But in Section 4.5 we will apply the mathematical definition of a stable model
18 CHAPTER 2. INPUT LANGUAGE OF CLINGO
to program (2.4), and we will see what its stable model consists of: it is the set of all atoms
of the form p(v), where v is an integer or symbolic constant that is greater than 7.
This conclusion does not reflect the functionality of clingo, but it is in agreement with
the behavior of Prolog systems. As discussed in Section 1.2, Prolog does not generate all
elements of a stable model at one blow. Infinite stable models are not problematic for it,
and Prolog does not reject rules like (2.4). Given this one-rule program, Prolog will answer
yes, for instance, to the query ?- p(10), and no to the query ?- p(5).
When a program contains a group of facts with the same predicate symbol, these facts
can be “pooled together” using semicolons. For instance, line (1.2) can be abbreviated as
#show large/1.
In #show directives, and in other cases when we refer to a predicate symbol used in a logic
program, we append its arity—the number of arguments—after a slash; in this case, the
predicate is unary, and its arity is 1. Specifying the arity is needed because the language
of clingo allows us to use the same character string to represent several predicate symbols
of different arities. This is sometimes convenient; we will see examples in Exercise 2.13 and
Listing 2.6. For instance, if we run clingo on the program
p. p(a). p(a,b).
#show p/0. #show p/2.
2.2. DIRECTIVES AND COMMENTS 19
then clingo will drop the atom p(a) from the output, because its predicate symbol p/1 is
different from both p/0 and p/2.
A #const directive allows us to use a symbolic constant as a placeholder for another
constant, symbolic or numeric (or for a more complex expression). For example, the directive
instructs clingo to substitute uk for c0 in the rest of the file. In the presence of directive
(2.5), the rule
As customary in mathematics, we identify a binary relation with the set of pairs of objects
for which that relation holds. Similarly, we will identify a property with the set of objects
with that property. We can say, for instance, that large/1 is a set of countries.
If the file large.lp contains the program in Listing 2.1, and the file large_input.lp
contains the program in Listing 2.2, then the command
will cause clingo to concatenate the two files and produce the answer
large(france) large(germany)
Instead of adding the name of an input file to the command line, we can specify it in
the program file using an #include directive. For instance, we can put the line
#include "large_input.lp".
anywhere in the file large.lp and then drop large_input.lp from command line (2.6).
2.3 Arithmetic
In the language of clingo, complex terms can be built from constants and variables using
the symbols
+ * ** / \ | |
for addition, multiplication, exponentiation, integer division, remainder, and absolute value.
The symbol .. is used to form intervals. For instance, the expression 0..3 denotes the
set {0, 1, 2, 3}. To express that the value of N belongs to this set we write N = 0..3. (Note
that in this case the symbol = plays the same role as the symbol ∈ in standard mathematical
notation. In Section 4.6 we will say more about comparisons that contain intervals.) For
example, the rule
p(N,N*N+N+41) :- N = 0..3. (2.7)
expresses that the pair of integers (x, x2 + x + 41) belongs to p/2 whenever x a number
between 0 and 3. The stable model of this one-rule program is
Exercise 2.7. For each of the given one-rule programs, predict what stable model clingo
is going to produce.
Exercise 2.8. Write a one-rule program that does not contain pooling and has the same
stable model as the program from Exercise 2.6.
Exercise 2.9. For each of the given sets of ground atoms, write a one-rule program that
does not contain pooling and has that set as its stable model.
(a)
p(0,1) p(1,-1) p(2,1) p(3,-1) p(4,1)
(b)
p(1,1)
p(2,1) p(2,2)
p(3,1) p(3,2) p(3,3)
p(4,1) p(4,2) p(4,3) p(4,4)
Intervals may be used not only in the bodies of rules, as in (2.7), but in the heads as
well. For instance, a program may include the fact
p(0..3).
p(0; 1; 2; 3).
Each of these two constructs, intervals and pooling, has its advantages and limitations.
Intervals are sets of numbers; we cannot replace pooling in Line 2 of Listing 2.2 by an
interval. On the other hand, it is not practical to replace a long interval, such as p(1..100),
by pooling.
Another example of intervals in the head is given by the one-rule program
square(1..8,1..8).
Its stable model consists of the 64 atoms corresponding to the squares of the chessboard:
p(1..2,1..4). p(1..4,1..2).
2.4 Definitions
Many rules in a logic program can be thought of as definitions. We can say, for instance,
that rule (1.1) defines the predicate large/1 in terms of the predicate p/2, rule (2.1) defines
child/2 in terms of parent/2, and rule (2.7) defines p/2.
Exercise 2.11. (a) How would you define the predicate grandparent/2 in terms of
parent/2? (b) If you run clingo on your definition, combined with facts (2.2), what
stable model do you think it will produce?
Exercise 2.12. (a) How would you define the predicate sibling/2 in terms of parent/2?
(b) If you run clingo on your definition, combined with facts (2.2), what stable model do
you think it will produce?
Exercise 2.13. Assuming that the atom enrolled(S,C) expresses that student S is
enrolled in class C, how would you define the set enrolled/1 of all students who are enrolled
in at least one class?
Exercise 2.14. Assuming that the atom lives_in(X,C) expresses that person X lives
in city C, and that the atom same_city(X,Y) expresses that X and Y live in the same city,
how would you define same_city/2 in terms of lives_in/2?
Exercise 2.15. Assuming that the atom age(X,N) expresses that person X is N years
old, and that the atom older(X,Y) expresses that X is older than Y, how would you define
older/2 in terms of age/2?
Sometimes the definition of a predicate consists of several rules. For instance, the pair
of rules
parent(X,Y) :- father(X,Y).
parent(X,Y) :- mother(X,Y).
ancestor(X,Y) :- parent(X,Y).
(2.8)
ancestor(X,Z) :- ancestor(X,Y), ancestor(Y,Z).
Exercise 2.16. If we run clingo on the program consisting of rules (2.2) and (2.8), what
stable model do you expect it to produce?
Sometimes a predicate cannot be defined in one step, and auxiliary predicates have to be
defined first. Consider, for instance, the property of being a prime number between 1 and
2.4. DEFINITIONS 23
some upper bound, say 5. It is easier to define the opposite property of being a composite
number between 1 and 5:
not composite(3)
in its body is justified in the sense that any attempt to use rule (2.9) to derive the atom
composite(3) would fail. The negation symbol not, which is often used in logic programs,
is said to represent “negation as failure.” To emphasize this understanding of negation, we
can read rule (2.10) as follows:
of course. Comments explaining what has been “achieved” by a group of rules at the
beginning of a program express properties of stable models that the programmer expects
to hold in the future, when more rules are added. Such comments help us understand
the design of the program, the programmer’s intentions. They also help the programmer
start debugging at an early stage, when only a part of the program has been written. For
example, after writing Lines 1–7 of the program in Listing 2.3 we may wish to check whether
the stable model produced by clingo for the first rule with n equal to 5 is indeed
composite(4)
Exercise 2.17. Two integers are said to be coprime if the only positive integer that
divides both of them is 1. We would like to generate the list of all integers from the set
{1, . . . , n} that are coprime with an integer k. For example, if we save such a program in
the file coprimes.lp then the command line
What rules would you place in Lines 5 and 10 of Listing 2.4 to get this result?
Exercise 2.18. Every nonnegative integer can be represented as the sum of 4 complete
squares, for instance:
7 = 22 + 12 + 12 + 12 ; 10 = 32 + 11 + 02 + 02 .
But if we want to represent a given number as the sum of only 3 complete squares, that
may be impossible. The two smallest numbers that require 4 complete squares are 7 and
2.5. CHOICE RULES 25
15. We would like to generate the list of all integers from the set {1, . . . , n} that cannot
be represented as the sum of 3 complete squares. What rules would you place in Lines 6
and 10 of Listing 2.5 to get such a program?
Listing 2.6 gives yet another example of a pair of definitions, one on top of the other.
Before defining the property fac/1 of being a factorial, we give a recursive definition of the
binary relation fac/2, “the factorial of N is F .” Note that there is no “achieved” comment
after Line 5. Nothing of interest is achieved in the middle of a definition.
Exercise 2.19. Consider the part of the program shown in Listing 2.6 that precedes the
comment in Line 7. What atoms do you expect to see in its stable model if the value of n
is 4?
has 4 stable models. The number of stable models that we would like clingo to display can
be specified on the command line; 1 is the default, and 0 means “find all.” For instance, if
rule (2.11) is saved in the file choice.lp then the command
% clingo choice.lp 0
Answer: 2
q(b)
Answer: 3
p(a)
Answer: 4
p(a) q(b)
SATISFIABLE
Models : 4
In response to the command line
% clingo choice.lp 2
Answer: 2
q(b)
SATISFIABLE
Models : 2+
The plus after 2 indicates that the process of generating stable models has not been com-
pleted, so that the program may have other stable models.
Choice rules may contain pooling and intervals. For instance, the rule
{p(a; b; c)}.
Before and after an expression in braces we can put integers, which express bounds
on the cardinality (number of elements) of the stable models described by the rule. The
number on the left is the lower bound, and the number on the right is the upper bound.
For instance, the one rule program
1 {p(1..3)} 2. (2.12)
Answer: 1
p(2)
Answer: 2
p(3)
Answer: 3
p(2) p(3)
Answer: 4
p(1)
Answer: 5
p(1) p(3)
Answer: 6
p(1) p(2)
Exercise 2.20. For each of the given programs, what do you think is the number of its
stable models?
(a) 1 {p(1..10)}.
Exercise 2.21. For each of the given rules, find a simpler rule that has the same meaning.
(a) 0 {p(a)}.
(b) 1 {p(a)}.
(c) {p(a)} 1.
If the lower and upper bound in a choice rule are equal to each other then the rule
can be rewritten in a different format, using the equal sign. For instance, the rule from
Exercise 2.20(b) can be written as
where n is a placeholder for a nonnegative integer. Each of its stable models includes one
of the atoms p(1), q(1), one of the atoms p(2), q(2), and so on. The program has 2n
stable models; each of them describes a partition of the set {1, ..., n} into subsets p/1, q/1
(possibly empty). For n = 2 clingo produces 4 stable models:
Answer: 1
q(1) p(2)
Answer: 2
q(1) q(2)
Answer: 3
p(1) p(2)
Answer: 4
p(1) q(2)
The rule
{p(X,1..2)} = 1 :- X = 1..n.
is similar: each of its 2n stable models includes one of the atoms p(1,1), p(1,2), one of
the atoms p(2,1), p(2,2), and so on.
Variables can be also used in a choice rule locally, for the purpose of specifying the list
of atoms in braces in terms of predicates defined earlier. For instance, if we defined the
predicate person/1 by the rule
Local variables, such as X in this example, are syntactically distinguished by the fact that
all their occurrences are between braces.
Variables that are not local are said to be global. Substituting new values for a global
variable produces new instances of the rule; substituting values for a local variable does not.
For example, rule (2.14) has one instance—itself, just like rule (2.13) that has no variables
at all.
Exercise 2.22. (a) Rewrite the last rule of the program
p(a; b).
{q(X,Y) : p(X), p(Y)} = 1.
30 CHAPTER 2. INPUT LANGUAGE OF CLINGO
without the use of local variables. (b) How many stable models do you think this program
has?
A choice rule may contain both local and global variables. For instance, in the rule
2.7 Constraints
Logic programs containing choice rules often contain also constraints—rules that weed out
the stable models for which the constraint is “violated.” A constraint is a rule with the
empty head, for instance
:- p(1). (2.15)
By adding this constraint to a program, we eliminate its stable models that contain p(1).
We have seen, for example, that program (2.12) has 6 stable models. Adding rule (2.15)
to it eliminates the last three of them—those that contain p(1). Adding the “opposite”
constraint
:- not p(1).
to (2.12) eliminates the first three solutions—those that do not contain p(1). Adding both
constraints to (2.12) will give a program that has no stable models. Combining choice
rule (2.12) with the constraint
:- p(1), p(2).
will eliminate the only stable model among the 6 that includes both p(1) and p(2)—the
last one.
Exercise 2.24. Consider the program consisting of choice rule (2.12) and the constraint
{p(a); q(b)}.
:- p(a), q(b).
1 {p(a); q(b)}.
:- p(X), q(X).
expresses that the set p/1 is disjoint from q/1. Adding this constraint to a program elimi-
nates the stable models in which p/1 and q/1 have a common element. The constraint
expresses that the binary relation f/2 is functional: for every X there is at most one Y such
that f(X,Y).
Any comparison in the body of a constraint can be replaced by the opposite comparison
in the head. For instance, the last constraint can be rewritten as
Y1 = Y2 :- f(X,Y1), f(X,Y2).
If the head of a rule is a comparison then that rule is not part of a definition; it is a constraint
in disguise. We will return to this example in Section 5.8.
Exercise 2.26. Find a place in Listing 2.6 (page 26) where an anonymous variable can
be used.
Underscores can be eliminated from a rule with anonymous variables by replacing them
with distinct new variables. For instance, rule (2.16) can be rewritten as
R1 = R2 :- filled(R1,Var1,X), filled(R2,Var2,X).
But the process implemented in clingo is different: it “projects out” anonymous variables
using auxiliary predicates. We can project out the anonymous variables in rule (2.16) by
rewriting it as
R1 = R2 :- aux(R1,X), aux(R2,X).
aux(R,X) :- filled(R,Var,X).
Auxiliary predicates, such as aux/2 in this example, are not shown in the output of clingo,
so that they remain invisible to the user.
It is important to keep this detail in mind when an anonymous variable is used in the
scope of negation. Consider, for instance, the program
{p(1..2)}.
(2.17)
:- not p(_).
The corresponding program with the auxiliary variable projected out is
{p(1..2)}.
aux :- p(Var).
:- not aux.
This program has 3 stable models:
Answer: 1
p(2) aux
Answer: 2
p(1) aux
Answer: 3
p(1) p(2) aux
The same answers will be produced by clingo in response to program (2.17), except that
the atom aux will be hidden. If, on the other hand, we replace the underscore in (2.17) with
Var then the response of clingo will be different: it will tell us that the program is unsafe.
Example (2.17) illustrates a general fact: adding the constraint
:- not p(_).
to any program weeds out its stable models in which p/1 is empty.
Exercise 2.27. Given the program
p(1,1).
q(X) :- X = 1..2, not p(X,_).
what solutions do you think clingo is going to produce?
2.9. BIBLIOGRAPHICAL AND HISTORICAL REMARKS 33
p(X) :- X = 8..12.
The rule
from the answer to Exercise 2.17 has the same meaning as the shorter rule
because the conditions N = 1..n, I > 1, N\I = 0 entail I = 2..N; however, the shorter
rule is rejected by clingo as unsafe. There are reasons to believe that an algorithm that
would correctly identify all “truly safe” rules is impossible [80].
The polynomial x2 + x + 41, used as an example in Section 2.3, is interesting for two
reasons. First, it is a “prime number generator”: if you start calculating its values for
x = 0, 1, 2, . . . , you will get a long sequence of primes. The first composite number in this
sequence corresponds to x = 40: 402 + 40 + 41 = 412 . Second, this is the polynomial that
Charles Babbage chose, many years ago, to illustrate the idea of using his Difference Engine
for evaluating polynomials [56].
There are no choice rules and no constraints in Prolog, and the first version of Smodels
did not have them either. Whenever a logic program with several stable models was needed,
Smodels programmers achieved that result using a “nonstratified” combination of rules
with negation as failure, as in the program
p :- not q.
q :- not p.
It has two stable models: one of them includes p but not q; the other includes q but not p.
(Incidentally, such combinations of rules are never found in Prolog programs. They would
cause Prolog to go into infinite loop.) We will return to this example in Chapter 5.
The answer set solver dlv [75] uses a different mechanism for describing multiple stable
models—disjunctive rules, which have more than one atom in the head. Disjunctive rules
are available in the language of clingo as well, and we will see examples in Sections 4.4
and 4.5. A book [87] about logic programs with disjunctive rules (but without negation as
failure) was published in 1992.
34 CHAPTER 2. INPUT LANGUAGE OF CLINGO
In the absence of constraints in the early days of ASP, the programmer who wanted to
eliminate some of the stable models of a program would achieve that by adding a carefully
constructed group of rules with nonstratified negation. With choice rules and constraints
incorporated in the second version of Smodels [99], ASP programs became more concise
and easier to understand.
The tradition of using underscores for anonymous variables, as much else in the syntax
of ASP programs, came from Prolog.
Chapter 3
Combinatorial Search
In a combinatorial search problem, the goal is to find a solution among a finite number of
candidates. The ASP approach is to encode such a problem as a logic program whose stable
models correspond to solutions, and then use an answer set solver, such as clingo, to find
a stable model.
In this chapter we discuss a few examples illustrating this approach to search.
35
36 CHAPTER 3. COMBINATORIAL SEARCH
not change, but each stable model is enriched by atoms that involve the newly defined
predicate.
Exercise 3.1. What is the number of stable models (a) of the first rule of the seating
arrangements program? (b) of the first two rules? (c) of the first three rules?
Exercise 3.2. There are n tables in the room, with m chairs around each table. The
guests are numbered from 1 to mn, and we would like to choose a table for each of them so
that guests who like each other sit at the same table, and guests who dislike each other sit
at different tables. What rules would you place in Lines 15, 18, 21 of Listing 3.3 to get a
clingo program that does it?
38 CHAPTER 3. COMBINATORIAL SEARCH
Exercise 3.6. How many models do you think this program has for r = 2 and n = 4?
Exercise 3.7. What is the number of stable models of the rule in Line 7?
Exercise 3.8. About a set X of numbers we say that it is almost sum-free if the sum
of two different elements of X never belongs to X. For instance, the set {1, 2, 4} is almost
3.4. DIGRESSION ON GROUNDING AND SOLVING 41
sum-free. If we want to describe partitions of {1, . . . , n} into r almost sum-free sets, how
will you change the program in Listing 3.6?
If we run the program in Listing 3.6 for r = 3 and various values of n then we will see
that the largest n for which stable models exist is 13. In other words, S(3) = 13. In a
similar way, clingo can tell us that S(4) = 44. In the next section we say more about
using clingo for calculating Schur numbers.
Exercise 3.9. Use clingo to verify that S(5) ≥ 130.
Exercise 3.10. About a set of numbers we say that it contains an arithmetic progression
of length 3 if it has three different elements a, b, c such that b − a = c − b. We would like
to write a clingo program that partitions {1, . . . , n} into r subsets that do not contain
arithmetic progressions of length 3, if this is possible. What rule would you place in Line 11
of Listing 3.7 to get this result?
The difference between the total time, 0.189 sec, and the solving time, 0.16 sec, is explained
by the fact that the operation of clingo begins with grounding—generating and simplifying
the instances of rules that are essential for finding the stable models. In this case, the
grounding time was around 0.03 sec; grounding was followed by the solving phase, which
took 1.16 sec.
There are cases when the solving time of a clingo program is so large that the program
is unusable. This happens, for instance, with the program in Listing 3.6 for large values
of r and n. This is not surprising, because answer set solvers (and satisfiability solvers) are
often used to solve intrinsically difficult, NP-hard problems. The runtimes of all (known)
algorithms solving NP-hard problems grow exponentially with the size of the problem. But
if large solving time is an issue then it may be useful to remember that clingo has several
solving strategies, and we can instruct it to try several strategies in parallel. For example,
the command
clingo -c r=4 -c n=45 schur.lp -t4
will instruct clingo to try solving the problem with 4 “threads,” and the output may look
like this:
UNSATISFIABLE
. . .
Threads : 4 (Winner: 2)
Information on the “winner” tells us which thread reached the goal first.
There are also cases when the grounding time of a program is unacceptably large. In
the case of the program from Exercise 2.18, the solving time is negligible, but the grounding
time grows quickly as n becomes larger. To understand why, look at the rule
suggested in Appendix A for Line 6 of the program (page 155). The instances of this rule
that are identified by clingo as essential for generating the stable model are obtained by
substituting arbitrary values between 0 and n for each of the variables I, J, K, and the
number of such instances is (n + 1)3 , it grows quickly with n. Significant grounding times
are typical for ASP programs containing a rule with many variables, and we try to avoid
including such rules in an encoding when possible.
The grounding time of the program from Exercise 2.18 can be improved using the fact
that the summands in the expression i2 + j 2 + k 2 can be always reordered so that i ≤ j ≤ k.
Rewriting the definition of three/1 in the form
The program from Exercise 2.18 can be further optimized by exploiting the fact that
√
the values of I, J, and K cannot be greater than n:
For some clingo programs, the process of grounding does not terminate at all. Given
the program
p(0).
(3.1)
p(N+2) :- p(N).
(the current version of) clingo dies and has to be restarted. We will return to this example
in Section 4.7.
{52314,
32541,
15432,
34512,
42513,
24315,
12345}
(i) if a sensor is attached to a zone, but the sensor and the zone are assigned to different
control units, then these two control units are partners;
(ii) the number of sensors assigned to a unit, the number of zones assigned to a unit, and
the number of partners of a unit do not exceed given upper bounds.
For example, the graph in Figure 3.2 shows a solution for the configuration in Figure 3.1
with 4 control units, assuming that each of the upper bounds (ii) equals 2. The horizontal
edges represent the partnership relation between units.
A clingo program solving the partner units problem is shown in Listing 3.11, and
Listing 3.12 is an input for that program corresponding to the example above.
zones
sensors
In Section 6.4 we will see how clingo can be instructed to solve the optimization version
of the set packing problem—to find the largest possible number of pairwise disjoint members
of a given list of sets.
Exercise 3.13. In the exact cover problem, we are given a list of finite sets, and the
goal is to find a part of the list such that its members are pairwise disjoint, and their union
is the same as the union of the entire list. What rules would you place in Lines 13, 16, 19
of Listing 3.15 to get a clingo program that finds a solution, if it exists?
a d
b e
c f
In a logic program, a directed graph can be described by two predicates, vertex/1 and
edge/2. For example, the graph shown in Figure 3.3 can be represented by the rules
vertex(a; b; c; d; e; f).
(3.2)
edge(a,b; b,c; c,a; d,f; f,e; e,d; a,d; f,c; b,e).
These rules can be viewed also as a representation of the corresponding undirected graph.
A clique in a graph is a subset of its vertices such that every two distinct vertices in it
are adjacent. For example, the graph in Figure 3.3 has cliques {a, b, c} and {d, e, f }, and
50 CHAPTER 3. COMBINATORIAL SEARCH
many smaller cliques, but no cliques of size 4. The program shown in Listing 3.16 describes
cliques of a given size.
Exercise 3.14. A vertex cover of a graph is a set of vertices such that every edge of the
graph has at least one endpoint in that set. We would like to find a vertex cover of size n,
if it exists. What rules would you place in Lines 6, 9, 10, 14 of Listing 3.17 to get a clingo
program that produces this result?
Exercise 3.15. We would like to write a clingo program that finds a way to color the
vertices of a given graph so that no two adjacent vertices share the same color. What rules
would you place in Lines 8 and 12 of Listing 3.18?
By running the program from the last exercise a few times, with different sets of colors,
we can estimate the chromatic number of a graph—the smallest number of colors needed
to color its vertices. In Section 6.4 we will see how we can instruct clingo to calculate the
chromatic number.
A Hamiltonian cycle in a directed graph is a cycle that visits every vertex of the graph
exactly once. For example, (a, b, e, d, f, c, a) is a Hamiltonian cycle in the graph from Fig-
ure 3.3.
An encoding of Hamiltonian cycles in the language of clingo is shown in Listing 3.19. In
the choice rule in Line 8, the variable X is global, and the variable Y is local (see Section 2.6).
The stable models of this rule (with definitions of vertex/1 and edge/2 added) correspond
to the sets of edges such that every vertex x of the graph is the tail of exactly one edge
52 CHAPTER 3. COMBINATORIAL SEARCH
(x, y) from that set. Adding the choice rule in Line 9 ensures, in addition, that every vertex
y of the graph is the head of exactly one edge from that set. Thus adding the second choice
rule does what it usually accomplished by adding a constraint—it eliminates some of the
unwanted candidate solutions.
Every Hamiltonian cycle is represented by one of the stable models of this pair of choice
rules, but the converse does not hold—some of these stable models do not correspond to
cycles. Consider, for instance, the edges
(a, b), (b, c), (c, a), (d, f ), (f, e), (e, d)
of the graph in Figure 3.3. Every vertex of the graph is the head of exactly one edge from
this set, and also the tail of exactly one edge from this set, but these edges do not form a
cycle. To eliminate the unsuccessful candidates like this, we need to require that any vertex
of the graph be reachable from any other vertex by a chain of edges from in/2. In the
program, this is accomplished using the set reachable/1 of all vertices that are reachable
by such a chain from some fixed vertex v0.
6
2 8
1
The goal is to fill the grid so that consecutive numbers connect horizontally, vertically, or
diagonally.
Exercise 3.16. Solve the puzzle in Table 3.1.
The program shown in Listing 3.21 solves the Number Snake puzzles in which the grid
is a square of size n, and the numbers go from 1 to n2 . The inequality in Line 14 expresses
that the √
distance between the centers of the squares (R1,C1) and (R2,C2) is less than or
equal to 2; this is equivalent to saying that the squares connect horizontally, vertically, or
diagonally.
Exercise 3.17. Cover a chessboard by twenty-one 3 × 1 tiles and one 1 × 1 tile.
The program in Listing 3.22 solves the problem from Exercise 3.17. This encoding
describes all possible ways to place twenty-one 3 × 1 tiles on the board without overlaps; it
does not mention the 1×1 tile explicitly. The expressions h(1..6,1..8) and v(1..8,1..6)
represent the 48 possible positions of horizontal tiles and the 48 possible positions of vertical
tiles, so that the choice rule in Line 7 requires the total number of tiles, both horizontal
and vertical, to be 21.
Addition in Line 10 is applied to a number and an interval—to C and 1..2. In the
language of clingo, this is understood as forming the set of all integers that can be obtained
by adding C and a number from the interval 1..2. In other words, this expression has the
same meaning as C+1..C+2. Similarly, R-(0..2) in Line 16 has the same meaning as
R-2..R. Applying arithmetic operations to intervals in the language of clingo is discussed
in Section 4.6 in more detail.
8. The man living in the house right in the center drinks milk.
10. The man who smokes Blend lives next to the one who has cats.
11. The man who has horses lives next to the Dunhill smoker.
15. The man who smokes Blend has a neighbor who drinks water.
3.11. PROGRAMMING EXERCISES 57
Use clingo to determine who owns the fish. To test your encoding, verify that it has a
unique stable model.
Clique Cover
Write a program for clingo to cover the set of vertices of a given graph by n cliques, if
possible. To test your program, use the graph from Figure 3.3.
Bishops on a Chessboard
Use clingo to determine how many bishops can be placed on a chessboard so that they do
not attack each other.
?
A
B
D C
E
Write a program for clingo that determines what letter can replace the question mark if
we fill the grid so that each letter is used once in each row, each column, and each of the
two diagonals.
Hitori
In a Hitori puzzle, you are given a square grid with integers appearing in all squares. The
object is to darken some of the squares so that
• in undarkened squares, no number appears in any row or column more than once,
the form W (3, r). For example, W (3, 3) = 27 [25]; this can be easily confirmed by clingo.
It is known also that W (3, 4) = 293 [72].
Deciding whether a given instance of the permutation matching problem has a solution
is NP-complete [14].
Sequence covering arrays, and the answer set approach to generating them, were intro-
duced in 2012 [74, 15].
Applications of the partner units problem include traffic management and security. The
program in Listing 3.11 is reproduced, with minor changes, from a 2011 paper [3].
The search problems discussed in Sections 3.8 and 3.9 belong to the list of 21 NP-
complete problems in the classical paper [69]. To be precise, the concept of NP-completeness
applies to the corresponding decision problems—determining whether a solution exists.
The list includes the set packing problem, the exact cover problem, the clique problem, the
vertex cover problem, graph coloring problem, and the Hamiltonian cycle problem.
Hidato is an invention of the computer scientist Gyora Benedek. Its name comes from
the Hebrew word hida (puzzle). Hidato puzzles of different degrees of difficulty are available
at http://hidato.com.
The eight queens puzzle was published by the chess composer Max Bezzel in 1848. It is
often used as an example in introductory programming courses. Here is the Pascal program
solving this puzzle from a classical book on programming methodology [118]:
program eightqueen1(output);
try(i + 1, q);
if not q then
begin
a[j] := true;
b[i + j] := true;
c[i - j] := true;
end
end
else
q := true
end
until q or (j = 8);
end;
begin
for i := 1 to 8 do a[i] := true;
for i := 2 to 16 do b[i] := true;
for i := -7 to 7 do c[i] := true;
try(1, q);
if q then
for i := 1 to 8 do write( x[i]:4);
writeln
end.
Chapter 4
In this chapter and the next, we discuss the mathematical definition of a stable model. In
the process, we introduce a few syntactic features of the input language of clingo that
have not been mentioned earlier.
The first step is to review a few concepts related to propositional formulas. The presen-
tation here is different from standard in that we write implications “backwards”:
q ← p (q if p)
instead of
p→q (if p then q).
This makes propositional formulas syntactically closer to rules in a logic program.
As common in the literature on logic programming, truth assignments are represented
here by sets of atomic formulas. For instance, assigning true to p and q and false to all
other atomic formulas will be represented by the set {p, q}. This is convenient because of
the role of sets of atoms in logic programming: a stable model is a set of ground atoms.
61
62 CHAPTER 4. PROPOSITIONAL PROGRAMS AND MINIMAL MODELS
F ¬F
false true
true false
F G F ∧G F ∨G F ←G
false false false false true
false true false true false
true false false true true
true true true true true
Exercise 4.2. Find a formula that is satisfied by {p} and by {q} but is not satisfied by
{p, q}.
We say that an interpretation I is a model of a set Γ of formulas if I satisfies all formulas
in Γ.
Exercise 4.3. Assuming that the vocabulary is {p, q, r}, find all models of the set
{p ← q ∧ r, q ← p, r ← p}.
Exercise 4.4. Assuming that the vocabulary is {p, q, r, s}, find all models of the set
{p ← q, q ← r, r ← s, s ← p}.
Exercise 4.5. Assuming that the vocabulary is {p1 , p2 , . . . , p8 }, find the number of models
of
(a) p1 ∧ p2 ,
(b) p1 ← p2 .
Exercise 4.6. Assuming that vocabulary is the infinite set {p0 , p1 , p2 , . . . }, find all models
of the infinite sets
4.2. EQUIVALENCE 63
The formulas in the examples and exercises above use the implication symbol ← in a
limited way. Some of them do not contain implication at all. Others have the form F ← G,
where F and G do not contain implication. Formulas of these two kinds will be called
propositional rules, and sets of propositional rules will be called propositional programs.
We will drop “propositional” when it is clear from the context that we are not talking about
rules and programs in the language of clingo. About a propositional rule F ← G we say
that F is its head and G is its body. If there are no implications in F then we say that
the whole formula F is the head of the rule.
Our plan is to define the concept of a stable model for propositional programs, and use
that definition as the basis for the study of stable models of clingo programs.
Note that a propositional program is a set of rules, not a list. The collection of stable
models of a propositional program, as we are going to define it, will not depend on how
the rules are ordered. This fact reflects a property of clingo: if we change the order of
rules of a clingo program, its stable models will remain the same, although the runtime
may change, as well as the order in which the stable models are generated. It contrasts
with properties of sequential composition in imperative programming, where the order of
components (for instance, assignments) is essential. The order of rules in a clingo program
is only important to humans who read the program: like the availability of comments, it
may affect our ability to understand the program’s design.
Furthermore, a model of a propositional program is a set of atoms, not a list. The order
in which the elements of a stable model are displayed by an answer set solver has no special
significance. It may change from one version of the system to another.
4.2 Equivalence
Two formulas or sets of formulas are equivalent to each other if they have the same models.
For instance, the set {p, q ← p} is equivalent to the formula p ∧ q.
When two formulas or sets of formulas are not equivalent, this fact can be demonstrated
by a counterexample—an interpretation that satisfies one of them but not the other. For
instance, the formula p ∧ q ∧ r is not equivalent to p ∧ q because the interpretation {p, q}
satisfies the latter but not the former.
Exercise 4.7. Determine whether the given formulas or sets of formulas are equivalent.
If they are not, give a counterexample.
(a) {p ← q, q ← r} and p ← r.
Table 4.1: Simplifying formulas and sets of formulas containing > and ⊥.
A set of formulas containing an atomic formula p can be simplified by replacing p with >
in the other formulas that contain p, and then simplifying each of these formulas. Similarly,
if a set of formulas contains ¬p then it can be simplified by replacing p in other formulas
by ⊥.
Exercise 4.9. Simplify each of the given sets of formulas.
(a) {p, p ∨ q ← r}.
(b) {¬p, p ∨ q ← r}.
{p ← q, q ∨ r}.
Note that in the last exercise the vocabulary is not specified. Since the question is
about minimal models, there is no need to know whether the vocabulary includes any
atomic formulas other than p, q, and r: such an atomic formula, if it is available, cannot
belong to a minimal model.
Exercise 4.15. Describe (a) the models of the empty set of formulas, (b) the minimal
models of the empty set.
Exercise 4.16. For the case when all elements of Γ are atomic formulas, describe (a) the
models of Γ, (b) the minimal models of Γ.
Exercise 4.17. Find a propositional rule that has exactly four minimal models.
Exercise 4.18. It is clear that if two formulas or sets of formulas are equivalent then
they have the same minimal models. But the converse is not true: two formulas may have
the same minimal models even though they are not equivalent to each other. Find such a
pair of formulas.
(i) its head is the conjunction of a non-empty set of atomic formulas (for instance, a
single atomic formula), and
(ii) its body (if it has one) does not contain negation.
p, (4.2)
q ← p ∧ r, (4.3)
r ← p ∨ t, (4.4)
s ← r ∧ t. (4.5)
Which atomic formulas need to be included in any model of (4.2)–(4.5)? To satisfy (4.2),
we must include p. Once p is included, the body of (4.4) becomes true, and to satisfy that
rule we must include r. Now the body of (4.3) became true, and to satisfy that rule we
4.3. MINIMAL MODELS 67
must include q. The set of atomic formulas that we have accumulated, {p, q, r}, satisfies all
formulas (4.2)–(4.5). This is the minimal model of the program.
Exercise 4.19. Describe the step-by-step process of constructing the minimal model of
the program
p 1 ∧ p 2 ← q1 ∨ q2 ,
q1 ← r1 ∨ r2 ,
r1 .
{p1 ← p2 ∧ p3 , p2 ← p3 ∧ p4 , . . . , p8 ← p9 ∧ p10 }.
For each of the following programs, describe the step-by-step process of constructing its
minimal model.
(a) Π,
(b) Π ∪ {p5 },
(c) Π ∪ {p5 , p6 }.
It is clear that condition (i) in the definition of a definite rule is essential: if we drop
it then the claim that every definite program has a unique minimal model will become
incorrect. Rule p ∨ q can serve as a counterexample. Indeed, it satisfies condition (ii),
because it has no body, but it has two minimal models.
Exercise 4.21. Condition (ii) in the definition of a definite rule is essential also. Give a
counterexample illustrating this fact.
Π = {p1 ← p2 , p2 ← p3 , p3 ← p4 , p4 ← p5 , . . . },
Σ = {p2 ← p1 , p3 ← p2 , p4 ← p3 , p5 ← p4 , . . . }.
For each of the following programs, describe the step-by-step process of constructing its
minimal model.
(a) Π ∪ {p3 },
(b) Σ ∪ {p3 }.
68 CHAPTER 4. PROPOSITIONAL PROGRAMS AND MINIMAL MODELS
Table 4.2: Correspondence between symbols in clingo rules and in propositional formulas.
In a clingo program, this rule has the same meaning as the constraint
:- p, q.
In other words, adding this rule to a program eliminates its stable models that contain both
p and q.
Rewriting rule (4.4) in the syntax of clingo is less straightforward, because the body of
this rule is a disjunction, and in the language of clingo there is no symbol for disjunction
in the body. But this rule can be replaced by an equivalent pair of simpler rules; see
Exercise 4.7(c).
Exercise 4.23. (a) Rewrite program (4.2)–(4.5) in the syntax of clingo. (b) Use clingo
to find its stable model.
Exercise 4.24. (a) Do the same for the program from Exercise 4.19.
Exercise 4.25. Use clingo to find the number of stable models of the program
p ∨ q,
r ∨ s,
s1 ∨ s2 ← s,
⊥ ← p ∧ s1 .
Answer set solvers can be used to generate arbitrary models of a propositional program,
not only minimal/stable models as in the examples above. In other words, they can function
as satisfiability solvers. We will talk about it in Section 5.4. The other way around, a
satisfiability solver can be sometimes used for generating stable models, as we will see in
Section 5.9.
H1 , . . . , Hm :- B1 , . . . , Bn . (4.6)
(i) by replacing the symbol :- and all commas in the head and the body by propositional
connectives as shown in Table 4.2, and dropping the period at the end of the rule;
(ii) by replacing each comparison t1 ≺ t2 in the head and in the body by > if it is true,
and by ⊥ if it is false;
(iii) by replacing the head of the rule by ⊥ if it is empty, and replacing the body by > if
it is empty.
Note that this definition is limited to clingo programs satisfying the two conditions
stated at the beginning of this section. A more general definition of the propositional image
will be given in Section 4.7. Then it will be generalized again in Sections 5.6 and 5.7, and
at that point we will see that the propositional images of some clingo programs are not
positive.
Definition. A stable model of a clingo program is a stable model of its propositional
image.
For instance, the propositional images of facts (1.2) are the atomic formulas
if v1 > v2 , and
large(v0 ) ← size(v0 , v1 ) ∧ size(uk, v2 ) ∧ ⊥ (4.11)
otherwise. Consequently the propositional image of clingo program (1.1), (1.2) consists of
propositional rules (4.9)–(4.11) for arbitrary v0 , v1 , v2 from S ∪ Z.
This program is definite (Section 4.3), so that is has a unique minimal model, and that
model can be constructed by accumulating the atoms that need to be included to satisfy
all its rules. Before doing this calculation, we will simplify the program. Formulas (4.11)
are tautologies and can be dropped, and in formula (4.10) the conjunctive term > can be
dropped. Consequently program (4.9)–(4.11) is equivalent to the propositional program
consisting of rules (4.9) and the rules
To satisfy these rules, we need to include, first of all, atomic formulas (4.9). After that,
among the infinitely many rules (4.12) there will be two that are not satisfied:
and
large(germany) ← size(germany, 83) ∧ size(uk, 64).
Once the heads
large(france), large(germany) (4.13)
of these rules are added, the construction of the minimal model will be completed.
This calculation justifies the assertion in Section 1.3 that atoms (4.9), (4.13) form the
only stable model of clingo program (1.1), (1.2).
Exercise 4.26. (a) Find the propositional image of the program
p(0,1).
p(1,2).
q(X,Y) :- p(X,Y), X > 0, Y > 0.
(b) Simplify it. (c) Describe the step-by-step process of constructing its minimal model.
(d) Check whether your answer is in agreement with the output of clingo.
Exercise 4.27. (a) Find the propositional image of the program consisting of rules (2.1),
(2.2), (2.8) (pages 15 and 22). (b) Describe the step-by-step process of constructing its
minimal model.
(b) Simplify it. (c) Find all its minimal models. (c) Check whether your answer is in
agreement with the output of clingo.
The above definition of a stable model is applicable even the program is unsafe. For
instance, the propositional image of program (2.4) on page 17 consists of the rules
Its only minimal model is obviously the set of all atoms p(v) with v > 7, as we claimed in
Section 2.1.
Exercise 4.29. (a) Find the propositional image of the unsafe program
p(a).
q(X,Y) :- p(X).
p(2*2).
Table 4.3: Correspondence between symbols for arithmetic operations in clingo terms and
in standard algebraic notation. The symbol bxc denotes the floor of a real number x, that
is, the largest integer less than or equal to x. The use of this symbol in the last line is
needed because n can be negative; then mn is a fraction.
For instance, the only value of 2*2 is 4, because the only value of 2 is 2, and 2 · 2 = 4.
The set of values of 2/0 is empty, because division by 0 is undefined. The set of values of
2*a is empty as well, because the only value of the symbolic constant a is not an integer.
The same goes for 2..a.
It is clear that every value of a ground term is either a symbolic constant (if the term
itself is a symbolic constant) or an integer.
Exercise 4.30. Determine for which of the following terms the set of values is empty.
(a) 6..5.
(b) a..(a+1).
(c) 2**(-2).
Exercise 4.32. Find a ground term (a) with the values 1, 3, 9; (b) with the values 22,
32, 42.
74 CHAPTER 4. PROPOSITIONAL PROGRAMS AND MINIMAL MODELS
Table 4.4: Propositional images of ground atoms and comparisons. Here p is a symbolic
constant, each ti is a ground term, and ≺ is a comparison symbol.
• the propositional image of the atom p(1/0) in the head is the empty conjunction >,
but the propositional image of the same atom in the body is the empty disjunction ⊥
(see the discussion of the empty conjunction and empty disjunction at the end of
Section 4.2);
• the propositional image of the comparison 1..2 = 2..3 in the head is ⊥ (because it
is not true that every element of one of the sets {1, 2}, {2, 3} is an element of the
other), but the propositional image of the same comparison in the body is > (because
sets {1, 2} and {2, 3} have a common element).
However, if each of the terms t1 , . . . , tk is a symbolic constant or an integer, as in Section 4.5,
then the only value of ti is ti itself, so that the conjunction in the first line of Table 4.4
is the single atom p(t1 , . . . , tk ), and the disjunction in the second line of the table is the
same atom. Similarly, if each of the terms t1 , t2 is a symbolic constant or an integer then
the truth value described in the third line of the table is > or ⊥ depending on whether
4.7. MORE ON PROPOSITIONAL IMAGES 75
the condition t1 ≺ t2 is true or false, and the value in the fourth line is calculated in the
same way. We conclude that the definition of the propositional image above has the same
meaning as the definition in Section 4.5 when the program contains neither arithmetical
operations nor intervals.
If each of the terms t1 , . . . , tk is formed from integers using addition, subtraction, and
multiplication, then ti has a unique value vi , so that the conjunction in the first line of
Table 4.4 is the atom p(v1 , . . . , vk ), and so is the disjunction in the second line. For instance,
the propositional image of p(2*2) is p(4) no matter whether this atom occurs in the head
or in the body.
Consider, for instance, one-rule program (2.7) (page 20). Its propositional image consists
of the rules
p(0, 41) ← >,
p(1, 43) ← >,
p(2, 47) ← >,
(4.14)
p(3, 53) ← >,
p(n, n2 + n + 41) ← ⊥ for all n ∈ Z \ {0, . . . , 3},
> ← ⊥.
(The last formula corresponds to the instances of (2.7) obtained by substituting symbolic
constants for N.) The rules in the last two lines are tautologies, and the other rules can be
equivalently written as
p(0, 41), p(1, 43), p(2, 47), p(3, 53).
Consequently these atoms form the only stable model of (2.7), in accordance with the claim
about this program made in Section 2.3.
The propositional image of the program
p(2).
p(a).
q(X+1) :- p(X).
The rules in the last line are tautologies and can be dropped. The stable model of the
program is {p(2), p(a), q(3)}.
Exercise 4.33. For each of the given rules, find its propositional image. Which of the
propositional images are tautologies?
(a) square(1..2,1..2).
(b) q :- square(1..2,1..2).
76 CHAPTER 4. PROPOSITIONAL PROGRAMS AND MINIMAL MODELS
(c) square(abra..cadabra,abra..cadabra).
(d) q :- square(abra..cadabra,abra..cadabra).
p(1).
q :- p(1..3).
(b) Find the minimal model of the propositional image. (c) Check whether your answer is
in agreement with the output of clingo.
p(1/N) :- N = 0..1.
p(1..3).
q(X) :- p(X), X = 2..4.
(b) Simplify it. (c) Describe the step-by-step process of constructing its minimal model.
(d) Check whether your answer is in agreement with the output of clingo.
p(1,1..2).
q(X,Y) :- p(X,Y), X != Y.
q(X,Y) :- q(Y,X).
p(1..3).
q(N-1..N+1) :- p(N).
p(1..3).
X = 1 :- p(X).
Exercise 4.40. (a) Find the propositional image of the unsafe program
4.8. BIBLIOGRAPHICAL AND HISTORICAL REMARKS 77
p(1).
q(X) :- p((-1)**X).
p(0),
p(m) ← p(n) for all n ∈ Z, where m is the value of n + 2,
> ← p(v) for all v ∈ S.
The rules in the last line are tautologies and can be dropped. The result is a definite
program, and the process of constructing its minimal model involves infinitely many steps:
we include p(0), then add p(2), then add p(4), and so on. This is similar to what we saw in
Exercise 4.22(b) on page 67.
Programs (2.4) and (3.1) are similar to each other in the sense that each of them has
a unique infinite stable model, but clingo responds to these programs in different ways:
it rejects the former as unsafe, but it tries—unsuccessfully—to ground the latter. The
difference can be explained in terms of the process of accumulating the ground atoms that
need to be included in the minimal model of the propositional image. With (2.4) and similar
unsafe programs, the set of accumulated atoms becomes infinite after several steps. In case
of (3.1), the set of accumulated atoms remains finite at every step, and the minimal model
turns out to be infinite only because the number of steps is infinite. Such programs are
treated by clingo as safe.
The classical truth table for implication is the best possible choice as long as we intend to
characterize the meaning of implication in terms of two truth values. But it describes only
one of many meanings of the word “if” [61].
Logical minimization of the kind described in this chapter plays an important part in
the theory of “nonmonotonic reasoning.” This term describes the situations when reasoners
draw tentative conclusions that may be retracted on the basis of further evidence. Reasoning
found in mathematical proofs is monotonic: when a theorem is derived from a set of axioms,
adding more axioms will not invalidate the proof. (This is so even if extending the set of
axioms makes it inconsistent: in this case, every proposition becomes a theorem, including
the theorems proved earlier.) But commonsense reasoning, practiced in everyday life, is
often nonmonotonic. For example, we often deal with lists that are presumed to be complete.
Conclusions based on such an assumption may need to be retracted when we get additional
information. Something like this happened when Prolog and clingo told us, in response
to rules (1.1), (1.2), that in 2015 there were two countries in Europe populated by more
people than the United Kingdom. We realized that the number of such countries is actually
three when we took into account the fact that Russia is a European country (Exercise 2.1
on page 15).
Theory of nonmonotonic reasoning became an active area of research after the publica-
tion of the special issue of the journal Artificial Intelligence on nonmonotonic reasoning in
1980 [2]. One of the mathematical models of nonmonotonic reasoning described in that jour-
nal used the syntactic transformation called circumscription [90, 91]. To give an example,
the result of applying this transformation to the formula
Formula (4.15) expresses that a and b are elements of the set p, and c is an element of q;
the result (4.16) of “circumscribing p and q” in that formula expresses that these lists of
elements are complete, so that a and b are the only elements of p, and c is the only element
of q. This is similar to what happens when we apply the definition of the minimal model
given in this chapter to formula (4.15): in the minimal model
of that formula, the atoms p(c), q(a) and q(b) are false, so that c does not belong to p,
and a, b do not belong to q.
Interaction between the semantics of logic programs and the theory of nonmonotonic
reasoning is the theme of biannual international conferences on logic programming and
nonmonotonic reasoning that have been held in America and Europe since 1991. We will
return to this subject in connection with the semantics of negation as failure in the next
chapter, and in connection with the frame problem in Chapter 7.
4.8. BIBLIOGRAPHICAL AND HISTORICAL REMARKS 79
The discussion of ground terms in Section 4.6 follows the account of the semantics of
clingo published in 2015 [43]. The explanation of the difference between two kinds of
programs with infinite stable models is based on the theory of safe rules proposed a year
later [80].
80 CHAPTER 4. PROPOSITIONAL PROGRAMS AND MINIMAL MODELS
Chapter 5
Our next goal is to extend the definition of a stable model from Chapter 4 to propositional
programs that contain negation. We begin with an informal discussion of a few examples.
5.1 Examples
The program
p,
q,
r ← p,
s←q
is positive definite, and its stable model can be formed by accumulating the atomic formulas
that are needed to satisfy all rules: we include p and q to satisfy the first two rules, and
then add r and s to satisfy the other two. The stable model is {p, q, r, s}. Consider the
modification of that program in which the conjunctive term ¬s is added to the body of the
third rule:
p, (5.1)
q, (5.2)
r ← p ∧ ¬s, (5.3)
s ← q. (5.4)
We think of this conjunctive term as a restriction on the process of accumulating atomic
formulas in the process of constructing the stable model. Rule (5.3) instructs us to add r
to the model if p is included under the condition that
s is not included in the model and will not be included in the future. (5.5)
Since the program contains rules (5.2) and (5.4), the model that we are building will in-
clude s, so that the conjunctive term ¬s “disables” the third rule of the program. Since r
81
82 CHAPTER 5. PROGRAMS WITH NEGATION
is not added in the process of accumulating atomic formulas, the stable model of pro-
gram (5.1)–(5.4) is {p, q, s}.
Consider now the program consisting of only three rules (5.1)–(5.3). Since the heads of
the rules of this program do not contain s, condition (5.5) is satisfied, and, in accordance
with rule (5.3), we add r. The stable model of program (5.1)–(5.3) is {p, q, r}.
These conclusions about the stable models of programs (5.1)–(5.4) and (5.1)–(5.3) are
in agreement with the behavior of clingo.
The idea that a negation in the body of a rule represents a restriction that can “disable”
the use of that rule for accumulating atomic formulas is related to the expression “negation
as failure” (Section 2.4). Condition (5.5) says, for example, that the attempt to justify
including s in the model will fail.
Failure conditions of this kind are somewhat vague, because they are circular: which
rules are disabled depends on which atomic formulas are going to be included in the model,
and the other way around. The definition of a stable model in the next section makes the
idea of negation as failure precise. But there are many cases when the meaning of failure
conditions like (5.5) is sufficiently clear for predicting what output is going to be produced
by an answer set solver.
Exercise 5.1. (a) Use the process described above to find the stable model of pro-
gram (5.1), (5.3), (5.4). (b) Check whether your answer is in agreement with the output of
clingo.
Exercise 5.2. (a) Use the process described above to find the stable model of the program
p ← ¬q, (5.6)
q ← ¬r. (5.7)
(b) Check whether your answer is in agreement with the output of clingo.
The last example we want to look at in this section is the program
p ← ¬q, (5.8)
q ← ¬p. (5.9)
We saw this program, written in the syntax of clingo, in Section 2.9, and asserted there
that it has two stable models. That assertion can be explained by saying that there are two
ways to decide which of the atomic formulas p, q are included in the process of constructing
a stable model. We can include p; then rule (5.9) is disabled, so that q is not included, and
rule (5.8) justifies the presence of p in the model. On the other hand, not including p is
a reasonable option as well; then rule (5.9) justifies including q, rule (5.8) is disabled, and
this fact justifies not including p. So it appears that program (5.8), (5.9) has the stable
models {p} and {q}.
In the next section we give a precise definition of the concept of a stable model applicable
to all propositional programs, and then we will be able to support this claim by a proof.
5.2. STABLE MODELS OF PROGRAMS WITH NEGATION 83
¬p ← ¬(q ∧ ¬r)
has two critical parts: the head ¬p and the body ¬(q ∧ ¬r). (The subformula ¬r is not
critical because it is contained in a larger subformula that begins with negation.)
Definition. Let F be a propositional rule, and let I be an interpretation. The reduct of F
relative to I is the positive rule obtained from F by substituting > for each critical part
that is satisfied by I, and substituting ⊥ for every other critical part. The reduct of a
propositional program Π relative to I is the positive program obtained from Π by the same
process.
Definition. Let Π be a propositional program, and let I be an interpretation. If I is a
minimal model of the reduct of Π relative to I then we say that I is a stable model of Π.
For instance, let Π be program (5.1)–(5.4), and let I be {p, q, s}. Since the critical
part ¬s of the third rule is not satisfied by I, the reduct is
p,
q,
(5.10)
r ← p ∧ ⊥,
s ← q.
This program is definite, and its only minimal model is {p, q, s}—exactly the interpretation I
that we started with. Consequently I is a stable model of (5.1)–(5.4).
The interpretation {p, q} is not a stable model of (5.1)–(5.4). Indeed, the reduct of the
program relative to this interpretation is
p,
q,
(5.11)
r ← p ∧ >,
s ← q,
and {p, q} is not a model of this reduct—it does not satisfy the last two rules.
Interpretation {p, q, r, s} is not a stable model of (5.1)–(5.4) either. Indeed, the reduct
of the program relative to this interpretation is (5.10), and {p, q, r, s} is not minimal among
the models of (5.10).
It is easy to show, in fact, that program (5.1)–(5.4) has no stable models other than
{p, q, s}. Take any interpretation I different from {p, q, s}, and consider two cases. Case 1:
s ∈ I. The reduct of the program relative to I is (5.10). The only minimal model of the
reduct is {p, q, s}, and it is different from I. Consequently I is not stable. Case 2: s 6∈ I.
84 CHAPTER 5. PROGRAMS WITH NEGATION
The reduct of the program relative to I is (5.11), and the only minimal model of the reduct
is {p, q, r, s}. Since this model contains s, it is different from I, so that I is not stable.
Exercise 5.3. (a) Prove that {p, q, r} is a stable model of program (5.1)–(5.3). (b) Prove
that program (5.1)–(5.3) has no other stable models.
Let us find now all stable models of the program
p ∨ q, (5.12)
r ← ¬p. (5.13)
Take an arbitrary interpretation I, and consider two cases. Case 1: p ∈ I. The reduct of
the program relative to I is
p ∨ q,
r ← ⊥.
It has two minimal models, {p} and {q}. The former satisfies the condition p ∈ I that
characterizes Case 1, so that it is a stable model of (5.12), (5.13). Case 2: p 6∈ I. The
reduct of the program relative to I is
p ∨ q,
r ← >.
It has two minimal models, {p, r} and {q, r}. The latter satisfies the condition p 6∈ I that
characterizes Case 2, so that it is a stable model of (5.12), (5.13). We conclude that this
program has two stable models, {p} and {q, r}.
Exercise 5.4. (a) Find all stable models of the program
p ← ¬p.
(b) Check that the result of your calculation is in agreement with the output of clingo.
p ∨ q,
⊥ ← p ∧ ¬q.
Program (5.8), (5.9) contains negations of two atoms, so that four cases need to be
considered in the process of calculating its stable models. Take any interpretation I. Case 1:
p, q ∈ I. The reduct is
p ← ⊥,
q ← ⊥.
5.2. STABLE MODELS OF PROGRAMS WITH NEGATION 85
The minimal model ∅ does not satisfy the condition characterizing this case. Case 2: p ∈ I,
q 6∈ I. The reduct is
p ← >,
q ← ⊥.
The minimal model {p} satisfies the condition characterizing this case, so that {p} is a
stable model of the given program. Case 3: p 6∈ I, q ∈ I. A similar calculation gives the
stable model {q}. Case 4: p, q 6∈ I. The reduct is
p ← >,
q ← >.
The minimal model {p, q} does not satisfy the condition characterizing this case. Conse-
quently the program has two stable models.
Exercise 5.6. Prove that your answer to Exercise 5.2 is correct.
p ← ¬q, (5.14)
q ← ¬p, (5.15)
r ← p, (5.16)
r ← q. (5.17)
(b) Check that the result of your calculation is in agreement with the output of clingo.
p ← ¬q, (5.18)
q ← ¬p, (5.19)
p ← q, (5.20)
q ← p. (5.21)
The process of calculating stable models used in the examples above becomes impractical
when the program contains many negated atomic formulas, because the number of reducts
of a program grows exponentially with the number of critical parts of its rules. Fortunately,
the study of stable models has led to the discovery of theorems that allow us to approach
the problem of calculating stable models in other ways. In the next section, for instance, we
will see how the stable models of the program from Exercise 5.5 can be calculated without
looking at reducts at all. Program completion, defined in Section 5.9, allows us to describe
and calculate the stable models of many logic programs without referring to reducts.
86 CHAPTER 5. PROGRAMS WITH NEGATION
The use of the term “stable model” is justified by the fact that every stable model of
a propositional program is indeed one of its models. In other words, every stable model
satisfies all rules of the program. This property of stable models is not immediately obvious:
the definition only shows that a stable model I of a program satisfies the reduct of the
program relative to I. But any stable model of a program satisfies the program itself as
well, in view of the following theorem:
Theorem on Reducts. An interpretation I satisfies a propositional program Π if and
only if it satisfies the reduct of Π relative to I.
For example, the interpretation {q} satisfies both the one-rule program p ← ¬q and its
reduct p ← ⊥ (which is a tautology); the interpretation ∅ satisfies neither p ← ¬q nor its
reduct p ← >.
From Theorem on Reducts we can conclude that the stable models of a propositional
program can be characterized as follows: an interpretation I is a stable model of Π if and
only if
(i) I is a model of Π, and
Table 5.1 shows the values of f (x) for all values of x. It is clear that this function has two
fixpoints.
5.3. STABLE MODELS AS FIXPOINTS 87
x f (x) fixpoint?
∅ {a, b}
{a} {a, b}
{b} {a, b}
{c} {a, b, c}
{a, b} {a, b} X
{a, c} {a, b, c}
{b, c} {a, b, c}
{a, b, c} {a, b.c} X
Table 5.2: Fixpoints of the stability operator s of the program from Exercise 5.7.
If a propositional program Π satisfies condition (α) then its reduct relative to any
interpretation is a definite program (Section 4.3), so that it has a unique minimal model.
We define the stability operator of Π as the function that maps every interpretation I to
the minimal model of the reduct of I relative to Π. It is clear that the stable models of a
program with property (α) can be characterized as the fixpoints of its stability operator.
Table (5.2), for instance, shows the values of the stability operator of the program from
Exercise 5.7 and its fixpoints—the stable models of the program.
Exercise 5.9. Make the table of values of the stability operator of the one rule program
q ← ¬p
Exercise 5.10. Describe the stability operator of program (4.2)–(4.5) on page 66.
88 CHAPTER 5. PROGRAMS WITH NEGATION
has two stable models, ∅ and {p}. Indeed, the reduct of (5.23) relative to ∅ is p ∨ >, which
is equivalent to >; the minimal model of the reduct is empty. The reduct of (5.23) relative
to {p} is p ∨ ⊥, which is equivalent to p; the minimal model of the reduct is {p}.
In rule (5.23), negation occurs in the head, and not in the body as in the examples that
we have seen before. clingo does not object against negation in the head. It will accept
program (5.23) if we rewrite it as
p, not p.
and it will produce two stable models for it, in accordance with the calculation above. In
other words, clingo views this rule as synonymous to the choice rule {p}.
Exercise 5.11. (a) Find all stable models of the program
p ∨ q,
r ∨ ¬s ← p.
(b) Check that the result of your calculation is in agreement with the output of clingo.
Formula (5.23) is known in logic as the law of excluded middle. (Any proposition p is
either true or false, there is nothing in the middle.) This formula plays an important role
in the theory of stable models because of its close relation to choice rules, and also because
of the following fact:
Theorem on Excluded Middle. An interpretation I is a model of a propositional pro-
gram Π if and only if I is a stable model of the program obtained from Π by adding the
rules p ∨ ¬p for all atomic formulas p.
For example, an interpretation I is a model of the propositional program from Exer-
cise 4.3 (page 62) if and only if it is a stable model of the program obtained from it by
adding the rules
p ∨ ¬p, q ∨ ¬q, r ∨ ¬r.
That means that the question from Exercise 4.3 can be answered by running clingo on
the program
p :- q, r.
q :- p.
r :- p.
p, not p.
q, not q.
r, not r.
5.4. EXCLUDED MIDDLE AND DOUBLE NEGATION 89
{p; q; r}.
has the same meaning as the last three rules of the program above. Consequently it can be
used instead of those rules.
In the special case when Π is empty, Theorem on Excluded Middle describes the stable
models of a set of rules the form p ∨ ¬p: they are arbitrary subsets of the set of atomic
propositions occurring in the rules.
Exercise 5.12. Use clingo to verify your answers to Exercises 4.3, 4.4, 4.5(a), 4.5(b),
4.13(a).
The formula
p ← ¬¬p (5.24)
is known as the law of double negation. From Table 5.3 we see that it has the same stable
models as the law of excluded middle: ∅ and {p}. Thus there is an essential difference
between rule (5.24) and the positive rule p ← p, which is obtained from it by dropping the
double negation. The latter has only one stable model—the minimal model ∅. The fact
that an equivalent transformation, such as dropping a double negation in a propositional
rule, may affect the set of stable models of a program is important. When we want to find
models, or minimal models, of a set of formulas, we often start by simplifying it—replacing
it by an equivalent set of formulas that is simpler. But if our goal is to find stable models of
a propositional program then simplifying the program may lead to a wrong answer. Some
transformations of rules are “strongly” equivalent, in the sense that they do not affect the
set of stable models; but dropping a double negation in front of an atomic formula is not
one of them. (Simplifying the reduct before calculating its minimal models is permissible,
of course; we are talking here about simplifying the program itself.)
It is often useful to know which equivalent transformations of propositional rules are
strongly equivalent, and which are not, and we will talk about this in Section 5.8. For
the time being, it is sufficient to remember two facts. First, the set of stable models of a
program is not affected by the simplifications shown in Table 4.1 (page 64). Second, the
set of stable models does not change if we break a rule with a conjunction in the head into
several rules, corresponding to the conjunctive terms. For instance, replacing p ∧ q ∧ r by
three rules p, q, r is a strongly equivalent transformation, and so is replacing p ∧ q ∧ r ← s
by
p ← s, q ← s, r ← s.
90 CHAPTER 5. PROGRAMS WITH NEGATION
The input language of clingo allows rules with two negations in a row. It will accept,
for instance, program (5.24) if we rewrite it as
p :- not not p.
and it will produce the two stable models shown in Table 5.3.
The designers of clingo decided, however, against permitting three negations in a row.
There is a good reason for that, as we will see in Section 5.8.
p ∨ q,
r ← p,
s ← q,
⊥ ← ¬p,
⊥ ← ¬r ∧ ¬s.
(b) Check whether your answer is in agreement with the output of clingo.
In the special case when program Π is definite (Section 4.3), Theorem on Constraints
shows that the result of adding a constraint ⊥ ← F to Π will have either no stable models
or the same stable model as Π, depending on whether the stable model of Π satisfies F . We
5.6. CLINGO PROGRAMS WITH NEGATION 91
saw, for example, that the stable model of program (4.2)–(4.5) (page is {p, q, r}. Adding the
constraint ⊥ ← ¬s to that program has no stable models; adding the constraint ⊥ ← ¬r
has the stable model {p, q, r}.
p(a).
q(a). (5.26)
r(X) :- p(X), not q(X).
p(a),
q(a), (5.27)
r(v) ← p(v) ∧ ¬q(v) for all v in S ∪ Z.
92 CHAPTER 5. PROGRAMS WITH NEGATION
p(a),
q(a),
r(a) ← p(a) ∧ ⊥,
r(v) ← p(v) ∧ > for all v in S ∪ Z \ {a},
or, equivalently,
p(a),
q(a),
r(v) ← p(v) for all v in S ∪ Z \ {a}.
This is a definite program, and (5.25) is its only minimal model.
The calculation above accomplished less than we would like to, in two ways. First, it
did not lead us from program (5.26) to its stable model; rather, we verified the guess that
a certain interpretation is stable. Second, it did not tell us whether the program has stable
models other than (5.25). In Section 5.10 we will see how to overcome these limitations.
Exercise 5.14. (a) Find the propositional image of the program
p(a).
q(b).
r(X) :- p(X), not q(X).
(b) Find the reduct of this propositional image relative to the interpretation
(c) Simplify the reduct. (d) Find the minimal model of the reduct to determine whether
interpretation (5.28) is a stable model of the program.
p(1).
q :- not p(1..3).
(a) q :- (5/0).
(d) (5/0) :- q.
Consider now the program consisting of rules (2.9) and (2.10) on page 23. We will check
that the interpretation
and infinitely many propositional rules containing ⊥ as a conjunctive term in the body.
Simplification steps from Table 4.1 turn it into the finite program
composite(4),
prime(2) ← ¬composite(2),
prime(3) ← ¬composite(3), (5.32)
prime(4) ← ¬composite(4),
prime(5) ← ¬composite(5).
and is equivalent to (5.30). The only minimal model of that set of atoms is (5.30) itself.
p(1..3).
q(X) :- X = 2..4, not p(X).
94 CHAPTER 5. PROGRAMS WITH NEGATION
(b) Simplify the propositional image by steps from Table 4.1. (c) Find the reduct of the
simplified propositional image relative to the interpretation
(d) Simplify the reduct. (e) Find the minimal model of the reduct and determine whether
interpretation (5.33) is a stable model of the program.
{A1 ; . . . ; Am }. (5.35)
and
{A1 ; . . . ; Am } :- B1 , . . . , Bn . (5.36)
where A1 , . . . , Am are atoms, and B1 , . . . , Bn are as in the previous section—atoms, possibly
prefixed with one or two negations, and comparisons.
As noted in Section 5.4, the law of excluded middle p ∨ ¬p has two stable models, ∅
and {p}. Consequently it can serve as the propositional image of the choice rule {p}.
We will apply this idea to arbitrary rules of forms (5.35) and (5.36) using the following
notation. For any set Ω of ground atoms, V (Ω) will stand for the set of all ground atoms
p(v1 , . . . , vk ) such that for some atom p(t1 , . . . , tk ) from Ω, v1 , . . . , vk are values of t1 , . . . , tk ,
respectively. The propositional image of the head of ground rules (5.35), (5.36) is defined
as the conjunction of the formulas A ∨ ¬A for all atoms A in V ({A1 , . . . , Am }).
For example,
V ({p(1), q(1..3)}) = {p(1), q(1), q(2), q(3)}.
It follows that the propositional image of the rule
is
(p(1) ∨ ¬p(1)) ∧ (q(1) ∨ ¬q(1)) ∧ (q(2) ∨ ¬q(2)) ∧ (q(3) ∨ ¬q(3)) ← ¬r(5).
{p(a)}.
q(X) :- p(X).
(b) Find the reduct of this propositional image relative to the interpretation
{q(a)}. (5.37)
(c) Simplify the reduct. (d) Find the minimal model of the reduct and determine whether
interpretation (5.37) is a stable model of the program.
p(a).
{q(X)} :- p(X).
p, not p.
q, not q. (5.39)
r, not r.
{p, q, r}>1
{A1 ; . . . ; Am } u.
96 CHAPTER 5. PROGRAMS WITH NEGATION
as the pair of propositional rules: the propositional image of choice rule (5.35) as defined
above and the constraint
⊥ ← V ({A1 , . . . , Am })>u . (5.41)
For example, the propositional image of the rule
{p; q; r} 1.
⊥ ← (p ∧ q) ∨ (p ∧ r) ∨ (q ∧ r).
{p(1..2,1..2)} 2.
For any finite set Ω of atomic formulas and any nonnegative integer z, Ω<z will denote
the conjunction of the formulas ¬Π∧ over all subsets Π of Ω that have z elements. This
formula expressed that the number of atomic formulas that are assigned the value true is
less than z. For example, the expression
{p, q, r}<2
l {A1 ; . . . ; Am }.
2 {p; q; r}.
l {A1 ; . . . ; Am } u.
consists of the propositional image of choice rule (5.35) and two constraints (5.41), (5.42).
5.7. CLINGO PROGRAMS WITH CHOICE 97
{p(1..2,1..2)} = 2.
{A1 ; . . . ; Am } u :- B1 , . . . , Bn .
l {A1 ; . . . ; Am } :- B1 , . . . , Bn .
l {A1 ; . . . ; Am } u :- B1 , . . . , Bn .
the propositional image is defined in a similar way: it consists of the propositional image of
choice rule (5.36) and one or two constraints. The constraints are (5.41) and (5.42) modified
by appending the propositional image of B1 , . . . , Bn to their bodies.
As an example, consider the program
letter(a).
letter(b). (5.43)
{p(X,1..2)} = 1 :- letter(X).
is one of its stable models. The propositional image of the program consists of the rules
letter(a),
letter(b),
(p(v, 1) ∨ ¬p(v, 1)) ∧ (p(v, 2) ∨ ¬p(v, 2)) ← letter(v), (5.45)
⊥ ← p(v, 1) ∧ p(v, 2) ∧ letter(v),
⊥ ← ¬p(v, 1) ∧ ¬p(v, 2) ∧ letter(v)
for all v in S ∪ Z. One way to proceed is to find the reduct of (5.45) relative to interpreta-
tion (5.44). Alternatively, we can use here Theorem on Constraints: an interpretation is a
stable model of program (5.45) if and only if it is a stable model of the first three lines of
the program and does not satisfy the bodies of the constraints in the last two lines. The use
of Theorem on Constraints makes the calculation a little easier, because it does not require
computing the reducts of the constraints. The reduct of the first three lines of (5.45) is
letter(a),
letter(b),
(p(a, 1) ∨ >) ∧ (p(a, 2) ∨ ⊥) ← letter(a),
(p(b, 1) ∨ ⊥) ∧ (p(b, 2) ∨ >) ← letter(b),
(p(v, 1) ∨ >) ∧ (p(v, 2) ∨ >) ← letter(v) (v ∈ S ∪ Z \ {a, b}),
98 CHAPTER 5. PROGRAMS WITH NEGATION
{p(c,1)}.
Definition. About sets Π1 , Π2 of propositional rules we say that they are strongly equiva-
lent to each other if, for every propositional program Π, the program Π ∪ Π1 has the same
stable models as Π ∪ Π2 .
From this definition we see that replacing any group of rules within a propositional
program by a strongly equivalent group of rules does not affect the set of stable models
of the program. For example, in Section 5.4 we claimed that the set of stable models of a
propositional program does not change if we break a rule with a conjunction in the head
into several rules. That claim can be expressed by saying that a rule of the form
F1 ∧ · · · ∧ Fn ← G (5.46)
F1 ← G, . . . , Gn ← G. (5.47)
The observation, in the same section, that the law of double negation p ← ¬¬p has a stable
model that is not a stable model of p ← p shows that these two propositional rules are not
strongly equivalent.
In the last example we do not even need to combine Π1 and Π2 with any additional rules
to see that they are not strongly equivalent. In other words, the empty set Π can serve in
this case as a counterexample. Similarly, we can see that the three equivalent rules
are not strongly equivalent to each other by observing that these rules have different stable
models if we think of each of them as a one-rule program. (The only stable model of the
5.8. STRONG EQUIVALENCE 99
first rule is {p}; the only stable model of the second is {q}; the third has two stable models.)
On the other hand, the one-rule programs q ← p and s ← r are not strongly equivalent,
even though they have the same stable model ∅. To see why, combine each of them with
the atomic formula p. The stable model of the former will turn into {p, q}; the stable model
of the latter into {p}.
The last of rules (5.48) has the same stable models as the combination of the first two
rules, but it is not strongly equivalent to that combination. Indeed, adding the rules
p ← q,
q←p
to the rule p ∨ q gives a program with the stable model {p, q}, but adding the same rules to
p ← ¬q, q ← ¬p gives a program without stable models (Exercise 5.8 on page 85).
Exercise 5.24. Prove that ¬¬p is not strongly equivalent to p.
Exercise 5.26. Prove that if two sets of positive propositional rules are equivalent to
each other then they are strongly equivalent.
Let us check now that ¬¬¬F is strongly equivalent to ¬F . Consider any interpretation I.
The reduct of each of the two formulas relative to an interpretation I is ⊥ if I satisfies F ,
and > otherwise. In either case, both formulas have the same reduct.
A similar calculation shows that G ← ¬¬¬F is strongly equivalent to G ← ¬F . More
generally, removing two of three successive negations anywhere within a propositional rule
is a strongly equivalent transformation. This is why allowing more than two negations in a
row within a clingo rule would be pointless.
In Section 2.7 we claimed that replacing the clingo constraint
by the rule
Y1 = Y2 :- f(X,Y1), f(X,Y2).
does not affect the stable models of a program. More generally, replacing a constraint of
the form
:- . . . , t1 != t2 . (5.51)
by
t1 = t2 :- . . . . (5.52)
within any clingo program does not affect its stable models. To see why, note that the
propositional image of a ground rule of form (5.51) has the form
⊥←F ∧⊥
⊥←F ∧>
>←F
or
⊥←F
depending on the same condition. In either case, the propositional images are strongly
equivalent to each other.
Exercise 5.27. Replacing a rule of the form
. . . :- t1 != t2 . (5.53)
by
. . . , t1 = t2 . (5.54)
5.8. STRONG EQUIVALENCE 101
within any clingo program does not affect its stable models. True or false?
In Section 5.4 we observed that the rule p ← ¬¬p has the same stable models as p ∨ ¬p.
In fact, these two rules are strongly equivalent to each other. More generally, any rule of
the form F ← ¬¬F is strongly equivalent to F ∨ ¬F . Indeed, if the reduct of the former
relative to some interpretation is F 0 ← > then the reduct of the latter relative to the same
interpretation is F 0 ∨ ⊥; if the reduct of the former is F 0 ← ⊥ then the reduct of the latter
is F 0 ∨ >. Either way, the two reducts are equivalent to each other.
Exercise 5.28. Any rule of the form
F ← ¬¬F ∧ G (5.55)
is strongly equivalent to
F ∨ ¬F ← G. (5.56)
True or false?
In Section 5.4 we claimed that all simplification steps listed in Table 4.1 preserve the
stable models of a program. For one of these steps, the validity of this claim is more difficult
to establish than for the others: it is not immediately clear that any constraint ⊥ ← F is
strongly equivalent to ¬F . This assertion is, however, a special case of the general theorem
stated below.
A propositional rule is negative if every occurrence of every atomic formula in its head is
in the scope of negation. For example, all constraints are negative—the head of a constraint
does not contain atomic formulas. If the head of a rule has the form ¬F or ¬F ∨ ¬G then
the rule is negative.
Theorem on Negative Rules. If two sets of negative propositional rules are equivalent
to each other then they are strongly equivalent.
The fact that ⊥ ← F is strongly equivalent to ¬F immediately follows, because these
formulas are equivalent. Theorem on Negative Rules shows also that every negative rule is
strongly equivalent to a constraint, because F ← G is equivalent to ⊥ ← ¬F ∧ G.
A propositional rule is strongly tautological if the set of stable models of a program
never changes when this rule is removed. In other words, a rule is strongly tautological rule
if it is strongly equivalent to the empty program.
We can assert that a propositional rule is strongly tautological if we can show that all its
reducts are tautologies. For instance, any rule of the form F ← G∧⊥ is strongly tautological,
because its reducts have the form F 0 ← G0 ∧ ⊥ and consequently are tautological.
If a rule is a positive tautology or a negative tautology then it is strongly tautological.
This fact follows from the assertion of Exercise 5.26 and from Theorem on Negative Rules.
Exercise 5.29. For each of the given expressions, determine whether every propositional
rule of this form is strongly tautological.
(a) F ∨ ¬F ,
(b) ¬F ∨ ¬¬F ,
102 CHAPTER 5. PROGRAMS WITH NEGATION
(c) ⊥ ← F ∧ ¬F ,
(d) F ← F ∧ G,
(e) F ∨ G ← F .
(β) for every atomic formula p, the set of rules of the program with the head p is finite.
This additional condition is trivially satisfied if the program has finitely many rules. But
there are also infinite programs with property (β). For instance, the propositional image of
the clingo rule
q(X) :- p(X).
consists of infinitely many propositional rules
but every atom q(v) is the head of only one of these rules. On the other hand, condition (β)
is violated for the propositional image of the rule
and every atom of the form q(v) is the head of infinitely many of them.
Definition. Let Π be a propositional program Π satisfying conditions (α) and (β). For
every atomic formula p from the vocabulary of Π, by Bp we denote
• the disjunction of the bodies of all rules of Π with the head p, otherwise.
(Condition (β) guarantees that this disjunction is finite.) The completion of Π is the set of
formulas
p ↔ Bp (5.59)
for all atomic formulas p.
5.9. PROGRAM COMPLETION 103
Consider, for instance, program (5.1)–(5.4), and assume that the vocabulary (the set of
all atomic formulas) is {p, q, r, s}. The completion of the program consists of the formulas
p ↔ >,
q ↔ >,
(5.60)
r ↔ p ∧ ¬s,
s ↔ q.
If the vocabulary includes any atomic formulas other than p, q, r, s, then the completion
will include also the formulas
x↔⊥
for every such atomic formula x. (Recall that the disjunction of the empty set set is ⊥.)
In the examples and exercises in the rest of this section we assume that the vocabulary
includes only the atomic formulas that occur in the given program.
The completion of the program from Exercise 5.2 (page 82) is
p ↔ ¬q,
q ↔ ¬r, (5.61)
r ↔ ⊥.
p ↔ ¬q,
q ↔ ¬p, (5.62)
r ↔ p ∨ q.
The intuition behind the concept of completion is that the bodies of rules with the
head p can be viewed as sufficient conditions for the validity of p, and formula (5.59) says
that, collectively, these sufficient conditions are also necessary. For instance, the last two
rules of the program from Exercise 5.7 tell us that p is a sufficient condition for r, and so
is q; the last of formulas (5.62) says that r is true if and only if at least one of these sufficient
conditions holds. It says, in other words, that the disjunction of these sufficient conditions
is necessary and sufficient.
In many cases, the set of stable models of a propositional program is exactly the same
as the set of all models of its completion. As an example, let us find all models of the
completion (5.60) of program (5.1)–(5.4). The completion can be easily simplified, because
the first two formulas in (5.60) allow us to replace p and q in the last two formulas by >:
p ↔ >,
q ↔ >,
r ↔ > ∧ ¬s,
s ↔ >.
Then the last line allows us to replace s in the third line by >:
r ↔ > ∧ ¬>.
104 CHAPTER 5. PROGRAMS WITH NEGATION
Exercise 5.31. (a) Form the completion of program (5.1)–(5.3) on page 81. (b) Check
that the stable model of that program is the only stable model of its completion.
p ↔ ¬q,
q ↔ ¬¬q,
r ↔ ¬q ∨ q.
p ↔ ¬q,
r ↔ >.
It follows that (5.62) has two models, corresponding to two ways to assign a truth value
to q: {p, r} (q is false) and {q, r} (q is true). As in the other examples, the set of all models
of the program’s completion coincides with the set of stable models.
There are cases, however, when these sets are different from each other. The program
p ← q,
(5.63)
q←p
is positive definite, and its only stable model is the minimal model ∅. But the completion
of this program
p ↔ q,
q↔p
has two models, ∅ and {p, q}.
A condition that eliminates cases when completion and stable models do not match is
discussed in the next section.
of q that is not in the scope of negation. In program (5.1)–(5.4), for example, p and q do
not depend on any atoms; r depends on p but not on s; s depends on q.
The statement of the theorem below refers to the following additional condition on
propositional programs:
(γ) it is possible to assign a nonnegative integer, called the rank, to every atomic formula
occurring in the program, so that the rank of each atomic formula is greater than the
ranks of the atomic formulas that it depends on.
For instance, program (5.1)–(5.4) satisfies not only conditions (α) and (β), but also condi-
tion (γ): we can assign rank 0 to p and q, and rank 1 to r and s.
On the other hand, condition (γ) does not hold for any program containing rules (5.63):
in application to such a program, this condition requires that the rank of p be both greater
than and less than the rank of q. Another example when condition (γ) is not satisfied
is given by the propositional image of the second rule in the recursive definition (2.8) of
ancestor/2:
anc(v1 , v3 ) ← anc(v1 , v2 ) ∧ anc(v2 , v3 ) (v1 , v2 , v3 ∈ S ∪ Z).
For a rule of this form with v1 = v2 = v3 , condition (γ) requires that the rank of anc(v1 , v1 )
be greater than itself.
Exercise 5.33. Determine whether program (4.2)–(4.5) on page 66 satisfies condition (γ).
Exercise 5.36. Use Theorem on Completion to confirm your answer to Exercise 5.8
(page 85).
Theorem on Completion is not limited to finite programs. Consider, for instance, two
infinite definite programs:
p1 ← p0 ,
p2 ← p1 , (5.64)
···
and
p0 ← p1 ,
p1 ← p2 , (5.65)
··· .
Each of them has one stable model—the minimal model ∅. The former satisfies conditions
(α)–(γ). (To verify (γ), assign rank n to pn .) Its completion consists of the formulas
p0 ↔ ⊥,
p1 ↔ p0 ,
p2 ↔ p1 ,
··· ,
and ∅ is the only model of the completion, in accordance with the theorem. Program (5.65),
on the other hand, does not satisfy condition (γ). Indeed, in application to that program
condition (γ) requires that the ranks of the atomic formulas p0 , p1 , . . . form a decreasing
infinite sequence of nonnegative integers, which is impossible. The completion of this pro-
gram
p0 ↔ p1 ,
p1 ↔ p2 ,
···
has two models: ∅, which is stable, and {p0 , p1 , . . . }, which is not.
In Section 5.6 we used the definition of a stable model in terms of reducts to verify
that interpretation (5.25) is a stable model of program (5.26). The problem of calculating
the stable models of that program can be approached also on the basis of Theorem on
Completion. The completion of the propositional image (5.27) of the program is
p(a) ↔ >,
p(v) ↔ ⊥ for all v other than a,
q(a) ↔ >,
q(v) ↔ ⊥ for all v other than a,
r(v) ↔ p(v) ∧ ¬q(v) for all v.
5.10. THEOREM ON COMPLETION 107
Exercise 5.38. Do the same for the program from Exercise 5.15.
Exercise 5.39. Use Theorem on Completion to find all stable models of program (2.9), (2.10)
on page 23.
Theorem on Completion can help us find stable models of a program that does not
satisfy condition (α) if we can find a strongly equivalent program that does. For instance,
we can find the stable model of the program
p ∧ q,
r ← ¬p
by breaking the first rule into p, q and then calculating the completion. The stable models
of the program
p ∨ ¬p,
q←p
can be found using Theorem on Completion if we rewrite the first rule as
p ← ¬¬p.
Exercise 5.40. (a) Use Theorem on Completion to find all stable models of the program
from Exercise 5.17 on page 93. (b) Check whether your answer is in agreement with the
output of clingo.
Exercise 5.41. Do the same for the program from Exercise 5.18.
Exercise 5.42. Do the same for the program from Exercise 5.19.
Sometimes a propositional program can be represented as the union of a program Π
satisfying conditions (α)–(γ) and a set Σ of constraints. The stable models of such a
program can be characterized as the models of the union of the completion of Π with Σ.
This fact follows from Theorem on Completion and Theorem on Constraints.
Exercise 5.43. (a) Use Theorem on Completion to find all stable models of the program
108 CHAPTER 5. PROGRAMS WITH NEGATION
{p(1..2,1..2)} = 2.
:- p(1,1).
:- p(2,2).
(b) Check whether your answer is in agreement with the output of clingo.
Another possibility is to allow propositional rules to contain infinitely long conjunctions and
disjunctions, for instance
q ← p1 ∧ p2 ∧ . . . and q ← p1 ∨ p2 ∨ . . . .
In some cases, an infinitary propositional formula has the same meaning as a set of finite
formulas. For instance, the second of formulas (5.66) is equivalent to the infinite set of finite
implications
q ← p1 , q ← p2 , . . . .
But the first of formulas (5.66) is not equivalent to any set of finite propositional formulas.
Infinitary formulas can help us extend the definition of the propositional image to choice
rules with local variables and cardinality bounds, such as
In the absence of cardinality bounds, local variables in a choice rule are not problematic.
For instance, the rule
{p(X) : q(X)}.
5.11. LOCAL VARIABLES AND INFINITARY FORMULAS 109
{p(X)} :- q(X).
in which the variable X is global, and we can define its propositional image as the set of
rules
p(v) ∨ ¬p(v) ← q(v)
for all v in S ∪ Z. But the propositional image of rule (5.67), with its lower bound 1,
should include also a constraint eliminating the stable models that do not include any of
the atoms p(v) for the values of v for which q(v) is included. The constraint that we need
should eliminate, in other words, the sets p/1 that are disjoint from q/1. That can be
expressed by the infinitary propositional rule
^
⊥← ¬(p(v) ∧ q(v)),
v∈S∪Z
for all v1 in S ∪ Z. In this more general setting, the assertion of Theorem on Completion can
be strengthened by dropping condition (β). In other words, for any propositional program Π
satisfying condition (α), every stable model of Π is a model of the completion of Π; if Π
satisfies also condition (γ) then the converse holds as well.
To show how infinitary completion can help us reason about stable models, assume that
we are given a finite directed acyclic graph G, such as the one shown in Figure 5.1, and
a b
consider the following game. We place a token on one of the vertices. Then two players
take turns moving the token to another vertex along one of the edges of the graph. When
110 CHAPTER 5. PROGRAMS WITH NEGATION
the player who has to move finds the token on a vertex without outgoing edges, that player
has lost. Whether the player who starts can win is determined by the vertex where the
token was placed initially. For instance, in the graph shown in Figure 5.1, vertices b and c
are winning (move the token to d), and vertices a and d are not.
The set winning/1 of winning vertices can be described by the rule
winning(X) :- edge(X,Y), not winning(Y). (5.68)
(a vertex is winning if there is an edge leading from it to a vertex that is not winning). The
set of winning vertices can be determined by running clingo on the program ΠG obtained
by adding this rule to the definition of the predicate edge/2 for graph G.
The propositional image of ΠG satisfies condition (α), but not (β): among the rules
winning(v1 ) ← edge(v1 , v2 ) ∧ ¬winning(v2 ) (5.69)
in the propositional image of (5.68) there are infinitely many rules with the same head
winning(v1 ). Condition (γ) is satisfied, however: we can assign rank 0 to all atoms edge(v1 , v2 )
and rank 1 to all atoms winning(v). (Note that in rule (5.69), winning(v1 ) does not de-
pend on winning(v2 ), because the latter is in the scope of negation.) Consequently stable
models of program ΠG can be characterized as models of the infinitary completion of its
propositional image, which consists of the formulas
edge(v1 , v2 ) ↔ > for every edge (v1 , v2 ),
edge(v1 , v2 ) ↔ W
⊥ for every other pair (v1 , v2 ),
winning(v1 ) ↔ v2 ∈S∪Z (edge(v1 , v2 ) ∧ ¬winning(v2 )) for all v1 .
In the presence of the formulas in the first two lines, the infinite disjunction in the
last line can be equivalently replaced by the disjunction of the formulas ¬winning(v2 ) over
all v2 such that (v1 , v2 ) is an edge of the graph, and that disjunction is finite. After that, a
sequence of simplification steps will lead us to the unique stable models of ΠG . In the case
of the graph in Figure 5.1, for instance, the last line of the completion is equivalent to
winning(a) ↔ ¬winning(b),
winning(b) ↔ ¬winning(c) ∨ ¬winning(d),
winning(c) ↔ ¬winning(d),
winning(v) ↔ ⊥ for all v other than a, b, c.
This set of formulas is equivalent to
winning(a) ↔ ¬winning(b),
winning(b) ↔ >,
winning(c) ↔ >,
winning(v) ↔ ⊥ for all v other than a, b, c,
and consequently to
winning(b) ↔ >,
winning(c) ↔ >,
winning(v) ↔ ⊥ for all v other than b, c.
5.12. BIBLIOGRAPHICAL AND HISTORICAL REMARKS 111
{edge(a, b), edge(b, c), edge(b, d), edge(c, d), winning(b), winning(c)}.
r ← p ∧ ¬Ls.
From this perspective, negation as failure in logic programming has the same meaning as
the combination ¬L in autoepistemic logic [47].
Stable models can be characterized in many different ways [79]. They were first defined
for rules of the form
A0 ← A1 ∧ · · · ∧ Am ∧ ¬Am+1 ∧ · · · ∧ ¬An ,
where each Ai is an atomic formula [39, 50], then for rules with a disjunction in the head [52],
and then for rules in which conjunction, disjunction, and negation can be nested arbitrarily
in heads and bodies [82], as in propositional rules in the sense of Section 4.1. The original
definition of a stable model for programs with choice rules [99] treated choice as an inde-
pendent construct; a few years later [37] it became clear that {p} can be viewed also as
shorthand for
p , not p.
112 CHAPTER 5. PROGRAMS WITH NEGATION
Equivalence relations between propositional formulas that are stronger than classical
equivalence and do not treat, for instance, dropping a double negation as an equivalent
transformation have been studied in logic for a long time. This work was initially related
to the intuitionist philosophy of mathematics. The idea that mathematics is the creation
of the mind has led intuitionists to the view that the law of excluded middle and “the
principle that for every system the correctness of a property follows from the impossibility
of the impossibility of the property” may be invalid in application to infinite systems [18].
The logical consequences of this view were clarified by the invention of intuitionistic propo-
sitional logic—a formal system that does not sanction the law of excluded middle and other
tautologies that intuitionists find objectionable [66].
The claim that the law of excluded middle is not intuitionstically provable was justified
using an auxiliary logical system, which is often called (for reasons that we do not go into
in this book) “the logic of here-and-there” and denoted by HT. The logic of here-and-
there is based on three truth values, instead of the two classical values false, true, and it
is intermediate in strength between intuitionistic logic and classical. Since HT is closely
related to the idea of strong equivalence in the theory of logic programming, we discuss it
here in some detail.
The three truth values can be represented by numbers 0, 12 , and 1; the new truth value 12
is reserved, informally speaking, for propositions “that cannot be false but whose correctness
is not proved” [66]. Once one of these truth values is assigned to every atomic formula, the
values of other formulas are calculated according to the following rules. The value of ¬F is
1 if the value of F is 0, and it is 0 otherwise. The values of F ∧G and F ∨G are, respectively,
the minimum and maximum of the values of F and G. Finally, if the value of F is x, and
the value of G is y, then
the value of F ← G is 1 if x ≥ y, and x otherwise.
It turns out that two propositional rules F , G are strongly equivalent if and only if they
are equivalent in the logic of here-and-there [81]; in other words, if and only if the truth
value of F for any assignment of truth values 0, 21 , 1 to atomic formulas is the same as
the truth value of G for the same assignment of truth values. Furthermore, a propositional
rule is strongly tautological if and only if its truth value is 1 for every assignment of truth
values 0, 12 , 1 to atomic formulas. For instance, the rule p ∨ ¬p is not strongly tautological;
accordingly, it gets the truth value 21 , different from 1, if the value of p is 12 . The rule p ← p,
on the other hand, is strongly tautological; its truth value is 1 for each of the three ways to
choose a truth value for p.
The proof of these theorems uses the fact that stable models can be characterized in
terms of equilibrium logic—a nonmonotonic logic based on the logic of here-and-there [101].
Program completion was proposed as an explanation of the meaning of negation as
failure in 1978 [27], long before the invention of stable models, and generalized in 1984 [86].
The definitions in these papers apply to rules with variables directly and do not require
that specific values be substituted for variables, as the version in this book. In the style of
the original definition, the completion of program (5.57) would be written as
∀X(q(X) ↔ ∃Y p(X, Y )).
5.12. BIBLIOGRAPHICAL AND HISTORICAL REMARKS 113
The first result on the relationship between completion and stable models was published
in 1994 [35] and later extended to other classes of programs [32, 33, 64]. These papers define
properties of programs similar to our condition (γ), and programs with these properties are
usually referred to as “tight.” The definitions of tightness in these papers are not expressed
in terms of assigning ranks to atomic formulas; they require instead that it should be
impossible to find an infinite sequence of atomic formulas such that every member of the
sequence depends on its successor. Tightness conditions of this kind are more general than
condition (γ). Consider, for instance, the infinite program
q ← p0 , p 1 ← p0 ,
q ← p1 , p 2 ← p1 ,
q ← p2 , p 3 ← p2 ,
··· .
In this case, there is no infinite sequence of atomic formulas such that every member of the
sequence depends on its successor. But finite sequences with this property that start with q
can be arbitrarily long:
q, pn , pn−1 , . . . , p1 , p0 .
It follows that this program does not satisfy condition (γ). Programs like this will be covered
if we modify condition (γ) by allowing ranks to be infinite ordinals ω, ω + 1, . . . .
If a program is not tight then its stable models can be described as the models of its
completion that satisfy additional “loop formulas” [84]. This fact has been used in the
design of answer set solvers [76, 84].
In some cases, stable models of a program can be calculated by “splitting”—dividing
the rules of the program into two parts, calculating the stable models of one part, and then
extending each of them to find stable models of the entire program [83]. Splitting can be
applied, for instance, to the program from Exercise 5.7 (page 85). The part consisting of
the first two rules of the program has two stable models, {p} and {q}. The last two rules
turn the first of them into {p, r}, and the second into {q, r}.
Infinitary formulas have been studied in logic since the 1950s [68, 111], but allowing
infinite rules in a logic program is a more recent idea [115]. Infinite conjunctions and
disjunctions have been added not only to classical logic, but also to intuitionistic logic [96]
and to the logic of here-and-there [63].
The encoding of two-person games in Section 5.11 is similar to encodings written earlier
for Prolog [117].
114 CHAPTER 5. PROGRAMS WITH NEGATION
Chapter 6
The programming constructs described below significantly extend the expressive possibilities
of the language used so far. The first three sections are about aggregates—functions that
apply to sets. Then we show how clingo can be used to solve combinatorial optimization
problems and discuss clingo programs with symbolic functions and classical negation.
6.1 Counting
The aggregate #count calculates the number of elements of a set. For example, the expres-
sion
#count{X,Y : edge(X,Y)}
represents the number of elements of the set edge/2. Expressions like this are used in the
bodies of rules as one side of a comparison, with a term on the other side:
The stable model of the program obtained by adding this rule to the definition (3.2) of a
graph contains the atom number_of_edges(9): the graph has 9 edges.
The part of an aggregate expression to the right of the colon may be a list of several
atoms, negated atoms, and comparisons. For example, the expression
#count{X,Y : edge(X,Y), X != a}
115
116 CHAPTER 6. MORE ABOUT THE LANGUAGE OF CLINGO
The part of an aggregate expression to the left of the colon may include not only vari-
ables, but also more complex terms. For example, if n is a placeholder for a positive integer
then the expression
Note that a comparison cannot contain aggregate expressions on both sides. When
we want to compare the values of two aggregate expressions, this can be accomplished by
comparing each of them with the value of a variable. For instance, call a vertex balanced if
its indegree equals its outdegree; the set of balanced vertices can be defined by the rule
{in(1..n)} = m.
(found, for example, in Line 10 of Listing 3.13, page 48) can be replaced by the combination
of the rule
{in(1..n)}.
with a constraint. What constraint is that?
Exercise 6.2. We would like to write a clingo program that calculates the number of
classes taught today on each floor of a classroom building. What rule would you place in
Line 6 of Listing 6.1?
Exercise 6.3. Rule (1.1) defines a large country as a country inhabited by more people
than the United Kingdom. How will you modify that rule if “large country” is understood
as a country with a population that places it
We will see now how the #count aggregate is used in a clingo program that solves
skyscraper puzzles. In such a puzzle, the goal is to fill an n × n grid with numbers from 1
to n. No number may be repeated in any row or column. The numbers represent the heights
of skyscrapers, and they should be chosen according to clues—numbers placed around the
perimeter of the grid. (See Figure 6.1 for an example.) Each clue tells us how many
buildings can be seen from that point, assuming that higher skyscrapers block the view of
lower skyscrapers located behind them.
In Listing 6.2, the position of each clue is represented by the row and column where
the clue is located. The clues to the left and above the grid are in row 0 and column 0,
respectively; the clues to the right and below the grid are in row n + 1 and column n + 1.
For example, the set clue/3 representing the puzzle in Figure 6.1 is defined by the rule
The constraint in Line 27 of the program says that the number of skyscrapers blocked from
1
4 1 2 3 4
2 3 1 4 2
4 3 2 1
2 2 4 1 3 2
3 2
view cannot be different from n − N , where N is the value of the corresponding clue.
6.2 Summation
The aggregate #sum calculates the sum of a set of integers. For example, the set q/1 defined
by the rule
q(N) :- N = #sum{X*X : p(X)}.
is a singleton, and its only element is the sum of the squares of all integers in the set p/1.
The program consisting of that rule and the rule
p(a; 1; 2).
then the value of (6.2) is 5, and the value of (6.3) is 3. Since the population sizes of all
countries in Table 1.1 are different from each other, expression (6.3) has in this case the
same value as (6.2).
Exercise 6.4. What is the stable model of the program
in your opinion?
Exercise 6.6. A magic square of size n is an n×n square grid filled with distinct integers
in the range 1, . . . , n2 so that the sum of numbers in each row, each column, and each of
the two diagonals equals the same “magic constant.” It is clear that the value of the magic
constant is determined by the size of the square: it is (1 + 2 + · · · + n2 )/n, which equals
(n + n3 )/2. We would like to write a clingo program that generates all magic squares
of a given size. The rules in Lines 5 and 9 of Listing 6.3 are the same as in Listing 3.21
(page 55). What rules would you place in Lines 14, 17, 20, 21?
The next example of using the #sum aggregate is motivated by the problem of determin-
ing the winner when voters rank several options or candidates in order of preference. One
possibility is to calculate the number of points assigned to each candidate by each voter, as
follows: the candidate ranked last gets zero points; next to last gets one point, and so on.
Once all votes have been counted, the candidate with the most points is the winner. There
are several winners in case of a tie.
6.3. MAXIMUM AND MINIMUM 121
For example, assume that Andy, Bob and Charlie run for the same office; the ranking
C > B > A is chosen by 400 voters, B > C > A by 200 voters, and A > B > C by 300
voters. Then
Andy gets 300 × 2 = 600 points,
Bob gets 400 × 1 + 200 × 2 + 300 × 1 = 1100 points,
Charlie gets 400 × 2 + 200 × 1 = 1000 points;
Bob is the winner.
The program in Listing 6.4 calculates the winner in accordance with this procedure.
The example above can be represented by the following input:
#const m=3.
votecount(1,400; 2,200; 3,300).
p(1,1,3; 1,2,2; 1,3,1;
2,1,2; 2,2,3; 2,3,1;
3,1,1; 3,2,2; 3,3,3).
#sum{S,R : posScore(R,C,S)}
(Line 14 of the program) the number S of points to the left of the colon is followed by the
number R of the ranking that contributed these points. This is essential when a candidate
receives the same number of points from different rankings; without R appended to S in this
expression, the number of points earned by such a candidate would be calculated incorrectly.
This would happen, in fact, in the example above, because Bob gets 400 points from the
voters who chose the ranking C > B > A, and the same number of points from the voters
who chose B > C > A. If we replace S,R in Line 14 by S then clingo will tell us, incorrectly,
that Charlie is the winner.
calculates the distance between sets p/1 and q/1 of integers (that is, the smallest among
the distances from elements of p/1 to elements of q/1).
Recall that the total order chosen by the designers of clingo for evaluating comparisons
is defined not only on numbers, but also on symbolic constants, and that it has the minimal
element #inf and maximal element #sup (Section 2.1). For this reason, expression (6.4) can
be used to choose one among the elements of any set p/1, no matter whether its elements
122 CHAPTER 6. MORE ABOUT THE LANGUAGE OF CLINGO
are numbers or symbolic constants. In application to the empty set, #max returns #inf, and
#min returns #sup. This is similar to the convention mentioned in Section 4.2: the sum of
the empty set of numbers is 0, and the product is 1.
Exercise 6.7. Adding the constraint
:- not p(_).
to a clingo program eliminates the stable models in which the set p/1 is empty (Sec-
tion 2.8). Find constraints with the same property that use, instead of an anonymous
variable, (a) the aggregate #count, (b) the aggregate #max, (c) the aggregate #min.
The encoding of Hamiltonian cycles in Listing 3.19 (page 53) expects an input that
specifies, in addition to the predicates vertex/1 and edge/2, one of the vertices v0 of the
graph. The symbol v0 is used in the first rule
reachable(X) :- in(v0,X).
6.4 Optimization
When a logic program has several stable models, we may be interested in finding its stable
model that is good, or even the best possible, according to some measure of quality. A
measure of quality can be specified by an aggregate expression. For instance, the expression
measures the quality of a stable model by the sum of the integers in the set p/1; the model
in which this sum is the largest or the smallest would be considered the best.
The directives #maximize and #minimize instruct clingo to improve the first stable
model that it generated using a #sum aggregate expression as the measure of quality, and to
keep looking for better and better stable models until the best model is found. For example,
the directive
#maximize{X : p(X)}
will cause clingo to generate stable models in which the values of aggregate expression (6.6)
are larger and larger. These directives allow us to apply clingo to combinatorial optimiza-
tion problems, where the goal is to find the best among several alternatives.
Consider, for instance, the knapsack problem, where we are given a set of items, each
with a weight and a value, and the goal is to determine which items to include in a collection
so that the total weight does not exceed a given limit and the total value is as large as
possible. This problem is encoded in Listing 6.5. Given this program and the input
Answer: 1
6.4. OPTIMIZATION 125
Optimization: 0
Answer: 2
in(b)
Optimization: -2
Answer: 3
in(b) in(e)
Optimization: -3
Answer: 4
in(b) in(d)
Optimization: -4
. . . . . . . . . .
Answer: 11
in(b) in(c) in(d) in(e)
Optimization: -15
OPTIMUM FOUND
In every answer, the number after the word Optimization shows the total weight of the
items in the set in/1. (The minus sign is prepended by clingo whenever the #maximize
directive is used, rather than #minimize.)
Exercise 6.9. We would like to restrict not only the total weight of the selected items, but
also their combined volume. The set volume/2 consists of the pairs (i, vol ) such that vol is
the volume of item i; maxvolume is the upper bound on the combined volume. How would
you modify the program in Listing 6.5 to encode this enhancement of the basic knapsack
problem?
#sum{1,C : color(X,C)}
will be small integers, between 1 and the chromatic number of the graph. This modification
will also cause clingo to terminate faster, because of its symmetry breaking effect.
Exercise 6.11. We would like to solve the optimization version of the set packing problem
(Section 3.8), which calls for finding the largest possible number of pairwise disjoint members
of a given list of finite sets. What directive would you place in Line 16 of Listing 6.8?
Exercise 6.12. Recall that a clique in a graph is a subset of its vertices such that every
two distinct vertices in it are adjacent (Section 3.9). We would like to write a clingo
program that finds the largest clique in a given graph. What rule would you place in Line 6
of Listing 6.9, and what directive in Line 13, to achieve this goal?
Exercise 6.13. Research papers submitted to a technical conference are reviewed by the
conference program committee. Every paper is read and discussed by a group of committee
members chosen by the chair of the committee, and this group decides if the paper can be
accepted for presentation. To help the chair find a good match between papers and referees,
every committee member submits a bid that classifies all papers that need to be reviewed
into three categories: “yes” (I want to review this paper), “maybe” (I do not mind reviewing
it), and “no” (do not assign it to me). We would like to write a program for clingo that
automates this part of the work of the chair. Using a list of bids, it should assign each
submitted paper for review to a specific number k of committee members so that
6.5. CLASSICAL NEGATION 129
• the workloads of committee members are approximately equal—do not differ by more
than 1;
• the total number of cases when a submission is assigned to a reviewer who placed it
in the “yes” group is as large as possible.
What rules would you place in Lines 7, 11, 17, 22, and 26 of Listing 6.10, and what directive
in Line 31, to achieve this goal?
p(1..2).
-p(3..4).
is
p(1) p(2) -p(3) -p(4)
but the program
p(1..2).
-p(2..3).
{p(1..2)}.
-p(2..3).
{p}.
q :- not p.
r :- -p.
(b)
{p}.
q.
-q :- not p.
Listing 6.12: Integers requiring four squares encoded using classical negation
1 % Numbers from 1 to n that cannot be represented as the sum
2 % of 3 complete squares .
3
4 % input : positive integer n .
5
6 three ( N ) : - N =1.. n , I =0.. n , J =0.. n , K =0.. n , N = I **2+ J **2+ K **2.
7 % achieved : three /1 is the set of numbers from {1 ,... , n } that
8 % can be represented as the sum of 3 squares .
9
10 - three ( N ) : - N =1.. n , not three ( N ).
11 % achieved : - three /1 is the set of numbers from {1 ,... , n } that
12 % can ’ t be represented as the sum of 3 squares .
13
14 # show - three /1.
6.6. SYMBOLIC FUNCTIONS 133
words, this rule represents the closed world assumption for the property three/1 in the
domain {1, . . . , n}. The general form of closed world assumption rules is
where the part of the body denoted by dots describes the domain. The rule in Line 9 of
Listing 6.11 expresses the opposite assumption about the property coprime/1: a number
between 1 and n is coprime with k if there is no evidence that it is not.
Classical negation is useful for distinguishing between what is known to be false and
what is unknown. For example, the facts
candidate(a; b; c; d; e).
elected(a; b).
-elected(c; d).
describe the status of five candidates in an election: a and b have won, c and d have lost,
and the status of e is still undecided.
Exercise 6.16. What stable models do you think will be produced by clingo for the
following programs?
(a)
p :- f(1,2) = 7.
134 CHAPTER 6. MORE ABOUT THE LANGUAGE OF CLINGO
v(0,3) v(3,3)
v(0,0) v(3,0)
(b)
p(f(1..2,g(1..2))).
q(X):- p(f(_,X)).
Symbolic functions can be used, for instance, to describe points in a coordinate plane.
The graph shown in Figure 6.2 can be represented by the rules
vertex(v(0..3,0..3)).
edge(v(R,C),v(R,C+1)) :- R = 0..3, C = 0..2.
edge(v(R,C),v(R+1,C)) :- R = 0..2, C = 0..3.
If we give these rules as input to the program in Listing 6.7 then clingo will determine
that the chromatic number of the graph is 2.
We will see other programs that use symbolic functions in Chapter 7.
Informally, the meaning of logic programs with two kinds of negation can be described
by three principles: satisfy the rules of the program; do not believe in contradictions; believe
in nothing you are not forced to believe [49]. The first and the last of these principles corre-
spond to clauses (i) and (ii) of the characterization of stable models on page 86; not believing
in contradictions corresponds to eliminating the stable models containing complementary
pairs.
The term “closed world assumption” was originally introduced in the context of deduc-
tive databases [106].
Symbolic functions are inherited by answer set solvers from Prolog. They were covered
by the original definition of a stable model [50].
Several useful constructs available in clingo, including conditional literals, external
functions, and multi-shot solving, go beyond the scope of this book. They are described in
Potassco User Guide, which can be downloaded from the website of the Potassco project,
https://potassco.org. Furthermore, we do not discuss here rules with ordered disjunc-
tion [16], ASP with sorts [4], ASP with consistency-restoring rules [7, 5], constraint ASP
[8, 9, 46, 67], ASP with preferences [17], and probabilistic ASP [23].
One other interesting extension of answer set programming is motivated by the fact
that ASP definitions of functions are somewhat cumbersome. Compare, for instance, the
definition of the predicate fac/2 in lines 5 and 6 of Listing 2.6 (page 26) with the definition
of factorial in Haskell (page 10). This observation has led several researchers to the idea of
merging ASP with functional programming [6, 11, 19].
136 CHAPTER 6. MORE ABOUT THE LANGUAGE OF CLINGO
Chapter 7
Dynamic Systems
Answer set programming has important applications to the study of dynamic systems—
systems whose states can be changed by performing actions. It can be used, for instance,
to predict and to plan. In a prediction problem, the task is to determine how the current
state of a dynamic system will change after executing a given sequence of actions. In a
planning problem, the task is to find a sequence of actions that leads a dynamic system
from a given initial state to a goal state.
In this chapter we describe the methodology of representing dynamic systems by logic
programs and give examples of the use of clingo for prediction and planning.
a b
b a a b
--- --- -----
S1 S2 S3
137
138 CHAPTER 7. DYNAMIC SYSTEMS
a b a c b c
b a c a c b
c c b b a a
--- --- --- --- --- ---
S1 S2 S3 S4 S5 S6
a b a c b c
b c a c c b a b c a b a a b c
----- ----- ----- ----- ----- ----- -------
S7 S8 S9 S10 S11 S12 S13
them from above.) For example, the only actions executable in state S7 (Figure 7.2) are
block b cannot be moved. Action move(c, b) is not executable in that state because there is
another block on top of b. Action move(c, table) is not executable because c is already on
the table.
Here are examples of prediction and planning problems in the blocks world with the
blocks a, b, c.
(i) Assume that the blocks world is initially in state S7 . What is going to be the effect of
executing the action move(a, c) and then move(b, a)? The answer to this prediction
question is that the blocks world will be in state S2 .
(ii) For the same initial state, what about executing the action move(a, c) and then
move(b, c)? Answer: this sequence of actions is not executable.
(iii) For the same initial state, if we would like b to be on top of c, what sequence of actions
would accomplish this? One possible plan is
Exercise 7.1. (a) In the initial state of the blocks world with n blocks, all blocks are on
the table. What is the number of actions that can be performed in this state? (b) In the
7.2. TRANSITION DIAGRAMS 139
move(a,b) move(b,a)
←−−−−−−−−− −−−−−−−−−→
S1 −−−−−−−−−→ S3 ←−−−−−−−−− S2
move(a,table) move(b,table)
initial state of the blocks world, blocks form n towers, and every tower contains more than
one block. What is the number of actions that can be performed? (c) Blocks are arranged
in n towers, and m out of them contain more than one block. What is the number of actions
that can be performed?
Exercise 7.2. Give an example of a planning problem in the blocks world with 3 blocks
that cannot be solved in fewer than 4 steps.
Exercise 7.3. In the transition diagram of the blocks world with 3 blocks, (a) what is
the total number of edges? (b) how many of them lead to S7 ? (c) how many of them are
labeled move(a, table)?
A prediction problem can be visualized as the problem of finding the end point of the
path in the transition diagram that starts at the given vertex and consists of edges labeled
by the given actions. For instance, the answer to question (i) from Section 7.1 tells us that
the path beginning at vertex S7 with the edges labeled move(a, c) and move(b, a) leads to
vertex S2 . The answer to question (ii) tells us that no path starting at S7 consists of edges
labeled move(a, c), move(b, c).
A planning problem can be thought of as the problem of finding a path in the transition
diagram that leads from the given initial state to the given set of goal states. For instance,
question (iii) from Section 7.1 calls for finding a path from S7 to any of the vertices S1 ,
S5 , S11 .
140 CHAPTER 7. DYNAMIC SYSTEMS
Exercise 7.4. Turkey shoot. Consider the dynamic system consisting of a gun, which
can be loaded or unloaded, and a turkey, which can be alive or dead. This system can be
in 4 states:
There are 2 actions: load, which can be executed whenever the gun is unloaded, and shoot,
which can be executed whenever the gun is loaded. After shooting, the turkey is dead, and
the gun is unloaded. Draw the transition diagram for this dynamic system.
Exercise 7.5. 3-way bulbs. Consider the dynamic system consisting of several 3-way
bulbs controlled by pull-chain switches. A switch can be in 4 positions: off (0), low (1),
medium (2), and high (3). The system can be in 4n states, represented by lists of numbers of
length n, where n is the number of bulbs. The actions are pull (i), “pull the chain controlling
bulb i.” (a) Draw the transition diagram describing this system for n = 1. (b) What is the
total number of edges in the transition diagram for an arbitrary n? (c) Describe the edges
starting at the vertex (0,0,3).
Exercise 7.6. Crossing the river. You are on a river bank, with a boat and several items
that you can take with you to the other bank. The boat, and each of the items, can be in
one of two locations—on the left bank or on the right bank. These locations determine the
state of the system. The items are bulky, so that the boat cannot carry more than one at a
time. The available actions are cross(x), where x is one of the items (cross the river taking x
with you) or the symbol empty. (a) Assume that in state S the boat and all n items are on
the left bank. What is the length of the shortest path in the transition diagram that leads
from S to the state in which the boat and all items are on the right bank? (b) How many
paths of length 2 in the transition diagram start at vertex S?
7.3 Time
To describe sequentially executed actions by a set of atoms, we need to represent time. Time
instants will be denoted by integers between 0 and a nonnegative integer h (“horizon”), and
the execution of an action will be assumed to take one unit of time. For example, we will
think of scenario (i) from Section 7.1 as executing the action move(a, c) between times 0
and 1, and executing move(b, a) between times 1 and 2.
In a clingo program, this scenario can be represented by the directive
The predicate occurs serves for specifying the time when the execution of an action begins.
Note that the symbol move is used here as a symbolic function (see Section 6.6).
States of a dynamic system can be described in terms of parameters called fluents. In
the case of the blocks world, locations of blocks can be used as fluents. For instance, state S7
can be characterized by saying that the location of a is (the top of) b, the location of b is
the table, and the location of c is the table also; symbolically,
The use of fluents to describe the state of a dynamic system is similar to the use of coordi-
nates to describe the position of an object.
To specify the value of a fluent at a given time instant, we use the predicate holds. The
atom holds(C,T) expresses that condition C holds at time T. For instance, the assumption
that the blocks world with 3 blocks is in state S7 at time 0 can be expressed by the facts
holds(loc(a,b),0).
holds(loc(b,table),0). (7.6)
holds(loc(c,table),0).
Exercise 7.8. States of the 3-way bulb domain (Exercise 7.5) with n bulbs can be
described by n fluents with the values 0, . . . , 3. For instance, the condition “bulb I is off”
can be represented by the term brightness(bulb(I), 0). Consider the following scenario: the
system consisting of 3 bulbs is initially in the state (0,0,3), and then the action pull(3) is
executed. How would you describe it by a directive and a set of atoms?
Exercise 7.9. States of the crossing the river domain (Exercise 7.6) can be described by
the locations of the boat and of all the items. The possible values of these fluents are left
and right. Consider the following scenario: there are two items, a and b; initially they are
on the left bank, and the boat is on the right bank; you cross the river to bring both items
to the right bank—first a and then b. How would you describe it by a directive and a set
of atoms?
The requirement that at each time instant, each block must have a unique location can
be expressed by the constraint
Constraints requiring the existence and uniqueness of value of every fluent at every time
instant, as in this example, will be included in all our encodings of dynamic domains.
Exercise 7.10. Write the existence and uniqueness of value constraints for the following
domains:
(a) the turkey shoot domain,
(b) the 3-way bulb domain, using the placeholder n for the number of bulbs,
(c) the crossing the river domain, using the predicate symbol item/1 to represent the set
of items.
Exercise 7.11. Describe the effects of actions in the 3-state bulb domain by one rule.
Program (7.1), (7.3)–(7.8) is close to being an adequate description of scenario (i) from
Section 7.1, but it is not completely satisfactory. In fact, that program has no stable models.
To understand why, consider the program obtained from it by removing constraint (7.7).
That smaller program has one stable model, consisting of the atoms
7.4. EFFECTS OF ACTIONS 143
In this model, blocks b and c are not assigned a location at time 1, and blocks a and c are
not assigned a location at time 2. This fact explains why the program becomes inconsistent
after adding a constraint that requires a unique location for each block.
A satisfactory encoding of scenario (i) would imply that at time 1 both b and c are on
the table, because that is where they were at time 0. It would also imply that at time 2
block a is on top of c, and c is on the table, because that is where they were at time 1.
Program (7.1), (7.3)–(7.8) specifies the location of a block after moving it, but it does not
say that a block “inherits” its location from the previous time instant if it is not moved.
This is why program (7.1), (7.3)–(7.8) is unsatisfactory.
This difficulty, known as the frame problem, is quite general. If the turkey is alive then
it will remain alive after loading the gun; an encoding of the turkey shoot domain will not
be adequate unless it allows us to draw this conclusion. If a bulb is off then it will be off
after pulling the chain controlling another bulb. If an item is on the left bank then it will
be still there after crossing the river with any other item in the boat. Generally, a fluent
can be presumed to have the same value that it had before if there is no evidence to the
contrary. This principle plays an important role in the theory of dynamic systems, and it
is known as “the commonsense law of inertia.”
In the blocks world, inertia can be expressed by the rule
holds(loc(B,L),T+1) :- holds(loc(B,L),T),
not not holds(loc(B,L),T+1), (7.9)
T = 0..h-1.
Exercise 7.12. Express inertia by rules (a) for the turkey shoot domain, (b) for the
3-way bulb domain, (c) for the crossing the river domain.
Inertia can be expressed also by choice rules. For instance, the choice rule
can be used in place of (7.9). This is not surprising in view of the fact that any propositional
rule of the form
F ← ¬¬F ∧ G
is strongly equivalent to
F ∨ ¬F ← G
(Exercise 5.28 on page 101).
Exercise 7.13. Rewrite the inertia rule from Exercise 7.12(b) as a choice rule.
If we add this constraint to program (7.1), (7.3)–(7.9), and after that replace (7.5) by (7.11),
then we will get an adequate representation of scenario (ii): the modified program has no
stable models.
Exercise 7.14. Constraint (7.12) will become unacceptable if we remove the atom
block(B) from its body. Explain why.
Besides the requirement that blocks be stacked one on top of another forming towers,
there are two other reasons why moving a block may be impossible. First, a block cannot
be moved if there is another block on top of it (Section 7.1):
Constraints (7.12)–(7.14) describe all possible reasons why the action of moving a block
onto another block or onto the table can be nonexecutable. Constraints (7.13) and (7.14)
are stated in terms of preconditions—conditions on a state that must be satisfied before
executing the action. According to the former, the block that we want to move should be
clear. According to the latter, the location to which we want to move it should be different
from its current location. Constraint (7.12), on the other hand, restricts the executability of
actions implicitly. It is stated in terms of fluents, and does not even mention actions. But in
combination with rule (7.8), which describes the effect of moving a block, constraint (7.12)
entails that a block cannot be moved to a place that is currently occupied.
The assumption that a block can be placed on top of another block only if the latter
is clear can be thought of as a precondition similar to (7.13) and (7.14), and a constraint
expressing that precondition can be used instead of (7.12).
Exercise 7.15. Write a constraint expressing that precondition.
In Section 7.8 we will say more about the relationship between this precondition and
constraint (7.12).
Exercise 7.16. In the turkey shoot domain, the action shoot can be executed only when
the gun is loaded, and the action load only when it is not. Express these preconditions by
constraints.
Exercise 7.17. In the crossing the river domain, an item can be taken to the other bank
only when it is on the same bank as the boat. Express this precondition by a constraint.
7.6 Prediction
Listings 7.1 and 7.2 reproduce the prediction program presented in Sections 7.4 and 7.5,
slightly modified. The first listing comprises the general rules, which are applicable to
any blocks world prediction problem; the second is the input describing scenario (i) from
Section 7.1. The modification involves introducing the auxiliary predicates init/1 and
final/1. The former allows us to describe the initial state a little more concisely—compare
facts (7.6) with Line 3 of Listing 7.2. The latter is used in the show directive at the end of
Listing 7.1.
Note that there are no “achieved” comments in these programs. Comments of that kind
are not particularly useful in encodings of dynamic domains.
Exercise 7.18. (a) Write a prediction program for the turkey shoot domain. (b) Initially,
the gun is unloaded and the turkey is alive. Then we load the gun, shoot the turkey, and
load the gun again. Describe this scenario as input for your prediction program. (c) Run
clingo on your program with that input.
146 CHAPTER 7. DYNAMIC SYSTEMS
Exercise 7.19. (a) Write a prediction program for the 3-way bulb domain. (b) There are
10 bulbs, and all switches are initially in the high position. We pull all chains controlling
the bulbs, one after the other. Describe this scenario as input for your prediction program.
(c) Run clingo on your program with that input.
Exercise 7.20. (a) Write a prediction program for the crossing the river domain.
(b) There are two items, a and b. Initially a and the boat are on the left bank, and b
is on the right bank. We take a to the opposite bank. Describe this scenario as input for
your prediction program. (c) Run clingo on your program with that input.
7.7 Planning
Now we will consider the use of answer set programming for generating a plan of a given
length, if it exists. Take, for instance, the problem of constructing a plan of length 2 for
example (iii) from Section 7.1. This problem can be encoded by modifying the prediction
program shown in Listings 7.1 and 7.2 as follows.
First, we replace Line 4 in Listing 7.4, which describes a specific sequence of actions, by
rules allowing an arbitrary sequence of actions of length h:
action(move(B1,B2)) :- block(B1), block(B2), B1 != B2.
action(move(B,table)) :- block(B).
{occurs(A,T) : action(A)} = 1 :- T = 0..h-1
These rules allow two kinds of actions in a plan: moving a block onto another block and
moving a block onto the table. After this modification, the program will have many stable
models: one per each sequence of 2 actions that can be executed starting in state S7 .
Exercise 7.21. How many stable models do you think the modified program has?
Now it remains to add a constraint eliminating “bad” choices of actions—those for which
the goal of having b on top of c at the end is not satisfied:
:- not holds(loc(b,c),h).
Stable models of the new program represent all plans of length 2 that solve the problem in
question.
Exercise 7.22. How many stable models do you think are eliminated by adding this
constraint?
A general planning program for the blocks world and an input file for it that represents
problem (iii) from Section 7.1 are shown in Listings 7.3 and 7.4. The auxiliary predicate
goal/1 is used to encode the goal of the planning problem.
Exercise 7.23. In the blocks world with 9 blocks, the initial state is
1
2 5
(7.15)
3 6 8
4 7 9
148 CHAPTER 7. DYNAMIC SYSTEMS
and the goal is to have 9 on top of 6, 6 on top of 3, and 3 on the table. We would like to
achieve this goal in 7 steps. (a) Encode this problem as an input file for the blocks world
planning program in Listing 7.3. (b) Use clingo to find a solution.
If a blocks world planning program does not have stable models for a given input then
we can conclude that there is no plan of required length h. It does not follow, generally,
that there is no plan of length strictly less than h, so that we cannot conclude that the
given value of h is too small. But it is easy to find out whether it is indeed necessary to
increase h. This can be accomplished by introducing a new action, which has no effect on
the values of fluents:
action(wait). (7.16)
Allowing this trivial action to appear in the plan is essentially equivalent to allowing h to
be replaced by a smaller number.
Furthermore, if we know a value of h such that the planning program with line (7.16)
added to the input has a stable model then we can instruct clingo to look for the shortest
possible solution to the given problem. To do that, add a directive that calls for using the
trivial action as often as possible—
#maximize{1,T : occurs(wait,T)}.
or (7.17)
#maximize{T : occurs(wait,T)}.
(see the discussion of the chromatic number example in Section 6.4). Take, for example,
the input shown in the solution to Exercise 7.23, replace the value 7 of the placeholder h
by a larger number—say, 10—and add to it line (7.16) and the second of directives (7.17).
For the modified input, the last part of the output produced by clingo may look like this:
Answer: 5
occurs(move(1,table),0) occurs(move(2,1),1) occurs(move(8,table),2)
occurs(move(3,table),3) occurs(move(5,2),4) occurs(move(6,3),5)
occurs(move(9,6),6) occurs(wait,7) occurs(wait,8) occurs(wait,9)
Optimization: -24
OPTIMUM FOUND
The fact that 3 out of the 10 occurs atoms in the optimal stable model contain the trivial
action shows that the length of the shortest solution to the given planning problem is 7.
One of these solutions is given by the occurs atoms that do not contain wait.
150 CHAPTER 7. DYNAMIC SYSTEMS
Exercise 7.24. (a) Write a planning program for the turkey shoot domain. (b) Initially,
the gun is loaded and the turkey is alive. We would like the gun to be loaded while the
turkey is dead. Use clingo to solve this planning problem.
Exercise 7.25. (a) Write a planning program for the 3-way bulb domain. (b) There are
3 bulbs, and initially all switches are in the medium position. We would like all of them to
be off. Use clingo to solve this planning problem.
In some cases, we want to find a solution to a planning problem that satisfies some
additional conditions, beyond those expressed by the definition of goal/1. This can be often
accomplished by adding constraints to the input of the planning program. As an example,
consider the planning problem from Exercise 7.23 with the additional requirement: there
should never be more than 3 towers on the table while the plan is executed. (The table is
small, and there is no room on it for more than 3 blocks side by side.) This requirement
can be expressed by the constraint
Exercise 7.26. Use clingo to find the shortest plan satisfying this condition.
Exercise 7.27. (a) Write a planning program for the crossing the river domain. (b) In
the fox, goose and bag of beans puzzle, a farmer must transport a fox, goose and bag of
beans from one side of a river to another using a boat which can only hold one item in
addition to the farmer, subject to the constraints that the fox cannot be left alone with the
goose, and the goose cannot be left alone with the beans. This puzzle can be viewed as
a planning problem in the crossing the river domain with additional conditions. Write an
input file for your crossing the river program that represents this puzzle. (c) Use clingo
to solve the puzzle.
7.8 Concurrency
A robot with several grippers may be able to move several objects simultaneously. Think,
for instance, of a robot with two grippers facing blocks world configuration (7.15) on
page 147. Instead of choosing between the actions, say, move(1,table) and move(5,table),
it can execute these actions concurrently. Or it can swap blocks 1 and 5 by executing the
actions move(1,6) and move(5,2). These two actions can only be performed concurrently;
any one of them is not executable in state (7.15) by itself.
To talk about the concurrent execution of actions in terms of transition diagrams, we
need to modify the description of that concept given in Section 7.2 and label the edges of
the graph by sets of actions, rather than individual actions. In case of the blocks world with
3 blocks (Figure 7.2, page 138) and a robot with 2 grippers, every edge will be labeled by
a set consisting of 1 or 2 actions. Let us assume that the robot is unable to move a block
7.8. CONCURRENCY 151
onto a block that is being moved at the same time. Under this assumption, instead of the
edges (7.2) starting at S7 (page 139), in the modified transition diagram we will see
To encode the assumption that blocks are being moved by a robot with m grippers (or
by m agents whose actions are synchronous), we replace Line 12 in Listing 7.3 by the rule
The assumption that the destination of a move is not moving concurrently can be expressed
by the constraint
:- occurs(move(_,B),T), occurs(move(B,_),T).
It is interesting that constraint (7.12) and the precondition from Exercise 7.15 (page 145)
are not interchangeable when concurrent actions are allowed. The latter would not allow B1
to be moved onto B2 even while the block covering B2 is being moved away. For instance,
it would prohibit swapping blocks 1 and 5 in state (7.15). This is much too strong. On the
other hand, it would allow two blocks to be moved concurrently onto the same block that is
currently clear. For instance, it would allow moving blocks 1 and 5 onto block 8 concurrently.
In this sense, it is too weak. Constraint (7.12), which restricts the executability of actions
indirectly, does not suffer from these problems.
When concurrent actions are allowed, the shortest solution to a planning problem is
not necessarily the most economical in the sense of the total number of actions: counting
actions is different from counting steps.
The use of rule (7.16) and directive (7.17) for generating the shortest solution to a
planning problem of this kind requires an additional constraint: the trivial action is not
executed concurrently with any other action. This can be written as
Exercise 7.28. Use clingo to find out how many steps a robot with 2 grippers would
need to solve the planning problem from Exercise 7.23.
Exercise 7.29. (a) Modify the planning program from Exercise 7.25(a) to reflect the
assumption that the person operating the switches uses both hands and can access any
two switches simultaneously. (b) How many steps do you think are needed to solve the
planning problem from Exercise 7.25(b) under this assumption? Use clingo to verify your
conjecture.
152 CHAPTER 7. DYNAMIC SYSTEMS
This feature is essential, because the program was supposed to produce workable plans even
when some switches malfunction.
Other rules of the program describe the relationship between the state of a switch and
the state of the valve that it controls; between the pressure on a jet and the states of
the valves separating it from fuel and oxidizer tanks; and so forth. In combination with
rule (7.19), these rules describe remote, indirect effects of flipping a switch. The bodies of
these additional rules do not refer to executing actions. But they are similar to the body
of rule (7.19) in the sense that they include conditions restricting them to “normal” cases,
when the valves are not stuck and not leaking.
The RCS consists of three subsystems: left, right, and forward. The RCS/USA Advisor
uses the atom action_of(A,R) (“A is an action of subsystem R) instead of action(A) that
we saw in the blocks world planning program (Listing 7.3 on page 148). Instead of the rule
on Line 11 of that program, which allows one action at each time instant, the RCS/USA
Advisor program allows up to three actions to be executed concurrently—at most one for
each subsystem.
154 CHAPTER 7. DYNAMIC SYSTEMS
Appendix A
Answers to Exercises
Answers to some of the exercises can be verified by running clingo, and they are not
included here.
2.1. (c) Replace rule (1.1) by large(C) :- size(C,S), S > 500.
2.2. (a) X is a child of Y if Y is a parent of X.
2.3. (a) large(germany) :- size(germany,83), size(uk,64), 83 > 64.
(b) child(dan,bob) :- parent(bob,dan).
2.4. (b), (c), and (d).
2.5. parent(ann,bob; bob,carol; bob,dan).
2.8. p(2**N,2**(N+1)) :- N = 0..3.
2.9. (a) p(N,(-1)**N) :- N = 0..4. (b) p(M,N) :- M = 1..4, N = 1..4, M >= N.
2.11. (a) grandparent(X,Z) :- parent(X,Y), parent(Y,Z).
2.12. (a) sibling(X,Y) :- parent(Z,X), parent(Z,Y), X != Y.
2.13. enrolled(S) :- enrolled(S,C).
2.14. same_city(X,Y) :- lives_in(X,C), lives_in(Y,C).
2.15. older(X,Y) :- age(X,M), age(Y,N), M > N.
2.17.
Line 5: noncoprime(N) :- N = 1..n, I = 2..N, N\I = 0, k\I = 0.
Line 10: coprime(N) :- N = 1..n, not noncoprime(N).
2.18.
Line 6:
155
156 APPENDIX A. ANSWERS TO EXERCISES
{p(a);q(b)}.
:- not p(a), not q(b).
fac(F) :- fac(_,F).
3.12. (s!)n .
3.13.
Line 13: I = J :- in(I), in(J), s(X,I), s(X,J).
Line 16: covered(X) :- in(I), s(X,I).
Line 19: :- s(X,_), not covered(X).
3.14.
Line 6: {in(X) : vertex(X)} = n.
Line 9: covered(X,Y) :- edge(X,Y), in(X).
Line 10: covered(X,Y) :- edge(X,Y), in(Y).
Line 14: :- edge(X,Y), not covered(X,Y).
157
3.15.
Line 8: {color(X,C) : color(C)} = 1 :- vertex(X).
Line 12: :- edge(X,Y), color(X,C), color(Y,C).
4.1. Only one: {q, r}.
4.2. ¬p ∨ ¬q.
4.3. ∅, {q}, {r}, {p, q, r}.
4.4. ∅, {p, q, r, s}.
4.5. (a) A subset of {p1 , p2 , . . . , p8 } satisfies p1 ∧ p2 iff it includes both p1 and p2 . For
each of the other 6 atomic propositions we can decide arbitrarily whether to include it.
Consequently the number of models of p1 ∧ p2 is 26 , or 64.
(b) The set {p1 , p2 , . . . , p8 } has 28 subsets. A subset of that set satisfies p1 ← p2 unless
it includes p2 but does not include p1 . The number of such exceptional subsets is 26 . It
follows that the number of models of p1 ← p2 is 28 − 26 , or 192.
4.6. (a) {p1 , p3 , p5 , . . . } and {p0 , p1 , p3 , p5 , . . . }. (b) ∅, {p0 }, {p0 , p1 }.
4.7. (a): not equivalent; for example, {q} satisfies p ← r but does not satisfy the first of
the formulas p ← q, q ← r. (b)–(e): equivalent.
4.8. (a) >. (b) p ∨ q. (c) p ← q.
4.9. (a) p. (b) {¬p, q ← r}.
4.10. Both (a) and (b).
4.11. q ← p.
4.12. This set is equivalent to {p ↔ q, q ← q ∧ r}. Since the second formula is a tautology,
it can be dropped.
4.13. (a) {p, r}, {q, s}, {p, r, s}, {q, r, s}, {p, q, r, s}. (b) {p, r} and {q, s}.
4.14. {p, q} and {r}. Note that {p, q} is a minimal model even though it has more elements
than {r}.
4.15. (a) All interpretations are models. (b) The only minimal model is ∅.
4.16. (a) All sets of interpretations containing Γ are models. (b) The only minimal model
is Γ itself.
4.17. p ∨ q ∨ r ∨ s.
4.18. p ← q and q ← p.
4.19. Step 1: include r1 ; step 2: add q1 ; step 3: add p1 and p2 . Minimal model:
{p1 , p2 , q1 , r1 }.
4.20. (a) Minimal model: ∅. (b) Step 1: include p5 . Minimal model: {p5 }. (c) Step 1:
include p5 and p6 ; step 2: add p4 ; step 3: add p3 ; step 4: add p2 ; step 5: add p1 . Minimal
model: {p1 , . . . , p6 }.
158 APPENDIX A. ANSWERS TO EXERCISES
4.21. p ← ¬q.
4.22. (a) Step 1: include p3 ; step 2: add p2 ; step 3: add p1 . Minimal model: {p1 , p2 , p3 }. (b)
Step 1: include p3 ; step 2: add p4 ; step 3: add p5 ; and so on. Minimal model: {p3 , p4 , . . . }.
4.23. (a)
p.
q :- p, r.
r :- p.
r :- t.
s :- r, t.
4.24. (a)
p1 :- q1.
p2 :- q1.
p1 :- q2.
p2 :- q2.
q1 :- r1.
q1 :- r2.
r1.
4.26. (a)
p(0, 1),
p(1, 2),
q(v1 , v2 ) ← p(v1 , v2 ) ∧ > ∧ > for all v1 , v2 ∈S∪Z such that v1 , v2 > 0,
q(v1 , v2 ) ← p(v1 , v2 ) ∧ ⊥ ∧ > for all v1 , v2 ∈S∪Z such that v1 ≤ 0, v2 > 0,
q(v1 , v2 ) ← p(v1 , v2 ) ∧ > ∧ ⊥ for all v1 , v2 ∈S∪Z such that v1 > 0, v2 ≤ 0,
q(v1 , v2 ) ← p(v1 , v2 ) ∧ ⊥ ∧ ⊥ for all v1 , v2 ∈S∪Z such that v1 , v2 ≤ 0.
(b)
p(0, 1),
p(1, 2),
q(v1 , v2 ) ← p(v1 , v2 ) for all v1 , v2 ∈ S ∪ Z such that v1 , v2 > 0.
(c) Step 1: include p(0, 1) and p(1, 2). Step 2: add q(1, 2).
4.27. (a)
parent(ann, bob),
parent(bob, carol),
parent(bob, dan),
child(v1 , v2 ) ← parent(v2 , v1 ) for all v1 , v2 ∈ S ∪ Z,
ancestor(v1 , v2 ) ← parent(v1 , v2 ) for all v1 , v2 ∈ S ∪ Z,
ancestor(v1 , v3 ) ← ancestor(v1 , v2 ) ∧ ancestor(v2 , v3 ) for all v1 , v2 , v3 ∈ S ∪ Z.
159
Step 2: add
Step 3: add
ancestor(ann, carol), ancestor(ann, dan).
4.28. (a)
p(1) ∨ p(2) ∨ p(3),
⊥ ← p(v) ∧ > for all v ∈ S ∪ Z such that v > 2,
⊥ ← p(v) ∧ ⊥ for all v ∈ S ∪ Z such that v ≤ 2.
(b) The formulas in the second line can be equivalently rewritten as ¬p(v), and the formulas
in the last line are tautologies. It follows this set of formulas is equivalent to
Since the set of formulas in the second line includes ¬p(3), the formula in the first line can
be equivalently replaced by p(1) ∨ p(2). (c) Set (A.1) has two minimal models, {p(1)} and
{p(2)}.
4.29. (a)
p(a),
q(v1 , v2 ) ← p(v1 ) for all v1 , v2 ∈ S ∪ Z.
(b) Step 1: include p(a). Step 2: Add q(a, v) for all v ∈ S ∪ Z.
4.30. (a) and (b).
4.31. 4, 6, 8, 9, 12, 16.
4.32. (a) 3**(0..2); (b) 10*(2..4)+2.
4.33. (a) square(1, 1) ∧ square(1, 2) ∧ square(2, 1) ∧ square(2, 2).
(b) q ← square(1, 1) ∨ square(1, 2) ∨ square(2, 1) ∨ square(2, 2). (c) >. (d) q ← ⊥.
Tautologies: (c) and (d).
4.34. (a) {p(1), q ← p(1) ∨ p(2) ∨ p(3)}. (b) {p(1), q}.
4.35. (a)
> ← >,
p(1) ← >,
> ← ⊥.
(b) {p(1)}.
160 APPENDIX A. ANSWERS TO EXERCISES
4.36. (a)
p(1) ∧ p(2) ∧ p(3),
q(2) ← p(2) ∧ >,
q(3) ← p(3) ∧ >,
q(4) ← p(4) ∧ >,
q(v) ← p(v) ∧ ⊥ for all v ∈ S ∪ Z \ {2, 3, 4}.
(b)
p(1) ∧ p(2) ∧ p(3),
q(2) ← p(2),
q(3) ← p(3),
q(4) ← p(4).
(c) Step 1: include p(1), p(2), p(3). Step 2: add q(2) and q(3).
4.37. (a)
p(1, 1) ∧ p(1, 2),
q(v1 , v2 ) ← p(v1 , v2 ) ∧ > for all v1 , v2 ∈ S ∪ Z such that v1 6= v2 ,
q(v, v) ← p(v, v) ∧ ⊥ for all v ∈ S ∪ Z,
q(v1 , v2 ) ← q(v2 , v1 ) for all v1 , v2 ∈ S ∪ Z.
(b)
p(1, 1) ∧ p(1, 2),
q(v1 , v2 ) ← p(v1 , v2 ) for all v1 , v2 ∈ S ∪ Z such that v1 6= v2 ,
q(v1 , v2 ) ← q(v2 , v1 ) for all v1 , v2 ∈ S ∪ Z.
(c) Step 1: include p(1, 1), p(1, 2). Step 2: add q(1, 2). Step 3: add q(2, 1).
4.38. (a)
p(1) ∧ p(2) ∧ p(3),
q(n − 1) ∧ q(n) ∧ q(n + 1) ← p(n) for all n ∈ Z,
> ← p(v) for all v ∈ S.
(b) The rules in the last line are tautologies and can be dropped.
(c) Step 1: include p(1), p(2), p(3). Step 2: add q(0), q(1), q(2), q(3), q(4).
4.39. (a)
p(1) ∧ p(2) ∧ p(3),
> ← p(1),
⊥ ← p(v) for all v ∈ S ∪ Z \ {1}.
(b) Since the set of formulas in the last line includes ⊥ ← p(2), the propositional image has
no models.
4.40. (a)
p(1),
q(n) ← p(m) for all n ∈ Z, where m is the value of (−1)n ,
q(v) ← ⊥ for all v ∈ S.
161
(b) Step 1: Include p(1). Step 2: Add q(n) for all even numbers n.
5.1. (a) Atomic proposition q is not going to be included in the stable model, because it
does not occur in the head of any rule. From this we can conclude that s is not going to
be included either, because the only rule with s in the head has the body q. Consequently
condition (5.5) is satisfied, and the stable model is {p, r}.
5.2. (a) Atomic proposition r is not going to be included in the stable model, because it
does not occur in the head of any rule. It follows that in accordance with rule (5.7), the
stable model will include q. From that we conclude that rule (5.6) is disabled, and there is
no justification for adding p. The stable model is {q}.
5.3. (a) The reduct of (5.1)–(5.3) relative to {p, q, r} is
p,
q, (A.2)
r ← p ∧ >,
and the only minimal model of the reduct is {p, q, r}. (b) Take any interpretation I different
from {p, q, r}, and consider two cases. Case 1: s ∈ I. The reduct of the program relative
to I is
p,
q,
r ← p ∧ ⊥,
and its minimal model {p, q} does not contain s. Case 2: s 6∈ I. The reduct is (A.2), and
its only minimal model {p, q, r} is different from I.
5.4. (a) Take any interpretation I, and consider two cases. Case 1: p ∈ I. The reduct is
p ← ⊥. This is a tautology, so that its only minimal model is empty. It does not satisfy
the condition characterizing Case 1. Case 2: p 6∈ I. The reduct is p ← >, and its minimal
model {p} does not satisfy the condition characterizing Case 2. Consequently the given
program has no stable models.
5.5. (a) Take any interpretation I, and consider two cases. Case 1: q ∈ I. The reduct is
p ∨ q,
⊥ ← p ∧ ⊥.
The second line is a tautology, so that the minimal models of the reduct are the minimal
models of its first rule, {p} and {q}. The latter satisfies the condition characterizing Case 1,
so that it is a stable model of the given program. Case 2: q 6∈ I. The reduct is
p ∨ q,
⊥ ← p ∧ >.
The second rule is equivalent to ¬p, so that the reduct is equivalent to {q, ¬p}. The
minimal model {q} of the reduct does not satisfy the condition characterizing this case.
Consequently {q} is the only stable model of the given program.
162 APPENDIX A. ANSWERS TO EXERCISES
5.6. Take any interpretation I, and consider four cases. Case 1: q, r ∈ I. The reduct is
p ← ⊥,
q ← ⊥.
Both rules are tautologies, and the minimal model ∅ of the reduct does not satisfy the
condition characterizing this case. Case 2: q ∈ I, r 6∈ I. The reduct
p ← ⊥,
q←>
is equivalent to q. Its minimal model {q} is a stable model of the program. Case 3: q 6∈ I,
r ∈ I. The reduct
p ← >,
q←⊥
is equivalent to p. Its minimal model {p} does not satisfy the condition characterizing this
case. Case 4: q, r 6∈ I. The reduct
p ← >,
q←>
is equivalent to q. Its minimal model {q} does not satisfy the condition characterizing this
case.
5.7. (a) Take any interpretation I, and consider four cases. Case 1: p, q ∈ I. The reduct is
p ← ⊥,
q ← ⊥,
r ← p,
r ← q.
The minimal model ∅ does not satisfy the condition characterizing this case. Case 2: p ∈ I,
q 6∈ I. The reduct is
p ← >,
q ← ⊥,
r ← p,
r ← q.
The minimal model {p, r} satisfies the condition characterizing this case, so that {p, r} is
a stable model of the given program. Case 3: p 6∈ I, q ∈ I. A similar calculation gives the
163
p ← >,
q ← >,
r ← p,
r ← q.
The minimal model {p, q, r} does not satisfy the condition characterizing this case. Conse-
quently the given program has two stable models, {p, r} and {q, r}.
5.8. (a) Take any interpretation I, and consider four cases. Case 1: p, q ∈ I. The reduct is
p ← ⊥,
q ← ⊥,
p ← q,
q ← p.
The minimal model ∅ does not satisfy the condition characterizing this case. Case 2: p ∈ I,
q 6∈ I. The reduct is
p ← >,
q ← ⊥,
p ← q,
q ← p.
The minimal model {p, q} does not satisfy the condition characterizing this case. Case 3:
p 6∈ I, q ∈ I. A similar calculation leads to the same result. Case 4: p, q 6∈ I. The reduct is
p ← >,
q ← >,
p ← q,
q ← p.
The minimal model {p, q} does not satisfy the condition characterizing this case. Conse-
quently the given program has no stable models.
5.9. Values of the stability operator s:
p ∨ q,
r ∨ ⊥ ← p.
It has two minimal models, {p, r} and {q}. Neither satisfies the condition that characterizes
Case 1. Case 2: s 6∈ I. The reduct is
p ∨ q,
r ∨ > ← p.
Its minimal models are {p} and {q}. Both satisfy the condition that characterizes Case 2,
so that both are stable models of the given program.
5.13. (a) From Exercise 4.13(b) we know that the stable models of the first three rules of
the program are {p, r} and {q, s}. The former satisfies both constraints, and the latter does
not. It follows that the only stable model of the program is {p, r}.
5.14. (a)
p(a),
q(b), (A.3)
r(v) ← p(v) ∧ ¬q(v) (v ∈ S ∪ Z).
(b)
p(a),
q(b),
r(b) ← p(b) ∧ ⊥,
r(v) ← p(v) ∧ > (v ∈ S ∪ Z \ {b}).
(c)
p(a),
q(b),
r(v) ← p(v) (v ∈ S ∪ Z \ {b}).
(d) The minimal model {p(a), q(b), r(a)} is different from (5.28). Consequently (5.28) is not
a stable model of the program.
5.15. (a)
p(1),
(A.4)
q ← ¬p(1) ∨ ¬p(2) ∨ ¬p(3).
(b)
p(1),
q ← ⊥ ∨ ⊥ ∨ >.
165
(c)
p(1),
q.
(d) The minimal model of the reduct is (5.29). Consequently (5.29) is a stable model.
5.16. (a)–(c): q ← ⊥. (d)–(f): > ← q.
5.17. (a)
p(1) ∧ p(2) ∧ p(3),
q(2) ← > ∧ ¬p(2),
q(3) ← > ∧ ¬p(3),
q(4) ← > ∧ ¬p(4),
q(v) ← ⊥ ∧ ¬p(v) (v ∈ S ∪ Z \ {2, 3, 4}).
(b)
p(1) ∧ p(2) ∧ p(3),
q(2) ← ¬p(2),
(A.5)
q(3) ← ¬p(3),
q(4) ← ¬p(4).
(c)
p(1) ∧ p(2) ∧ p(3),
q(2) ← ⊥,
q(3) ← ⊥,
q(4) ← >.
(d)
p(1) ∧ p(2) ∧ p(3),
q(4).
(e) The minimal model {p(1), p(2), p(3), q(4)} of the reduct is different from (5.33). It follows
that (5.33) is not a stable model.
5.18. (a)
p(1) ∧ p(2) ∧ p(3) ∧ p(4),
q(1) ← > ∧ ¬p(1),
q(2) ← > ∧ ¬p(4),
q(3) ← > ∧ ¬p(9),
q(4) ← > ∧ ¬p(16),
q(v) ← ⊥ ∧ ¬p(v) (v ∈ Z \ {1, 2, 3, 4}),
q(v) ← ⊥ ∧ ⊥ (v ∈ S).
(b)
p(1) ∧ p(2) ∧ p(3) ∧ p(4),
q(1) ← ¬p(1),
q(2) ← ¬p(4), (A.6)
q(3) ← ¬p(9),
q(4) ← ¬p(16).
166 APPENDIX A. ANSWERS TO EXERCISES
(c)
p(1) ∧ p(2) ∧ p(3) ∧ p(4),
q(1) ← ⊥,
q(2) ← ⊥,
q(3) ← >,
q(4) ← >.
(d)
p(1) ∧ p(2) ∧ p(3),
q(3),
q(4).
(e) The minimal model of the reduct is (5.34). It follows that (5.34) is a stable model.
5.19. (a)
p(a) ∨ ¬p(a),
(A.7)
q(v) ← p(v) (v ∈ S ∪ Z).
(b)
p(a) ∨ >,
q(v) ← p(v) (v ∈ S ∪ Z).
(c)
q(v) ← p(v) (v ∈ S ∪ Z).
(d) The minimal model ∅ is different from (5.37). Consequently (5.37) is not a stable model
of the program.
5.20. (a)
p(a),
q(v) ∨ ¬q(v) ← p(v) (v ∈ S ∪ Z).
(b)
p(a),
q(v) ∨ > ← p(v) (v ∈ S ∪ Z).
(c) p(a). (d) The minimal model of the reduct is (5.38). Consequently (5.38) is a stable
model.
5.21.
(p(1, 1) ∨ ¬p(1, 1)) ∨ (p(1, 2) ∨ ¬p(1, 2)) ∨
(A.8)
(p(2, 1) ∨ ¬p(2, 1)) ∨ (p(2, 2) ∨ ¬p(2, 2)),
⊥ ← (p(1, 1) ∧ p(1, 2) ∧ p(2, 1)) ∨ (p(1, 1) ∧ p(1, 2) ∧ p(2, 2)) ∨
(A.9)
(p(1, 1) ∧ p(2, 1) ∧ p(2, 2)) ∨ (p(1, 2) ∧ p(2, 1) ∧ p(2, 2)).
letter(a),
letter(b),
p(c, 1) ∨ ¬p(c, 1),
(p(v, 1) ∨ ¬p(v, 1)) ∧ (p(v, 2) ∨ ¬p(v, 2)) ← letter(v),
⊥ ← p(v, 1) ∧ p(v, 2) ∧ letter(v),
⊥ ← ¬p(v, 1) ∧ ¬p(v, 2) ∧ letter(v)
(v ∈ S ∪ Z). The reduct of the first four rules of the propositional image relative to
interpretation (5.44) is
letter(a),
letter(b),
p(c, 1) ∨ >,
(p(a, 1) ∨ >) ∧ (p(a, 2) ∨ ⊥) ← letter(a),
(p(b, 1) ∨ ⊥) ∧ (p(b, 2) ∨ >) ← letter(b),
(p(v, 1) ∨ >) ∧ (p(v, 2) ∨ >) ← letter(v) (v ∈ S ∪ Z \ {a, b}),
5.26. Consider sets Γ1 , Γ2 of positive propositional rules that are equivalent to each other.
The reduct of Γi relative to any interpretation is Γi . Consequently the reduct of Γ1 relative
to any interpretation is equivalent to the reduct of Γ2 relative to the same interpretation.
5.27. True. Indeed, the propositional image of a ground rule of form (5.53) has the form
F ←⊥
F ←>
F ∨>
or
F ∨⊥
depending on the same condition. In both cases, the propositional images are strongly
equivalent to each other.
5.28. True. Indeed, if the reduct of (5.55) relative to some interpretation is F 0 ← > ∧ G0
then the reduct of (5.56) relative to the same interpretation is F 0 ∨ ⊥ ← G0 ; if the reduct
of the former is F 0 ← ⊥ ∧ G0 then the reduct of the latter is F 0 ∨ > ← G0 . Either way, the
two reducts are equivalent to each other.
5.29. (a) False: p∨¬p has two stable models, and the empty program has one. (b) True: this
is a negative tautology. (c) True, for the same reason. (d) True: any reduct F 0 ← F 0 ∧ G0
of this rule is a tautology. (e) True: any reduct F 0 ∨ G0 ← F 0 of this rule is a tautology.
5.30. The result of simplifying (5.61) is
p ↔ ⊥,
q ↔ >,
r ↔ ⊥,
p ↔ >,
q ↔ >,
r ↔ >,
s ↔ ⊥,
169
p ↔ >,
q ↔ ⊥,
r ↔ >,
s ↔ ⊥,
p ↔ ¬q,
q ↔ ¬¬q,
r ↔ p.
This second formula became a tautology and can be dropped. It follows that the completion
has two models, corresponding to two ways to assign a truth value to q: {p, r} and {q}.
5.35. (a) The completion of the program is
p ↔ ¬q,
q ↔ ¬r,
r ↔ ¬p.
r ↔ ¬¬q.
This formula can be rewritten as r ↔ q, which contradicts the second line. Consequently
the completion of this program has no models, and the program has no stable models.
5.36. The completion of the program is
p ↔ ¬q ∨ q,
q ↔ ¬p ∨ p.
170 APPENDIX A. ANSWERS TO EXERCISES
The first formula is equivalent to p, and the second is equivalent to q. Consequently the
only model of completion is {p, q}. Since the program does not satisfy condition (γ), we
need to check whether this model is stable. The reduct of the program relative to {p, q} is
p ← ⊥,
q ← ⊥,
p ← q,
q ← p,
p(a) ↔ >,
p(v) ↔ ⊥ for all v other than a,
q(b) ↔ >,
q(v) ↔ ⊥ for all v other than b,
r(v) ↔ p(v) ∧ ¬q(v) for all v.
which is equivalent to
r(a) ↔ >,
r(v) ↔ ⊥ for all v other than a.
Consequently the only model of the completion is {p(a), q(b), r(a)}. Since (A.3) satisfies
conditions (α)–(γ), it follows that {p(a), q(b), r(a)} is the only stable model of the program.
5.38. (a) The completion of the propositional image (A.4) of the program is
p(1) ↔ >,
p(v) ↔ ⊥ for all v other than 1,
q ↔ ¬p(1) ∨ ¬p(2) ∨ ¬p(3).
q ↔ ¬> ∨ ¬⊥ ∨ ¬⊥,
which is equivalent to
q ↔ >.
171
Consequently the only model of the completion is {p(1), q}. Since (A.4) satisfies condi-
tions (α)–(γ), it follows that {p(1), q} is the only stable model of the program.
5.39. The simplified propositional image (5.32) of the program satisfies conditions (α)–(γ),
and its completion is
composite(4) ↔ >,
composite(v) ↔⊥ for all v other than 4,
prime(v) ↔ ¬composite(v) if v ∈ {2, . . . , 5},
prime(v) ↔⊥ if v 6∈ {2, . . . , 5}.
The first two lines allow us to rewrite the last two lines as
prime(v) ↔ > if v ∈ {2, 3, 5},
prime(v) ↔ ⊥ if v ∈
6 {2, 3, 5}.
5.40. (a) The simplified propositional image (A.5) of the program, with the first rule broken
into three, satisfies conditions (α)–(γ). Its completion is
It follows that {p(1), p(2), p(3), q(4)} is the only stable model of the program.
5.41. (a) The simplified propositional image (A.6) of the program, with the first rule broken
into four, satisfies conditions (α)–(γ). Its completion is
q(1) ↔ ⊥,
q(2) ↔ ⊥,
q(3) ↔ >,
q(4) ↔ >.
172 APPENDIX A. ANSWERS TO EXERCISES
It follows that {p(1), p(2), p(3), q(3), q(4)} is the only stable model of the program.
5.42. (a) The propositional image (A.7) of the program has the same stable models as the
program
p(a) ← ¬¬p(a),
q(v) ← p(v) for all v,
which satisfies conditions (α)–(γ). The completion of this program is
p(a) ↔ ¬¬p(a),
p(v) ↔ ⊥ for all v other than a,
q(v) ↔ p(v) for all v.
The first line is a tautology and can be dropped. The second line allows us to replace the
third line by
q(a) ↔ p(a),
q(v) ↔ ⊥ for all v other than a.
Consequently the completion has two models, corresponding to two ways to assign a truth
value to p(a): ∅ (if p(a) is false) and {p(a), q(a)} (if p(a) is true).
5.43. (a) The propositional image of the program consists of rules (A.8)–(A.10) and the
constraints
⊥ ← p(1, 1),
(A.12)
⊥ ← p(2, 2).
Rule (A.8) is strongly equivalent to the program
which satisfies conditions (α)–(γ); rules (A.9), (A.10), (A.12) are constraints. It follows
that the stable models of the given program can be characterized as the models of the
completion of program (A.13) that satisfy constraints (A.9), (A.10), (A.12). The completion
of program (A.13) is a set of tautologies. Formulas (A.12) allow us to rewrite (A.9), (A.10)
as
⊥ ← (⊥ ∧ p(1, 2) ∧ p(2, 1)) ∨ (⊥ ∧ p(1, 2) ∧ ⊥) ∨
(⊥ ∧ p(2, 1) ∧ ⊥) ∨ (p(1, 2) ∧ p(2, 1) ∧ ⊥),
6.6.
Line 14: :- #sum{X : filled(R,_,X)} != magic, R = 1..n.
Line 17: :- #sum{X : filled(_,C,X)} != magic, C = 1..n.
Line 20: :- #sum{X : filled(R,R,X)} != magic.
Line 21: :- #sum{X : filled(R,n+1-R,X)} != magic.
6.8.
howmany(I,N) :- N = #count{C : where(C,I)}, I = 1..K,
K = #max{J : where(C,J)}.
6.10.
Line 10: {in(I,0..maxweight/W)} = 1 :- weight(I,W).
Line 15: :- #sum{W*N,I : in(I,N), weight(I,W)} > maxweight.
Line 20: #maximize{V*N,I : in(I,N), value(I,V)}.
6.13.
Line 7: referee(R) :- bid(R,_,_).
Line 11: paper(P) :- bid(_,P,_).
Line 17: {review(R,P) : referee(R), not bid(R,P,no)} = k :- paper(P).
Line 22: workload(R,N) :- referee(R), N = #count{P : review(R,P)}.
Line 26: :- workload(R1,N1), workload(R2,N2), |N1-N2| > 1.
Line 31: #maximize{1,R,P : bid(R,P,yes), review(R,P)}.
7.4.
(loaded, alive) (loaded, dead )
load ↑ shoot & shoot ↓ ↑ load
(unloaded, alive) (unloaded, dead )
7.5. (a)
pull (1)
0 −−−−−−−−−→ 1
pull (1) ↑ ↓ pull (1)
3 ←−−−−−−−−− 2
pull (1)
(b) n4n . (c) Edge labeled pull (1) leading to (1,0,3); edge labeled pull (2) leading to (0,1,3);
edge labeled pull (3) leading to (0,0,0).
7.7.
#const h=2.
holds(state_of_gun(unloaded),0).
holds(state_of_turkey(alive),0).
occurs(load,0).
occurs(shoot,1).
7.8.
#const h=1.
holds(brightness(bulb(1),0),0).
holds(brightness(bulb(2),0),0).
holds(brightness(bulb(3),3),0).
occurs(pull(3),0).
7.9.
#const h=4.
holds(loc(a,left),0).
holds(loc(b,left),0).
holds(loc(boat,right),0).
occurs(cross(empty),0).
occurs(cross(a),1).
occurs(cross(empty),2).
occurs(cross(b),3).
175
7.10. (a)
:- #count{S : holds(state_of_gun(S),T)} != 1, T = 0..h.
:- #count{S : holds(state_of_turkey(S),T)} != 1, T = 0..h.
(b) :- #count{B : holds(brightness(bulb(I),B),T)} != 1, I = 1..n, T = 0..h.
(c)
:- #count{L : holds(loc(I,L),T)} != 1, item(I), T = 0..h.
:- #count{L : holds(loc(boat,L),T)} != 1, T = 0..h.
7.11.
holds(brightness(bulb(I),(B+1)\4),T+1) :-
occurs(pull(I),T), holds(brightness(bulb(I),B),T).
7.12. (a)
holds(state_of_gun(X),T+1) :- holds(state_of_gun(X),T),
not not holds(state_of_gun(X),T+1),
T = 0..h-1.
holds(state_of_turkey(X),T+1) :-
holds(state_of_turkey(X),T),
not not holds(state_of_turkey(X),T+1),
T = 0..h-1.
(b)
holds(brightness(bulb(I),B),T+1) :-
holds(brightness(bulb(I),B),T),
not not holds(brightness(bulb(I),B),T+1),
T = 0..h-1.
(c) Rule (7.9) will do.
7.13.
{holds(brightness(bulb(I),B),T+1)} :- holds(brightness(bulb(I),B),T),
T = 0..h-1.
7.18. (a)
% Predict the effect of executing a sequence of actions in the
% turkey shoot domain.
% effects of actions
holds(state_of_gun(loaded),T+1) :- occurs(load,T).
holds(state_of_gun(unloaded),T+1) :- occurs(shoot,T).
holds(state_of_turkey(dead),T+1) :- occurs(shoot,T).
% inertia
{holds(state_of_gun(X),T+1)} :- holds(state_of_gun(X),T), T = 0..h-1.
{holds(state_of_turkey(X),T+1)} :- holds(state_of_turkey(X),T),
T = 0..h-1.
#show final/1.
(b)
#const h=3.
init(state_of_gun(unloaded); state_of_turkey(alive)).
occurs(load,0; shoot,1; load,2).
7.19. (a)
% Predict the effect of executing a sequence of actions in the
% 3-way bulb domain.
177
% effects of actions
holds(brightness(bulb(I),(B+1)\4),T+1) :-
occurs(pull(I),T), holds(brightness(bulb(I),B),T).
% inertia
{holds(brightness(bulb(I),B),T+1)} :- holds(brightness(bulb(I),B),T),
T = 0..h-1.
#show final/1.
(b)
#const n=10.
#const h=10.
init(brightness(bulb(1..10),3)).
occurs(pull(I),I-1) :- I = 1..10.
7.20. (a)
% definition of opposite/2.
opposite(left,right; right,left).
% effects of actions
178 APPENDIX A. ANSWERS TO EXERCISES
holds(loc(boat,L1),T+1) :- occurs(cross(_),T),
holds(loc(boat,L),T),
opposite(L,L1).
holds(loc(I,L1),T+1) :- occurs(cross(I),T), item(I),
holds(loc(I,L),T),
opposite(L,L1).
% inertia
{holds(loc(X,L),T+1)} :- holds(loc(X,L),T), T = 0..h-1.
#show final/1.
(b)
item(a; b).
#const h=1.
init(loc(a,left); loc(boat,left); loc(b,right)).
occurs(cross(a),0).
7.23. (a)
block(1..9).
init(loc(1,2); loc(2,3); loc(3,4); loc(4,table);
loc(5,6); loc(6,7); loc(7,table);
loc(8,9); loc(9,table)).
goal(loc(9,6); loc(6,3); loc(3,table)).
#const h=7.
7.24. (a)
% For a planning problem in the turkey shoot domain, find
% solutions of a given length.
% choice of actions
action(load; shoot).
{occurs(A,T) : action(A) } = 1 :- T = 0..h-1.
% effects of actions
holds(state_of_gun(loaded),T+1) :- occurs(load,T).
holds(state_of_gun(unloaded),T+1) :- occurs(shoot,T).
holds(state_of_turkey(dead),T+1) :- occurs(shoot,T).
% inertia
{holds(state_of_gun(X),T+1)} :- holds(state_of_gun(X),T), T = 0..h-1.
{holds(state_of_turkey(X),T+1)} :- holds(state_of_turkey(X),T),
T = 0..h-1.
#show occurs/2.
7.25. (a)
% For a planning problem in the 3-way bulb domain, find solutions
% of a given length.
% choice of actions
action(pull(1..n)).
{occurs(A,T) : action(A) } = 1 :- T = 0..h-1.
% effects of actions
180 APPENDIX A. ANSWERS TO EXERCISES
holds(brightness(bulb(I),(B+1)\4),T+1) :-
occurs(pull(I),T), holds(brightness(bulb(I),B),T).
% inertia
{holds(brightness(bulb(I),B),T+1)} :- holds(brightness(bulb(I),B),T),
T = 0..h-1.
#show occurs/2.
7.27. (a)
% For a planning problem in the crossing the river domain, find
% solutions of a given length.
% choice of actions
action(cross(I)) :- item(I).
action(cross(empty)).
{occurs(A,T) : action(A) } = 1 :- T = 0..h-1.
% definition of opposite/2.
opposite(left,right; right,left).
% effects of actions
holds(loc(boat,L1),T+1) :- occurs(cross(_),T),
holds(loc(boat,L),T),
opposite(L,L1).
holds(loc(I,L1),T+1) :- occurs(cross(I),T), item(I),
holds(loc(I,L),T),
opposite(L,L1).
% inertia
{holds(loc(X,L),T+1)} :- holds(loc(X,L),T), T = 0..h-1.
#show occurs/2.
(b)
init(loc(boat,left)).
init(loc(I,left)) :- item(I).
goal(loc(boat,right)).
goal(loc(I,right)) :- item(I).
#const h=10.
action(wait).
#maximize{T : occurs(wait,T)}.
by
183
184 LISTINGS
[3] Markus Aschinger, Conrad Drescher, Gerhard Friedrich, Georg Gottlob, Peter Jeav-
ons, Anna Ryabokon, and Evgenij Thorstensen. Optimization methods for the partner
units problem. In Proceedings of the Eigth International Conference on Integration of
AI and OR Techniques in Constraint Programming for Combinatorial Optimization
Problems, pages 4–19, 2011.
[4] Evgenii Balai, Michael Gelfond, and Yuanlin Zhang. Towards answer set program-
ming with sorts. In Proceedings of the Twelfth International Conference on Logic
Programming and Nonmonotonic Reasoning, pages 135–147, 2013.
[6] Marcello Balduccini. ASP with non-Herbrand partial functions: a language and sys-
tem for practical use. Theory and Practice of Logic Programming, 13:547–561, 2013.
[7] Marcello Balduccini and Michael Gelfond. Logic programs with consistency-restoring
rules. In Working Notes of the AAAI Spring Symposium on Logical Formalizations
of Commonsense Reasoning, 2003.
[8] Marcello Balduccini and Yuliya Lierler. Constraint answer set solver EZCSP and why
integration schemas matter. Theory and Practice of Logic Programming, 17:462–515,
2017.
[9] Mutsunori Banbara, Benjamin Kaufmann, Max Ostrowski, and Torsten Schaub.
Clingcon: The next generation. Theory and Practice of Logic Programming, 17:408–
461, 2017.
[10] Chitta Baral. Knowledge Representation, Reasoning and Declarative Problem Solving.
Cambridge University Press, 2003.
185
186 BIBLIOGRAPHY
[11] Michael Bartholomew and Joohyung Lee. Stable models of formulas with intensional
functions. In Proceedings of International Conference on Principles of Knowledge
Representation and Reasoning, pages 2–12, 2012.
[12] Leonard Baumert and Solomon Golomb. Backtrack programming. Journal of the
ACM, 12:516–524, 1965.
[13] Nicole Bidoit and Christine Froidevaux. Minimalism subsumes default logic and cir-
cumscription in stratified logic programming. In Proceedings LICS-87, pages 89–97,
1987.
[14] Prosenjit Bose, Jonathan Buss, and Anna Lubiw. Pattern matching for permutations.
Information Processing Letters, 65(5):277–283, 1998.
[15] Martin Brain, Esra Erdem, Katsumi Inoue, Johannes Oetsch, Jörg Pührer, Hans
Tompits, and Cemal Yilmaz. Event-sequence testing using answer-set programming.
International Journal on Advances in Software, 5:237–251, 2012.
[16] Gerhard Brewka. Logic programming with ordered disjunction. In Proceedings of the
Eighteenth National Conference on Artificial Intelligence, pages 100–105, 2003.
[17] Gerhard Brewka, James Delgrande, Javier Romero, and Torsten Schaub. asprin:
Customizing answer set preferences without a headache. In Proceedings of the Twenty-
Ninth AAAI Conference on Artificial Intelligence, pages 1467–1474, 2015.
[18] Luitzen Egbertus Jan Brouwer. Über die Bedeutung des Satzes vom ausgeschlossenen
Dritten in der Mathematik, insbesondere in der Funktiontheorie. Journal für die reine
und angewandte Mathematik, 154:1–7, 1923.
[19] Pedro Cabalar. Functional answer set programming. Theory and Practice of Logic
Programming, 11:203–234, 2011.
[20] Marco Calautti, Sergio Greco, and Irina Trubitsyna. Detecting decidable classes of
finitely ground logic programs with function symbols. ACM Transactions on Compu-
tational Logic, 18(4):28:1–28:42, November 2017.
[21] Francesco Calimeri, Susanna Cozza, Giovambattista Ianni, and Nicola Leone. Com-
putable functions in ASP: theory and implementation. In Proceedings of International
Conference on Logic Programming (ICLP), pages 407–424, 2008.
[22] Günther Charwat and Andreas Pfandler. Democratix: A declarative approach to win-
ner determination. In Proceedings of the 4th International Conference on Algorithmic
Decision Theory (ADT), 2015.
[23] Baral Chitta, Michael Gelfond, and Nelson Rushton. Probabilistic reasoning with
answer sets. Theory and Practice of Logic Programming, 9:57–144, 2009.
BIBLIOGRAPHY 187
[24] Pawel Cholewiński, Victor Marek, and Miroslaw Truszczynski. Default reasoning
system DeReS. In Proceedings of International Conference on Principles of Knowledge
Representation and Reasoning (KR), pages 518–528, 1996.
[25] Vas̆ek Chvátal. Some unknown van der Waerden numbers. In Richard Guy, Haim
Hanani, and Norbert Sauer, editors, Combinatorial Structures and Their Applications,
pages 31–33. New York: Gordon and Breach, 2009.
[26] Simona Citrigno, Thomas Eiter, Wolfgang Faber, Georg Gottlob, Christoph Koch,
Leone Nicola, Cristinel Mateis, Gerald Pfeifer, and Francesco Scarcello. The dlv
system: Model generator and application frontends. In Proceedings of Workshop on
Logic Programming (WLP97), 1997.
[27] Keith Clark. Negation as failure. In Herve Gallaire and Jack Minker, editors, Logic
and Data Bases, pages 293–322. Plenum Press, New York, 1978.
[29] Martin Davis, George Logemann, and Donald Loveland. A machine program for
theorem proving. Communications of the ACM, 5(7):394–397, 1962.
[30] Yannis Dimopoulos, Bernhard Nebel, and Jana Koehler. Encoding planning problems
in non-monotonic logic programs. In Sam Steel and Rachid Alami, editors, Proceedings
of European Conference on Planning, pages 169–181. Springer, 1997.
[31] Thomas Eiter, Nicola Leone, Cristinel Mateis, Gerald Pfeifer, and Francesco Scarcello.
The KR system dlv: Progress report, comparisons and benchmarks. In Anthony
Cohn, Lenhart Schubert, and Stuart Shapiro, editors, Proceedings of International
Conference on Principles of Knowledge Representation and Reasoning (KR), pages
406–417, 1998.
[32] Esra Erdem and Vladimir Lifschitz. Fages’ theorem for programs with nested ex-
pressions. In Proceedings of International Conference on Logic Programming (ICLP),
pages 242–254, 2001.
[33] Esra Erdem and Vladimir Lifschitz. Tight logic programs. Theory and Practice of
Logic Programming, 3:499–518, 2003.
[34] Wolfgang Faber, Gerald Pfeifer, and Nicola Leone. Semantics and complexity of
recursive aggregates in answer set programming. Artificial Intelligence, 175:278–298,
2011.
[35] François Fages. Consistency of Clark’s completion and existence of stable models.
Journal of Methods of Logic in Computer Science, 1:51–60, 1994.
188 BIBLIOGRAPHY
[36] Paolo Ferraris. Answer sets for propositional theories. In Proceedings of International
Conference on Logic Programming and Nonmonotonic Reasoning (LPNMR), pages
119–131, 2005.
[37] Paolo Ferraris and Vladimir Lifschitz. Weight constraints as nested expressions. The-
ory and Practice of Logic Programming, 5(1–2):45–74, 2005.
[38] Richard Fikes and Nils Nilsson. STRIPS: A new approach to the application of
theorem proving to problem solving. Artificial Intelligence, 2(3–4):189–208, 1971.
[39] Kit Fine. The justification of negation as failure. In Proceedings of the Eighth Inter-
national Congress of Logic, Methodology and Philosophy of Science, pages 263–301.
North Holland, 1989.
[40] Raphael Finkel, Wiktor Marek, and Miroslaw Truszczynski. Constraint Lingo:
towards high-level constraint programming. Software: Practice and Experience,
34(15):1481–1504, 2004.
[41] John Franco and John Martin. A history of satisfiability. In Armin Biere, Marijn
Heule, Hans van Maaren, and Toby Walsh, editors, Handbook of Satisfiability, pages
7–74. IOS Press, 2009.
[42] Harold Fredricksen and Melvin Sweet. Symmetric sum-free partitions and lower
bounds for Schur numbers. Electronic Journal of Combinatorics, 7, 2000.
[43] Martin Gebser, Amelia Harrison, Roland Kaminski, Vladimir Lifschitz, and Torsten
Schaub. Abstract Gringo. Theory and Practice of Logic Programming, 15:449–463,
2015.
[44] Martin Gebser, Roland Kaminski, Benjamin Kaufmann, and Torsten Schaub. Answer
Set Solving in Practice. Synthesis Lectures on Artificial Intelligence and Machine
Learning. Morgan and Claypool Publishers, 2012.
[45] Martin Gebser, Marco Maratea, and Francesco Ricca. The design of the seventh
answer set programming competition. In Proceedings of the Fourteenth International
Conference on Logic Programming and Nonmonotonic Reasoning, pages 3–9. Springer,
2017.
[46] Martin Gebser, Max Ostrowski, and Torsten Schaub. Constraint answer set solving.
In Proceedings of 25th International Conference on Logic Programming (ICLP), pages
235–249. Springer, 2009.
[48] Michael Gelfond. Answer sets. In Frank van Harmelen, Vladimir Lifschitz, and Bruce
Porter, editors, Handbook of Knowledge Representation, pages 285–316. Elsevier, 2008.
BIBLIOGRAPHY 189
[49] Michael Gelfond and Yulia Kahl. Knowledge Representation, Reasoning, and the
Design of Intelligent Agents: The Answer-Set Programming Approach. Cambridge
University Press, 2014.
[50] Michael Gelfond and Vladimir Lifschitz. The stable model semantics for logic program-
ming. In Robert Kowalski and Kenneth Bowen, editors, Proceedings of International
Logic Programming Conference and Symposium, pages 1070–1080. MIT Press, 1988.
[51] Michael Gelfond and Vladimir Lifschitz. Logic programs with classical negation. In
David Warren and Peter Szeredi, editors, Proceedings of International Conference on
Logic Programming (ICLP), pages 579–597, 1990.
[52] Michael Gelfond and Vladimir Lifschitz. Classical negation in logic programs and
disjunctive databases. New Generation Computing, 9:365–385, 1991.
[53] Michael Gelfond and Vladimir Lifschitz. Representing actions in extended logic pro-
gramming. In Krzysztof Apt, editor, Proceedings Joint International Conference and
Symp. on Logic Programming, pages 559–573, 1992.
[54] Michael Gelfond and Yuanlin Zhang. Vicious circle principle and logic programs with
aggregates. Theory and Practice of Logic Programming, 14(4-5):587–601, 2014.
[55] Malik Ghallab, Dana Nau, and Paolo Traverso. Automated planning and acting.
Cambridge University Press, 2016.
[56] Herman Goldstine. The computer from Pascal to von Neumann. Princeton University
Press, 1973.
[57] Carla Gomes, Henry Kautz, Ashish Sabharwal, and Bart Selman. Satisfiability solvers.
In Frank van Harmelen, Vladimir Lifschitz, and Bruce Porter, editors, Handbook of
Knowledge Representation, pages 89–134. Elsevier, 2008.
[58] Cordell Green. Application of theorem proving to problem solving. In Proceedings
of International Joint Conference on Artificial Intelligence (IJCAI), pages 219–240,
1969.
[59] Steve Hanks and Drew McDermott. Default reasoning, nonmonotonic logics, and
the frame problem. In Proceedings of National Conference on Artificial Intelligence
(AAAI), 1986.
[60] Steve Hanks and Drew McDermott. Nonmonotonic logic and temporal projection.
Artificial Intelligence, 33(3):379–412, 1987.
[61] W.L. Harper, G.A. Pearce, and R. Stalnaker, editors. IFS: Conditionals, Belief,
Decision, Chance and Time. Springer, 1980.
[62] Amelia Harrison and Vladimir Lifschitz. Relating two dialects of answer set pro-
gramming. In Working Notes of the 17th International Workshop on Non-Monotonic
Reasoning, 2018.
190 BIBLIOGRAPHY
[63] Amelia Harrison, Vladimir Lifschitz, David Pearce, and Agustin Valverde. Infinitary
equilibrium logic and strongly equivalent logic programs. Arificial Intelligence, 246,
May 2017.
[64] Amelia Harrison, Vladimir Lifschitz, and Fangkai Yang. The semantics of Gringo
and infinitary propositional formulas. In Proceedings of International Conference on
Principles of Knowledge Representation and Reasoning (KR), 2014.
[65] Marijn Heule. Schur number five. In Proceedings of AAAI Conference on Artificial
Intelligence, 2018.
[66] Arend Heyting. Die formalen Regeln der intuitionistischen Logik. Sitzungsberichte
der Preussischen Akademie von Wissenschaften. Physikalisch-mathematische Klasse,
pages 42–56, 1930.
[67] Tomi Janhunen, Roland Kaminski, Max Ostrowski, Sebastian Schellhorn, Philipp
Wanko, and Torsten Schaub. Clingo goes linear constraints over reals and integers.
Theory and Practice of Logic Programming, 17:872–888, 2017.
[68] Carol Ruth Karp. Languages with expressions of infinite length. North-Holland,
Amsterdam, 1964.
[70] Henry Kautz and Bart Selman. Planning as satisfiability. In Proceedings of European
Conference on Artificial Intelligence (ECAI), pages 359–363, 1992.
[71] Daniel Korman, Erik Mack, Jacob Jett, and Allen Renear. Defining textual entail-
ment. Journal of the Association for Information Science and Technology, 69(6):763–
772, 2018.
[72] Michal Kouril. Computing the van der Waerden number W(3,4)=293. Integers, 2012.
[73] Robert Kowalski. The early years of logic programming. Communications of the
ACM, 31(1), 1988.
[75] Nicola Leone, Gerald Pfeifer, Wolfgang Faber, Thomas Eiter, Georg Gottlob, Simona
Perri, and Francesco Scarcello. The DLV system for knowledge representation and
reasoning. ACM Transactions on Computational Logic, 7(3):499–562, 2006.
BIBLIOGRAPHY 191
[76] Yuliya Lierler. SAT-Based Answer Set Programming1 . PhD thesis, University of Texas
at Austin, 2010.
[77] Yuliya Lierler and Vladimir Lifschitz. One more decidable class of finitely ground
programs. In Proceedings of International Conference on Logic Programming (ICLP),
2009.
[78] Yuliya Lierler and Vladimir Lifschitz. Termination of grounding is not preserved by
strongly equivalent transformations. In Procedings of International Conference on
Logic Programming and Nonmonotonic Reasoning (LPNMR), 2011.
[79] Vladimir Lifschitz. Thirteen definitions of a stable model. In Fields of Logic and Com-
putation: Essays Dedicated to Yuri Gurevich on the Occasion of his 70th Birthday,
pages 488–503. Springer, 2010.
[80] Vladimir Lifschitz. Intelligent instantiation and supersafe rules. In Technical Commu-
nications of the 28th International Conference on Logic Programming (ICLP), 2016.
[81] Vladimir Lifschitz, David Pearce, and Agustin Valverde. Strongly equivalent logic
programs. ACM Transactions on Computational Logic, 2:526–541, 2001.
[82] Vladimir Lifschitz, Lappoon R. Tang, and Hudson Turner. Nested expressions in logic
programs. Annals of Mathematics and Artificial Intelligence, 25:369–389, 1999.
[83] Vladimir Lifschitz and Hudson Turner. Splitting a logic program. In Pascal
Van Hentenryck, editor, Proceedings of International Conference on Logic Program-
ming (ICLP), pages 23–37, 1994.
[84] Fangzhen Lin and Yuting Zhao. ASSAT: Computing answer sets of a logic program
by SAT solvers. Artificial Intelligence, 157:115–137, 2004.
[86] John Lloyd and Rodney Topor. Making Prolog more expressive. Journal of Logic
Programming, 1:225–240, 1984.
[87] Jorge Lobo, Jack Minker, and Arcot Rajasekar. Foundations of Disjunctive Logic
Programming. MIT Press, 1992.
[88] Victor Marek and Miroslaw Truszczynski. Stable models and an alternative logic
programming paradigm. In The Logic Programming Paradigm: a 25-Year Perspective,
pages 375–398. Springer Verlag, 1999.
[89] John McCarthy. Programs with common sense. In Proceedings of the Teddington
Conference on the Mechanization of Thought Processes, pages 75–91, London, 1959.
Reproduced in [92].
1
http://www.cs.utexas.edu/users/vl/dissertations/lierler.pdf
192 BIBLIOGRAPHY
[92] John McCarthy. Formalizing Common Sense: Papers by John McCarthy. Ablex,
Norwood, NJ, 1990.
[93] John McCarthy and Patrick Hayes. Some philosophical problems from the standpoint
of artificial intelligence. In B. Meltzer and D. Michie, editors, Machine Intelligence,
volume 4, pages 463–502. Edinburgh University Press, Edinburgh, 1969.
[94] Arindal Mitra and Chitta Baral. Learning to automatically solve logic grid puzzles.
In Proceedings of the 2015 Conference on Empirical Methods in Natural Language
Processing, pages 1023–1033, 2015.
[96] Mark Nadel. Infinitary intuitionistic logic from a classical point of view. Annals of
Mathematical Logic, pages 159–191, 1978.
[97] Ilkka Niemelä. Logic programs with stable model semantics as a constraint program-
ming paradigm. Annals of Mathematics and Artificial Intelligence, 25:241–273, 1999.
[98] Ilkka Niemelä and Patrik Simons. Efficient implementation of the well-founded and
stable model semantics. In Proceedings Joint International Conference and Symposium
on Logic Programming, pages 289–303, 1996.
[99] Ilkka Niemelä and Patrik Simons. Extending the Smodels system with cardinality and
weight constraints. In Jack Minker, editor, Logic-Based Artificial Intelligence, pages
491–521. Kluwer, 2000.
[100] Monica Nogueira, Marcello Balduccini, Michael Gelfond, Richard Watson, and
Matthew Barry. An A-Prolog decision support system for the Space Shuttle. In Pro-
ceedings of International Symposium on Practical Aspects of Declarative Languages
(PADL), pages 169–183, 2001.
[101] David Pearce. A new logical characterization of stable models and answer sets. In
Jürgen Dix, Luis Pereira, and Teodor Przymusinski, editors, Non-Monotonic Exten-
sions of Logic Programming (Lecture Notes in Artificial Intelligence 1216), pages 57–
70. Springer, 1997.
[102] David Pearce and Gerd Wagner. Reasoning with negative information I: Strong nega-
tion in logic programs. Acta Philosophica Fennica, 49, 1990.
BIBLIOGRAPHY 193
[103] Edwin Pednault. ADL: Exploring the middle ground between STRIPS and the situ-
ation calculus. In Ronald Brachman, Hector Levesque, and Raymond Reiter, editors,
Proceedings of International Conference on Principles of Knowledge Representation
and Reasoning (KR), pages 324–332, 1989.
[104] Nikolay Pelov, Marc Denecker, and Maurice Bruynooghe. Well-founded and stable
semantics of logic programs with aggregates. Theory and Practice of Logic Program-
ming, 7(3):301–353, 2007.
[106] Raymond Reiter. On closed word data bases. In Herve Gallaire and Jack Minker,
editors, Logic and Data Bases, pages 119–140. Plenum Press, New York, 1978.
[107] Raymond Reiter. A logic for default reasoning. Artificial Intelligence, 13:81–132,
1980.
[108] Alan Robinson. A machine-oriented logic based on the resolution principle. Journal
of ACM, 12:23–41, 1965.
[109] Issai Schur. Über die Kongruenz xm + y m ≡ z m (mod p). Jahresbericht der Deutschen
Mathematiker-Vereinigung, 25:114–116, 1916.
[110] Rolf Schwitter. The jobs puzzle: Taking on the challenge via controlled natural
language processing. Theory and Practice of Logic Programming, 13(4,5):487–501,
2013.
[111] Dana Scott and Alfred Tarski. The sentential calculus with infinitely long expressions.
In Colloquium Mathematicae, volume 6, pages 165–170, 1958.
[112] Tran Cao Son and Enrico Pontelli. A constructive semnatic characterization of ag-
gregates in answer set programming. Theory and Practice of Logic Programming,
7:355–375, 2007.
[113] Leon Sterling and Ehud Shapiro. The Art of Prolog: Advanced Programming Tech-
niques. MIT Press, 1986.
[114] V.S. Subrahmanian and Carlo Zaniolo. Relating stable models and AI planning do-
mains. In Proceedings of International Conference on Logic Programming, pages 233–
247, 1995.
[115] Miroslaw Truszczynski. Connecting first-order ASP and the logic FO(ID) through
reducts. In Esra Erdem, Joohyung Lee, Yuliya Lierler, and David Pearce, editors,
Correct Reasoning: Essays on Logic-Based AI in Honor of Vladimir Lifschitz, pages
543–559. Springer, 2012.
194 BIBLIOGRAPHY
[116] Bartel Leendert van der Waerden. Beweis einer Baudetschen Vermutung. Nieuw
Archief voor Wiskunde, 15:212–216, 1927.
[117] Maarten van Emden and Keith Clark. The logic of two-person games. In Micro-
PROLOG: Programming in Logic, pages 320–340. Prentice Hall, 1984.
[118] Niklaus Wirth. Algorithms + Data Structures = Programs. Prentice Hall, 1976.
[120] Larry Wos, Ross Overbeek, Ewing Lusk, and Jim Boyle. Automated Reasoning: In-
troduction and Applications. Prentice Hall, 1984.
Index
195
196 INDEX
satisfiability solver, 12, 69, 152 turkey shoot, 139, 141, 142, 145, 150
satisfies, 62
Schur number, 40 underscore, 16, 31, 34
Schur numbers, 58
value of a ground term, 72, 73, 133
sensor, 45
van der Waerden number, 58
sequence covering array, 43
variable, 10, 16
set packing, 45, 59
anonymous, 31, 32
#show, 18 in the scope of negation, 32
simplification, 64, 65, 89 global, 29
skyscraper puzzles, 117 local, 29, 108, 116
Smodels, 12, 33, 34, 134 unsafe, 17, 33
social choice, 135 vertex coloring, see graph coloring
solving, 42 vertex cover, 51, 59
solving strategy, 42 vocabulary, 61
sorts, 135 voting, 120, 135
Space Shuttle, 152
splitting, 113 3-way bulb, 140–142, 147, 150
stability operator, 87
stable model, 11, 12, 61, 68, 83
infinite, 17, 18, 72, 77, 79
state, 137
strong negation, see negation, classical
#sum, 118, 134
sum of squares, 24
sum-free set, 38, 58
#sup, 17
symmetry breaking, 42, 123
tautology, 64
term, 16, 20, 133
textual entailment, 58
theorem
on completion, 105
on constraints, 90
on excluded middle, 88
on negative rules, 101
on reducts, 86
thread, 42
time, 140
traffic management, 59
transition diagram, 139, 150
truth table, see truth value
truth value, 61, 112