Event choice datalog

12
Event Choice Datalog: A Logic Programming Language for Reasoning in Multiple Dimensions Gianluigi Greco DEIS Universit ` a della Calabria 87030 Rende - Italy [email protected] Antonella Guzzo DEIS Universit ` a della Calabria 87030 Rende - Italy [email protected] Domenico Sacc ` a ICAR-CNR and DEIS, Univ. della Calabria 87030 Rende - Italy [email protected] Francesco Scarcello DEIS Universit ` a della Calabria 87030 Rende - Italy [email protected] ABSTRACT This paper presents a rule-based declarative database language which extends DATALOG to express events and nondeterministic state transitions, by using the choice construct to model uncertainty in dynamic rules. The proposed language, called Event Choice DATALOG (DATALOG !ev for short), provides a powerful mecha- nism to formulate queries on the evolution of a knowledge base, given a sequence of events envisioned to occur in the future. A distinguished feature of this language is the use of multiple spatio- temporal dimensions in order to model a finer control of evolution. A comprehensive study of the computational complexity of answer- ing DATALOG !ev queries is reported. Categories and Subject Descriptors I.2.3 [Artificial Intelligence]: Deduction and Theorem Proving— Logic Programming; D.3.2 [Programming Languages]: Lan- guage Classifications—Constraint and logic languages General Terms Languages Keywords Logic Programming, Knowledge Representation 1. INTRODUCTION Finding a suitable declarative framework for modeling and rea- soning about actions is a problem that has received a great deal of interest in the past years. Indeed, logic-based languages (see, e.g., [20, 43]) developed in the context of logics for knowledge representation might be profitably exploited for defining and solv- ing planning problems, that often arise in AI applications. Tradi- tional declarative approaches for planning fall into three distinct categories: situation calculus ([33]), temporal reasoning (see, e.g., [36]) and event calculus ([26]). Several recent proposals exploit, instead, logic programming and, specifically, the answer set pro- gramming paradigm for developing domain-independent planning Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, to republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee. PPDP’04, August 24–26, 2004, Verona, Italy. Copyright 2004 ACM 1-58113-819-9/04/0008 ...$5.00. languages [30]. Besides the very declarative modeling features of logic programming, the most interesting aspect is that, since an- swer sets represent the solution of the planning problem, planners may be easily implemented with the support of efficient answer set engines such as GnT [24], DLV [28], Smodels [41], DeReS [12], XSB [39], and ASSAT [31]. The language K [16] is a prototyp- ical representative of the languages exploiting such an approach. In fact, it is completely based on principles and methods of logic programming and its main feature is the ability of dealing with in- complete knowledge, i.e., of modeling scenarios when the designer has a partial knowledge of the world, only. One of the major limitations of the language K, as well as of most of logic-based languages for reasoning about actions, is the lack of an explicitly support for time, in the planning pro- cess. Moreover, the few logic-languages dealing with timed ac- tions rarely consider the possibility of dealing with multiple time or spatial units. Typically, they are suitable extensions of the event calculus (EC) [9]. Multiple time units are also called time granularities, in the tem- poral database community (see, e.g., [8]). The basic idea is to dis- tinguish a number of time dimensions at different scales, in order to model the validity of properties over coarser or finer time inter- vals. Note that the simple solution of mapping all dimensions into the finest scale does not always work, as the coarser dimensions may impose restrictions on time validity, and because it can lead to a tremendous blowup in the size of the problem instance. In summary, multiple time units can be profitably used for two main purposes: For modeling in a more natural way a large class of prob- lems, such as those involving planning tasks. In fact, it has been recognized that the ability to reason with multiple time granularities is an important feature, as all the human activ- ities are essentially related to multiple units, such as weeks, days, and hours. (See [8], for an overview of different pro- posals and the definition of a unifying model for multiple time granularities.) For dealing with plans at different levels of details. Each time dimension may be seen as a conceptual dimension, and we can employ a main dimension for reasoning about complex activities, and some auxiliary time dimension for modeling the execution of possible subtasks these activities are made of. Note that, since these subtasks are executed in a different dimension, they can be seen as instantaneous, as far as the main time scale is concerned. This can be particularly useful if, at the main activities level, we are only interested in the effects of subtasks, rather than on their temporal properties, as shown in a subsequent example.

Transcript of Event choice datalog

Event Choice Datalog: A Logic Programming Languagefor Reasoning in Multiple Dimensions

Gianluigi GrecoDEIS

Universita della Calabria87030 Rende - Italy

[email protected]

Antonella GuzzoDEIS

Universita della Calabria87030 Rende - Italy

[email protected]

Domenico SaccaICAR-CNR and

DEIS, Univ. della Calabria87030 Rende - Italy

[email protected]

Francesco ScarcelloDEIS

Universita della Calabria87030 Rende - Italy

[email protected]

ABSTRACTThis paper presents a rule-based declarative database languagewhich extendsDATALOG to express events and nondeterministicstate transitions, by using the choice construct to model uncertaintyin dynamic rules. The proposed language, called Event ChoiceDATALOG (DATALOG!ev for short), provides a powerful mecha-nism to formulate queries on the evolution of a knowledge base,given a sequence of events envisioned to occur in the future. Adistinguished feature of this language is the use of multiple spatio-temporal dimensions in order to model a finer control of evolution.A comprehensive study of the computational complexity of answer-ing DATALOG!ev queries is reported.

Categories and Subject DescriptorsI.2.3 [Artificial Intelligence ]: Deduction and Theorem Proving—Logic Programming; D.3.2 [Programming Languages]: Lan-guage Classifications—Constraint and logic languages

General TermsLanguages

KeywordsLogic Programming, Knowledge Representation

1. INTRODUCTIONFinding a suitable declarative framework for modeling and rea-

soning about actions is a problem that has received a great dealof interest in the past years. Indeed, logic-based languages (see,e.g., [20, 43]) developed in the context of logics for knowledgerepresentation might be profitably exploited for defining and solv-ing planning problems, that often arise in AI applications. Tradi-tional declarative approaches for planning fall into three distinctcategories: situation calculus ([33]), temporal reasoning (see, e.g.,[36]) and event calculus ([26]). Several recent proposals exploit,instead, logic programming and, specifically, the answer set pro-gramming paradigm for developing domain-independent planning

Permission to make digital or hard copies of all or part of this work forpersonal or classroom use is granted without fee provided that copies arenot made or distributed for profit or commercial advantage and that copiesbear this notice and the full citation on the first page. To copy otherwise, torepublish, to post on servers or to redistribute to lists, requires prior specificpermission and/or a fee.PPDP’04,August 24–26, 2004, Verona, Italy.Copyright 2004 ACM 1-58113-819-9/04/0008 ...$5.00.

languages [30]. Besides the very declarative modeling features oflogic programming, the most interesting aspect is that, since an-swer sets represent the solution of the planning problem, plannersmay be easily implemented with the support of efficient answer setengines such as GnT [24], DLV [28],Smodels[41], DeReS [12],XSB [39], and ASSAT [31]. The languageK [16] is a prototyp-ical representative of the languages exploiting such an approach.In fact, it is completely based on principles and methods of logicprogramming and its main feature is the ability of dealing with in-complete knowledge, i.e., of modeling scenarios when the designerhas a partial knowledge of the world, only.

One of the major limitations of the languageK, as well asof most of logic-based languages for reasoning about actions, isthe lack of an explicitly support for time, in the planning pro-cess. Moreover, the few logic-languages dealing with timed ac-tions rarely consider the possibility of dealing with multiple timeor spatial units. Typically, they are suitable extensions of the eventcalculus (EC) [9].

Multiple time units are also calledtime granularities, in the tem-poral database community (see, e.g., [8]). The basic idea is to dis-tinguish a number of time dimensions at different scales, in orderto model the validity of properties over coarser or finer time inter-vals. Note that the simple solution of mapping all dimensions intothe finest scale does not always work, as the coarser dimensionsmay impose restrictions on time validity, and because it can leadto a tremendous blowup in the size of the problem instance. Insummary, multiple time units can be profitably used for two mainpurposes:

¤ For modeling in a more natural way a large class of prob-lems, such as those involving planning tasks. In fact, it hasbeen recognized that the ability to reason with multiple timegranularities is an important feature, as all the human activ-ities are essentially related to multiple units, such as weeks,days, and hours. (See [8], for an overview of different pro-posals and the definition of a unifying model for multipletime granularities.)

¤ For dealing with plans at different levels of details. Each timedimension may be seen as a conceptual dimension, and wecan employ a main dimension for reasoning about complexactivities, and some auxiliary time dimension for modelingthe execution of possible subtasks these activities are madeof. Note that, since these subtasks are executed in a differentdimension, they can be seen as instantaneous, as far as themain time scale is concerned. This can be particularly usefulif, at the main activities level, we are only interested in theeffects of subtasks, rather than on their temporal properties,as shown in a subsequent example.

a b

c

a b c a

b

c a

b

a b c a

b

c a

b

c

a

b

c

move()@<S,1>

!move()@sub(S)

move()@<S,2> move()@<S,3>

done()

Figure 1: Blocksworld planning problem.

Note that the latter issue is also a viable way for planning inHierarchical Task Networks (HTNs) [38]. The HTN frameworkis an approach to planning where problem-specific knowledge isused to remedy the computational intractability of classical plan-ning. This knowledge comes in the form of task decompositiondirectives: the planner is given a set of methods telling how a high-level task can be decomposed into lower-level tasks. First attemptsto define languages able to explicitly deal with time and HTN plan-ning problems have been done in [19], where suitable extension ofthe Golog/ConGolog [29] languages (based on situation calculus)are designed.

In this paper we tackle the above knowledge representation is-sues in the logic programming context, and we propose a new lan-guage, called Event ChoiceDATALOG (DATALOG!ev for short), formodeling and querying action theories with different time granu-larities. The language can be used for defining declaratively sub-tasks that may eventually be combined in order to solve complexactivities, in a way that is completely transparent to the user. Wepoint out that combining programs (or program fragments) is notnatural in logic programming, as the union of two programs mayhave unexpected semantics. Conversely, an interesting peculiarityof DATALOG!ev is its modularity, which makes it useful for manyapplications, e.g., for the HTN planning. Indeed, note that any pro-gram performing some planning task can be reused in more com-plex systems, by making it working in a proper subunit of time,without any interference with previously defined modules.

We will show thatDATALOG!ev is well suited for modeling andreasoning about complex dynamic systems in real applicative sce-narios, and can be useful for simulation and design purposes.

1.1 Overview of the LanguageIn a nutshell,DATALOG!ev is a language for modeling the evolu-

tion of knowledge states, triggered by events and guided by nonde-terministic transition rules. Its main features are:

• Event Activation Rules: The language models transitionsamong states of the world by exploiting the notion of event,in the same spirit ofC [22]. The occurrence of an event en-ables the application of a rule that may modify the state byasserting or retracting some facts (fluents), and may triggerother events to occur in the future. The language also sup-ports the interaction with external events. This latter featureis particularly useful for simulating and reasoning about pos-sible scenarios, as we shall describe in our motivating exam-ples.

• Choice constructs: The ability to deal with the nondeter-minism has been recognized as a key feature of logic basedlanguages. However, an undisciplined use of unstratifiednegation and/or disjunction leads to higher computationalcomplexities and to hard-to-read programs. For this reason,

DATALOG!ev programs are stratified, but their rules may con-tain choiceatoms, that provide nondeterministic features. Inparticular, if we are not interested in a particular outcome(temporal evolution) of the program, thechoiceconstruct isable to model adon’t-careform of nondeterminism.

Thus,DATALOG!ev combines the capability of thechoicecon-struct to express nondeterminism (possibly,don’t-care nondeter-minism), with theevent activation rules, used for modeling eventsoccurring at certain specified time instants. Moreover, one canmake queries on possible future states of the knowledge base, givensome list of events that are envisioned to happen. In the rest of thissection, we give a brief overview of the language by considering anexample of complex planning problem. We present this examplein two steps, starting from the classicalBlocksworldproblem [40],and then exploiting its encoding as a subtask of a more involvedplanning problem. In a subsequent section, we will also show an-other application in a different domain.

1.1.1 Planning with Events and ChoiceWe have a table and a set of blocks. The table can hold arbitrarily

many blocks, while each block can hold at most one other block.Initially, blocks a andb are on the table, while blockc is in thetop of a. We can move a block at a time to the table or on the topof another block, provided that its top is empty. We want to find asequence of moves leading to the configuration in whicha is on thetable,b is on the top ofa, andc on the top ofb — see Figure 1.

The first component of aDATALOG!ev program used for model-ing such program is thebackground knowledgeexpressed as a setof facts, denoted byEDB (extensional database), which are assumedto do not change over the time. These facts specifies the objects in-volved in the modelled domain. In our example,EDB consists ofthe facts

block(a). block(b). block(c).

The second component is a set of fluents, denoted byDDB (dynamicdatabase). These facts can be dynamically asserted or retracted dur-ing the time, on the basis of the occurrence of events. In the exam-ple, we can assume to have dynamic facts of the formon(X, Y),which specifies that blockX is on the top ofY. E.g., the initial sce-nario shown in the leftmost part of Figure 1 is represented by thefollowing DDB

on(a, table). on(b, table). on(c, a).

The third component is a set of dynamic rules, denoted byD-KB (dy-namic knowledge base). These rules are essentially datalog rules(possibly with stratified negation) whose predicates are equippedwith a time argument. Rules inD-KB are used for expressing prop-erties that depend on the time, and hence they may relate status ofthe world at different time units. For instance, a rule of the form

p(X)@T ← q(X)@(T+2) imposes that predicatep(X) is true twoinstants of time after predicateq(X) is. In the special case that allpredicates in a dynamic rule deal with the same time instant, sucha rule can be used for representingstatic knowledge, i.e., invariantover the time – in these cases, the time argument is often strippedoff. For instance, in our running example,D-KB contains the rules

fixed(B) ← on(B′, B), block(B).goodLocation(D) ← block(D), ¬fixed(D).goodLocation(D) ← D = table.

done() ← on(a, table), on(b, a), on(c, a).

Intuitively, fixed(B) is false at any given timeT if the blockB hasno other block on the top of it and, hence, it can be freely moved;goodLocation(D) is true if eitherD is the table or a block withoutblocks on it;done is true if the desired final condition has beenreached.

The most important component of our language consists in thespecification of theevent activation rules. These rules state thatwhenever a given event is (internally or externally) triggered, a setof actions will be performed. In our example, we only consider anevent requiring the move of a block.[move()@T]

!move()@(T+ 10),−on(S, X), +on(S, D) ← ¬done(),

on(S, X), ¬fixed(S),goodLocation(D), D 6= S,

choiceAny().

Intuitively, whenmove is triggered at timeT, we check for the con-dition in the body of the rule. Notice that the predicates in this bodydo not have an explicit time argument; we will use such a shorthandin the case the time arguments are the same as the triggering timeof the event, i.e., if we are looking at the state of the world at thetime the event occurs. Specifically, in the above rule, we checkwhether the planning has not been yet completed (done() is false),and whether there is a blockS that can be moved on the top of agood location. Obviously, there are several possible choices, i.e.,several blocks can be moved to several locations. Then, the predi-catechoiceAny() is a directive of our language ensuring that onlyone of these possibilities is non-deterministically chosen. After thechoice is done, the status of the world is updated according to thehead of the rule, that is,on(S, X) is retracted andon(S, D) is as-serted for representing the move ofS. Moreover, since we have notyet completed the planning, the eventmove() is internally triggeredagain. If we assume that such moves require ten time units, e.g., tenseconds, then we may trigger this event at time (T+ 10).

The interesting feature of the above formalization is that the userwrites simple rules involving non-deterministic actions. The focusin writing DATALOG!ev programs goes only in properly definingone step of transition only. Then, the non-deterministic transitionsensure that all the possible evolutions can be considered. Note thatin this example we are interested in those particular sequences ofmoves leading to the achievement of the goal. This can be easilyspecified by means of the last component ofDATALOG!ev i.e., itsquery language. In order to query a program, we have to specify aset of (external) events that are envisioned to happen. In our case,this list consists of the single eventH = [move()@0], specifyingthat the planning starts at time0. Then, a query of the formQ =∃@tdone() will be true iff there exists a possible way for achievingthe desired final condition within timet. As we can see from Figure1, this query will be evaluated true for anyt ≥ 30 (seconds). Wenext see how the blocksworld problem can be reused for solving asubgoal of a more complex planning problem.

BW

OUT

0,0

8,6

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

aaaaaaaaaaaaaaaa

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Figure 2: Labyrinth.

1.1.2 Multidimensional PlanningLet us consider a complex scenario, where we have to control a

robot that enters a labyrinth (the grid in Figure 2) and should findthe exit within a given time bound. In our example, the robot isin the position(0, 3) and must arrive in position(4, 0). As far asthis “main” problem is concerned, we are only interested in count-ing the number of steps in the robot’s escaping path, so that wecare only at the spatial dimensions — for instance, we may want tominimize the length of the path. Therefore, in this case, the maindimension is the space or, equivalently, the number of steps, ratherthan the time.

To make this example more realistic, we consider the case wheresome walls may be removed by the robot, in order to pass acrossthem. However, this removal is not trivial. Rather, it involves thesolution of a blocksworld problem, modeling the feasible ways ofbreaking the wall. For instance, in Figure 2, we allow the robotto pass across the wall in position(6, 5), if it is able to solve aninstance of the blocksworld problem associated with this positionin at most 30 seconds. Thus, as far as these subtasks are concerned,we are interested in actual time dimensions.

It is worthwhile noting that this scenario is prototypical of allthose situations where we have to realize some goals involving theachievement of further (sub-)goals. Our encoding of this problemshows howDATALOG!ev allows us to reuse in a simple way theprogram that models the blocksworld problem as a module of thefull robot program. Moreover, note that we deal here with twodimensions: the length of the path and the execution time of thesubtasks.

The static knowledge consists of facts of the formwall(X, Y),asserting the presence of a wall in the position of coordinates(X, Y).

The dynamic databaseDDB comprises an atompos(X, Y) that de-fines the current position of the robot in the labyrinth (initially, weassertpos(0, 3)), and atoms of the formmovableWall(X, Y), as-serting the presence of a removable wall, which can be traversed bysolving an instance of the blocksworld problem. (E.g., in Figure 1,movableWall(6, 5) is in DDB.)

Moreover,D-KB consists of the rules

arrived() ← pos(4, 0).walk(n, X, Y + 1) ← pos(X, Y), Y < 6,¬wall(X, Y + 1).walk(s, X, Y− 1) ← pos(X, Y), Y > 0.¬wall(X, Y− 1).walk(w, X− 1, Y) ← pos(X, Y), X > 0.¬wall(X− 1, Y).walk(e, X + 1, Y) ← pos(X, Y), X < 8.¬wall(X + 1, Y).

The first rule is used for determining whether the tasks of the robothas been accomplished. Predicatewalk contains instead the nextlocation of the robot after a walk — notice, that we check whether

the next location is admissible, i.e., if it falls within the grid and ifit is not in a place where a wall is.

Finally, the walk of the robot is controlled trough events of theform pathFinder()@S, whereS is the step of the path. Such anevent activates two transition rules, as shown below:

[pathFinder()@S]!pathFinder()@S++,

−pos(X, Y),+pos(XN, YN) ← ¬arrived(),

walk(D, XN, YN), pos(X, Y),¬movableWall(X, Y),choiceAny().

!move()@sub(S),!toBeCompleted(X, Y)@〈S, 30〉 ← movableWall(X, Y).

The first transition rule selects a new feasible position for therobot (i.e., a position such thatwalk(D, XN, YN) is true), if therobot is not arrived at the exit and is not in a position correspond-ing to a movable wall. Note that this selection is performed non-deterministically, by means of thechoiceAny() construct. Then,the robot position is updated and a new eventpathFinder is trig-gered for the successive step, denoted byS+ + (shorthand for(S+ 1)).

The second transition rule deals with the case where the robotencounters a movable wall, and thus we have to trigger the execu-tion of a planning procedure in charge of removing the wall blockswithin a certain time (in our case, 30 seconds). This task is accom-plished in a finer temporal dimension, whose events and operationsare seen as instantaneous as far as the higher dimension is con-cerned. Thus, in the latter sub-dimension we take care of the timebounds for the obstacle removal, while in the main dimension wetake care of the steps only. The picture is completed by the fol-lowing event activation rule, which checks that the robot has suc-cessfully completed its wall removal operation, at the timestamp(in our case,T = 〈S, 30〉) where the eventtoBeCompleted(X, Y)is triggered:

[toBeCompleted(X, Y)@T]!pathFinder()@sup(T),−movableWall(X, Y) ← done().

Note that thisDATALOG!ev program specifies just the rules ofevolution of the system (in this case, of the robot state). Then, weexploit theDATALOG!ev query language in order to find out thedesired evolutions, and hence the moves for reaching the goal. Inour example, the query∃@12arrived() is true if it is possible tofind a path leading to the exit in 12 steps, possibly including somecomplex steps involving blocksworld.

1.2 OrganizationThe paper is organized as follows. Some preliminaries on

DATALOG are reported in Section 2. We introduce the multidi-mensional time domain in Section 3, while in Section 4 we presentthe syntax ofDATALOG!ev. In the subsequent section, we illustrateits model theoretic semantics, by introducing the notions oftem-poral andstationarymodel. In Section 6, we formulate queries onDATALOG!ev programs and analyze their complexities. Finally, inSection 7, we present related work, discuss the main novelties ofour language, and draw our conclusions.

2. PRELIMINARIESA Datalog programP is a finite set of rulesr of the form

H(r) ← B(r), whereH(r) is an atom (headof the rule) andB(r)

is a conjunction of literals (bodyof the rule). A rule with emptybody is called afact. Theground instantiationof P is denoted byground(P); the Herbrand universeand theHerbrand baseof Pare denoted byUP andBP , respectively.

Let an interpretationI ⊆ BP be given — with a little abuse ofnotation we sometimes seeI as a set of facts. Given a predicatesymbolr in PD, I(r) denotes the relation{t : r(t) ∈ I}. More-over,pos(P, I) denotes the positive logic program that is obtainedfrom ground(P) by (i) removing all rulesr such that there existsa negative literal¬A in B(r) andA is in I, and (ii) by removingall negative literals from the remaining rules. Finally,I is a (total)stable model[20] if I = T

pos(P,I)(∅), i.e., it is the least fixpointof the classicalimmediate consequence transformationfor the pos-itive programpos(P, I). The set of all the stable models of a givenprogramP is denoted bySM(P).

Given a programP and two predicate symbolsp andq, we writep → q if there exists a rule whereq occurs in the head and there isa predicate in the body, says, such that eitherp = s or p → s. P

is stratified if for eachp andq, if q → p holds, then¬p does notoccur in the body of any rule whose head predicate symbol isq, i.e.there is no recursion through negation. The class of allDATALOGprograms is simply calledDATALOG; the subclass of all stratifiedprograms is calledDATALOG¬s .

Note that stratified programs have a unique stable model thatcan be computed in polynomial time. However, they allow us toexpress only deterministic queries. If we need the ability to dealwith nondeterminism, we have to use programs with unstratifiednegation. Unfortunately, in this case, the complexity is higher andsometimes programs become hard to read.

A solution to such drawbacks of negation is disciplining its use,by adding to the basic stratified language some special constructthat provides nondeterministic features. In this paper, we considerthechoiceconstruct [37], that allows us to express choices in logicprograms, by enforcing functional dependency (FD) constraints onthe consequences of rules.

Let achoice ruler with a choice construct – in general a choicerule may contain more than one choice construct in the body butfor this paper one will be enough – be given:

r : A ← B(Z), choice((X), (Y )).

where, B(Z) denotes the conjunction of all the literals in thebody of r that are not choice constructs,Z is the list of all vari-ables occurring inB, andX, Y denote lists of variables such thatX ∩Y = ∅ andX, Y ⊆ Z — note thatX can be empty and in thiscase, it is denoted by “()”. The constructchoice((X), (Y )) pre-scribes that the set of all consequences derived fromr, sayR, mustrespect the FDX → Y . Thus, if two consequences have the samevalues forX but different ones forY then only one consequence,nondeterministically selected, will be eventually derived.

We denote bychoiceAny() the constructchoice((), (Z)) thatnondeterministically selects one consequence, whereZ is the listof all variables occurring in the rule body, according to the meaningof the FD∅ → Z.

A DATALOG programP with choice rules is called anextendedchoice program. We say thatP is stratified modulo choice(or sim-ply stratified) if, by considering choice atoms as extensional atoms,the program results stratified.

3. MULTIDIMENSIONAL DOMAINSIn this paper we consider a multidimensional model of time, that

allows us to consider different level of details, often called granu-larities in the literature – see [23] and [8].

Each timeinstant is a tuple〈t1, ..., tn〉, wheren is thecurrentdimensionof this instant and eachti is a natural number. The time〈0〉 is a distinguished element standing for thebeginning of thetime, and is denoted by0. A (multidimensional) time domainTis a set of time instants.

Note that this notion of time is very general, as we have just con-ceptual dimensions, which can model any desired level of detailsin reasoning about events. For instance, we can employ a maindimension for reasoning about some complex activities, and oneauxiliary time dimension for modeling the execution of the varioussubtasks such activities are made of. Note that these subtasks takein fact some time to be executed, but they can be seen as instan-taneous, as far as the main time scale is concerned. This can beparticularly useful if, at the complex activities level, we are onlyinterested in the effects of subtasks, rather than on their detailedtemporal succession.

We often impose some restriction on the set of time instants,either on the number of dimensions, or on the range of each di-mension. For instance, the usual notion of time (in every-day life)is modelled as a multidimensional time domain, where we have amain infinite dimension (encoding, e.g., the number of years afterChrist) and a number of bounded range sub-dimensions (encoding,e.g., days, hours, minutes, and seconds). We denote byT ω1,m thistemporal domain. Moreover, we denote byTn,m a time domain hav-ing the number of dimensions bounded by some numberm andeach dimension counts at mostn time instants (range of the dimen-sion), for some numbern > 0; Tω,m has infinite temporal rangesover a finite set of dimensions;Tn,ω has infinite set of dimensionswith bounded ranges.

All time domainsT are linearly ordered according to the usuallexicographic precedence relationship, that we denote by≺. Wealso equip time domains with temporal functions, for incrementingor decrementing the current time of a given amount of time units.

Definition 3.1 Let T be a time domain. Then, to each time instantt = 〈t1, ..., tn−1, tn〉, we can apply one of the following operators,also calledtemporal functions overT:

• t + k, with k ≥ 0 natural number, that increments (if possible)the time in the current dimensionn of k units, i.e., it outputs〈t1, ..., tn + k〉; if the incrementk is not possible, because ofsome bound on the current dimensionn, thent+ k is undefined.

• t − k, with k ≥ 0 natural number, that decrements (if possi-ble) the time in the current dimension ofk units, i.e., it outputs〈t1, ..., tn − k〉; if tn < k, thent− k is undefined.

• sup(t), which is defined if the current dimensionn is greaterthan1, and returns the time instantsup(t) = 〈t1, ..., tn−1 + 1〉,i.e., it projectst onto the preceding dimensionn − 1 and incre-ments the time in that dimension.

• sub(t), that outputs〈t1, ..., tn−1, tn, 0〉, i.e., it creates (if possi-ble) a new time dimension; ifn is the maximum allowed numberof dimensions inT, sub(t) is undefined.

• t, i.e., theidentityfunction.

Moreover,t++ andt-- are shorthand fort + 1 andt− 1, respec-tively. 2

The above functions is all we need for reasoning about eventswith the language we present in this paper. Note however that manyother complex temporal operators have been proposed for differentpurposes in the literature (e.g., the operators for converting timeinstants and scaling intervals [15]).

4. EVENT CHOICE DATALOGIn this section we presentEvent ChoiceDATALOG (short:

DATALOG!ev), an extension ofDATALOG that is able to deal withevents and dynamic knowledge, in a temporal framework with mul-tiple dimensions.

4.1 SyntaxRoughly speaking, allDATALOG!ev predicates are enriched with

an additional argument that provides the time dimension: for anyliteral p and each time instantt, p@t is true ifp holds at timet.

We assume that three sets of constants, variables, and time vari-ables symbols,σconst , σvars, andσtime vars are given, where theconstants symbols are disjoint from the (time) variables symbols.Moreover, letT be a time domain.

A term s is an element inσconst ∪ σvars. Moreover, letσEDB,σDDB, σIDB, andσEV be disjoint sets of predicate symbols, with as-sociated arity (≥ 0). Then, anEDB atom has a ”classical” for-matp(s1, . . . , sn) wherep is a symbol inσEDB ands1, . . . , sn areterms. InsteadDDB (dynamic extensional predicates),IDB (inten-sional predicates), andEV (event predicates) atoms are of the formp(s1, . . . , sn)@f(t), wherep is a symbol inσDDB, σIDB, σEV), re-spectively,n is the arity ofp, s1, ...sn are terms,f is a temporalfunction over the domainT, andt is a time instant or a time vari-able inσtime vars.

An EDB,DDB,IDB, orEV literal is either an atom or its negation.The set of all theEDB literals (resp.DDB, IDB, EV), is denoted byLEDB (resp. LDDB, LIDB, LEV). Furthermore, for any set of literalsL, L+ andL− denote the sets of its positive and of its negativeliterals, respectively.

Definition 4.1 A dynamicrule has the formp(X1, ..., Xn)@T ←B1, ..., Bm. wherep(X1, ..., Xn)@T ∈ L+

IDB, m ≥ 0, andB1, ..., Bm ∈

LEDB ∪ LDDB ∪ LIDB. An event activationrule has the followingformat:

[e(X1, ..., Xn)@T] TR1 ... TRk

wheree(X1, ..., Xm)@T ∈ L+EV

, andTR1, ..., TRk aretransition rules.Each transition rule is of the form

!EV1@f1(T), ..., !EVn@fn(T),+A1, ..., +Ah,−Ah+1, ...,−Aℓ ← B1, ..., Bm, C.

wheren+ ℓ > 0, EV1, ..., EVn ∈ L+EV

, m ≥ 0, A1, ..., Ah, Ah+1, ..., Aℓ

∈ L+DDB

, B1, ..., Bm ∈ LEDB∪LDDB∪LIDB, f1, .., fn are temporal func-tions, andC is an optional choice atom in{choice, choiceAny}. 2

The informal semantics of an event activation rule is that, if theevente(X1, ..., Xn) occurs at timet ∈ T and the body of the tran-sition rule is evaluated true, then the factsA1, ..., Ah are asserted attime t, the factsAh+1, ..., Aℓ are retracted at timet, and the eventsEV1, ..., EVn are triggered to be executed at timesf1(t), ..., fn(t).

Definition 4.2 Let us assume a time domainT and a set of knowl-edge baseEDB predicates are given. Then, aDATALOG!ev programPT = 〈D-KB, EV〉 over T and σEDB consists of a setD-KB of dy-namic rules, calleddynamic knowledge base, and a setEV of eventactivation rules. If the time domain is clear from the context, theprogram will be denoted simply byP. The set of allDATALOG!ev

Release

Tool

Release

Tool

Receive

Order

Receive

OrderCheck

Requirements

Check

Requirements

Accept

Order

Accept

Order

Refuse

Order

Refuse

Order

Requirement

Analysis

Requirement

AnalysisImplementationImplementation

Verify

Client

Verify

Client

Verify

Staffing

Verify

Staffing

OK

OK

FailiureFailiurenotOK

notOK

notOK

!init(P)@T

end(P)

!leave(E)@T

received

verifiedClient

Figure 3: Project management.

programs whose dynamic knowledge base is stratified is denotedby DATALOG!ev,¬s .

If we are additionally given an extensional databaseEDB overσEDB encoding the (static) initial knowledge we are interested in,then we denote byPT

EDB the programPT ∪ {p ←| p ∈ EDB}, i.e.,the program obtained by adding a fact for each atom inEDB. 2

4.2 Modeling Dynamic SystemsWe next illustrate the peculiarities ofDATALOG!ev in modeling

complex dynamic systems. Assume that you are the project man-ager of a software house and your clients ask you to implementnovel tools. In order to supply each request, you might think at ac-tivating a project involving some employees. However, if you findthat this is either not convenient for your company or not possiblesince you do not have employees enough to guarantee the actual im-plementation of the tool, you might also refute the order. Figure 3shows a possible workflow implementing the project managementprocess. The process is quite complex because it involves severalsubtasks, each one activated by events triggered by previous tasks— denoted in the figure by labels over the arcs. We next presentsome guidelines on building aDATALOG!ev programPpm for mod-eling this process.

The first event (init), causing the activation of the process, isan external one and occurs when an order is received. In fact, thisevent is responsible for the execution of theReceive Ordertask inwhich some preliminary activities, such as storing of client data,have to be performed. This can be modelled by means of an eventactivation rule of the form

[init(P)@(T)]!receiveOrder(P)@T++ ←

The taskReceive Ordernotifies its completion trough the acti-vation of the eventreceived, which in its turn activates the taskCheck Requirements:

[received(P)@T]!checkRequirements(P)@T++ ←

In case you find the order not convenient, theCheck Requirementtask notifies thenotOK event to therefuse Ordertask:

[notOK(P)@T]!refuseOrder(P)@T++ ←

Otherwise, the eventOK will lead to the acceptance of the order:[OK(P)@T]

!acceptOrder(P)@T++ ←

If the order is accepted, you will start the actual realization andyou will eventually release the tool. Here, we consider just twophases:Requirement AnalysisandImplementation. Notice that, inthe latter task, it might happen that some employee leave the com-pany, represented by means of the external eventleave, possiblycausing the failure of the project.

After the skeleton of the process is designed by means of theabove event activation rules,DATALOG!ev can be used for mod-eling in simple and natural ways the different subtasks discussedabove. In Figure 3, we have reported only some details for theCheck Requirementtask. Essentially, it comprises a check for thereliability of the client, which can be modelled as follow:

[checkRequirement(P)@T]!verifyClient(P)@T++ ←

The activityverifyClient is not further described here. We justassume that if the client is not reliable, it will eventually triggerthe eventnotOK (causing the rejection of the order); otherwise itwill trigger the eventverifyStaffing, that is responsible for thestaffing of employees in the project:

[verifyStaffing(P)@T]!staff(P)@sub(T) ←

Staffing a project is another complex task, which is executed intoa new conceptual dimension as described next. Each projectpi re-quires some specific skills, and thus the company has to assign asuitable set of employees to the project, such that all the requiredskills are granted topi. Of course, once an employee is assigned toa project team, she is not available for another project until the cur-rent one has been ended. Then the staffing must be also planned,since the management has to make a sequence of choices for se-lecting the employees to be included in the team. However, at thelevel of projects execution times, the details about such sequencesof choices are not relevant, and hence it should be done in a con-ceptual finer dimension. Rather, it is crucial that this process iscorrectly performed, according to the following constraints: (i) anemployee can be assigned to one project at a time, (ii) for each skill

required in a project, one employee must be present in the workingteam. A project isstaffedif both the above conditions are satisfied.

We next define someDATALOG!ev rules encoding our staffingproblem and give just a flavor of its meaning, as the semantics ofthe language is formally presented in the next section. Figure 4shows a possible extensional databaseEDB encoding the informa-tion about projects and employees in our project management ex-ample. For instance, we can see that projectp1 must be completedwithin four time units and requires a developer and a consultant,that employeee1 has the skills1 (developer), etc. Then,Ppm con-tains a set ofDDB factsinTeam(Project#, Employes#)@t toencode the fact that an employee is enrolled in a project at sometimet. The followingD-KB rules determine whether a projectP isstaffed at a timeT .staffed(P) ← project(P, ), ¬missingSkill(P).missingSkill(P) ← requiredSkill(P, S, ),

¬skillInP(S, P).skillInP(S, P) ← inTeam(P, E), employee(E, S, ).

Moreover, the program also contains the following rules for infer-ring the employees that are not currently involved into any project,and whose skills are still missing.candidate(E, P) ← employee(E, S), ¬inSomeTeam(E),

requiredSkill(P, S, ),¬skillInP(S, P).

inSomeTeam(E) ← project(P, ), inTeam(P, E).moreCandidates(P) ← candidate(E, P).

The only event transition rule for the staffing problem has beenalready shown in Figure 3. Roughly speaking, thestaff eventis responsible for choosingnon-deterministicallyan employee forthe inclusion in the project having a skill that is still missing inthe staffing. When the project is staffed the eventOK is eventuallytriggered. Otherwise, i.e., if there are no more candidates and theproject is not yet staffed, thennotOK is triggered.

Finally, at the end of the project we release the team members(note that, in this case, we do not choice a particular employee, andin fact we want to delete all the employees in the team). This way,these employees may be enrolled in a further project.

[end(P)@T]−inTeam(P, E) ← inTeam(P, E).

It is worthwhile noting that, as several projects may be initial-ized, the staffing activities can be thought as concurrent processesthat share the same resources (the employees). It follows that, ingeneral, there exists bad combinations of choices such that someproject may not be staffed.

Since the incomes are mainly due to the ability of properly man-aging the projects, you might think at developing a simulation en-vironment that can help your decision.DATALOG!ev might helpyour job by means of its powerful query language described in Sec-tion 6. In fact, after the process is modelled, as we shall show, youmay query the program for verifying whether there exists a properstaffing that guarantees the satisfaction of the whole order (and,obviously, for computing such aplan). Similarly, you may alsoidentify those employees which are crucial for the implementationof a tool, i.e., the employees that will cause a failure of the projectif they leave the company.

5. SEMANTICSLet PT

EDB = 〈D-KB, EV〉 be aDATALOG!ev program, over a timedomainT and a knowledge baseEDB. As usual, theHerbrand Uni-verseUPT

EDB

of aPT

EDB is the set of all constants appearing inPT

EDB.

requiredSkill:

P# Skill# Descriptionp1 s1 developerp1 s2 consultantp2 s1 developerp2 s3 researcher

project:P# Durationp1 4p2 5

employee:

E# Skill#e1 s1

e2 s1

e2 s2

e3 s3

Figure 4: An extensional databaseEDB for the program Ppm.

A dynamic literal (resp., an event) inLDDB ∪ LIDB (resp. inLEV)is ground if no variable occurs in it. TheEDB (resp.DDB, IDB, EV)Herbrand Base, denoted byBEDB (resp.BDDB, BIDB, BEV), is the setof all ground extensional (resp., dynamic fact, intensional, event)literals that can be constructed with the predicate symbols inσEDB

(resp.,σDDB, σIDB, σEV), by replacing the variables inσvars by con-stants in the Herbrand universe and the time variables inσtime vars

by time instants inT.

Definition 5.1 An interpretationfor the programPT

EDB consists ofa pair〈S, E〉, whereS is a set of ground literals andE is a set ofground events, such that

S ⊆ BEDB ∪ BIDB ∪ BEV ∪ BDDB

E ⊆ B+EV

The minimum temporal argument occurring in the events inE isdenoted bynextTime(I), while the maximum temporal argumentoccurring in the predicates inS is denoted bycurTime(I). Fi-nally, an interpretationI is feasibleif E = ∅ or curTime(I) ≺nextTime(I). 2

Intuitively, a feasible interpretationI determines a truth valuefor all the predicates preceding the timecurTime(I), and containsthe information on the events that are currently triggered to occurin the future. In particular, a groundIDB or EDB predicate is truew.r.t. I if it is an element of it; a dynamic ground factp@t is truew.r.t. I if there exists an elementp@t′ in I such thatt′ ¹ t, andthere is no literal¬p@t′′ ∈ I such thatt′ ≺ t′′ ≺ t.

Note that in the above definition, we assume that anyDDB pred-icate asserted at a given time, remains valid till it is explicitly re-tracted from the database; indeed, the behavior of theDDB predi-cates is essentiallyinertial, while the truth value of theIDB predi-cates must be determined at each time instant.

Finally, the special choice literals are defined to be always truew.r.t. to any possible interpretationI, regardless whether they occuror not inI.

We say that a ground transition ruletr is enabledif all the literalsoccurring in the body oftr are true with respect toI.

Example 5.2 Let us consider again the project management plan-ning problem. Then,

I1 = 〈{staffable(p1, e1)@3, inTeam(p2, e3)@5},{end(p1)@8}〉

and

I2 = 〈{inTeam(p2, e3)@8,¬inTeam(p2, e4)@5},{end(p2)@2, end(p1)@9}〉

are both interpretations. However, the latter is not feasible sincenextTime(I2) = 2 andcurTime(I2) = 8. Moreover, note thatin the former interpretation the predicateinTeam(p2, e3) is true in

every time instant following5, since it has been never retractedafter its assertion at time5. 2

Given an interpretationI = 〈S, E〉, we denote bytriggered(I)the set of all events inE having temporal argumentnextTime(I),in the casenextTime(I) ∈ T; otherwise, we lettriggered(I) = ∅.Let TR(I) be the set of all transition rules such that all their ac-tivating events belong totriggered(I), andC(I) be the set of allchoice predicates occurring in the rules inTR(I). Moreover, letground TR(I) be the set of all the ground instantiationsR of therules inTR(I) such that (i) all transition rules inR are enabled,and (ii) the functional dependencies determined by the choice con-structs inC(I) are satisfied byR. Thus,ground TR(I) containsa set of enabled ground rules (coming from instantiations of therules inTR(I)) for each possible way of enforcing the functionaldependencies determined by the choices inC(I).

Let chosen tr be any set of ground rules inground TR(I). Wedenote byAI(chosen tr) the set of all the dynamic atomsp suchthat +p occurs in the head of some transition rule inchosen tr

andp is false w.r.t. I. Such a dynamic atomp is said to be as-serted. Similarly,RI(chosen tr) is the set of all the dynamic lit-erals¬p such that−p occurs in the head of some transition rule inchosen tr andp is true w.r.t.I. In this case, we say thatp has beenretracted. Finally,EI(chosen tr) is the set of the events triggeredby all transition rulesr in chosen tr such that at least one dynamicatom is either asserted or retracted because ofr.

In the sequel, the set of all the interpretations of a given programP is denoted byIP , while the set of all the subsets ofIP is denotedby 2IP .

Definition 5.3 Let P = 〈D-KB, E〉 be an event choice Datalog pro-gram. Then, we defineT : 2IP 7→ 2IP to be the functionthat, given a set of interpretationsI, outputs a set of interpre-tationsT(I) containing, for anyI = 〈S, E〉 ∈ I and any set oftransition ruleschosen tr ∈ ground TR(I), all interpretations〈S′, E′〉 such that

S′ ∈ SM(D-KB ∪ S ∪ AI(chosen tr) ∪RI(chosen tr))∪∪triggered(E), and

E′ = E ∪ EI(chosen tr) − triggered(E). 2

Note that, for any given interpretationI = 〈S, E〉, this functioncomputes the set of all feasible interpretations that can be obtainedby triggering events and by asserting or retracting predicates, ac-cording toI. Note that any output interpretationI ′ = 〈S′, E′〉takes into account the consequences of the events triggered at thetime nextTime(I). All these events are removed from the set ofenvisioned eventsE′, while new events possibly planned to occurin the future are added toE′ through the setEI(chosen tr). ThesetS′ is any stable model of the dynamic knowledge baseD-KBevaluated overS plus the asserted and retracted predicates, and in-cluding the recently occurred events, too.

We point out that, as a consequence of the non-deterministicchoice constructs, the output ofT applied on a singleton{I} isin general a set of multiple alternative interpretations, even in thecase the dynamic knowledge base is stratified (DATALOG!ev,¬s pro-gram). However, it deterministically outputs a unique interpreta-tion (for the givenI) if the program is stratified and there are no“active” choices, i.e.,C(I) = ∅.

Definition 5.4 Let P be aDATALOG!ev program,EDB be an inputdatabase, andH a list of ground events, also calledlist of envisionedevents. Theevolutionof the programP givenEDB andH (short: the

verifyStaffing(p )1

acceptOrder(p )1

0 1 2 3 4 5 6 7 8 9 10 11 12 13

inTeam(p )1,e2

end(p )1

init(p )1

inTeam(p )2,e3

inTeam(p )2,e1

OK(p )1

Staffing Time

init(p )2

verifyStaffing(p )2

end(p )2OK(p )2

acceptOrder(p )2

Figure 5: A graphical view of a temporal model forPs.

evolution ofPEDB,H) is the succession of sets of interpretationsT

such that (i)T0 = {〈EDB, H〉}, and (ii)Ti+1 = T(Ti).For everyj > 0, any interpretationM ∈ Tj is called atemporalmodelfor PEDB,H. 2

Note that the definition of temporal model refers to a listH ofenvisioned events, containing the events that are deterministicallyknown to happen. Thus,H can be used for simulating the actualbehavior of a system modelled withDATALOG!ev. For instance, inour running example the list[init(p1)@0, init(p2)@2] is usedfor simulating a scenario in which two projects are going to bestaffed at times 0 and 2, respectively. Under an abstract perspec-tive, the events inH are used for constraining the evolution of theDATALOG!ev program.

Definition 5.5 Let P be aDATALOG!ev program,EDB be an inputdatabase, andH a list of ground events. A temporal modelM forPEDB,H is astationary model(for PEDB,H) if it is a fixpoint of T, i.e.,if M ∈ T({M}). Then,curTime(M) is called theconvergingtimeof M . 2

Another characterization of stationary models is provided by thefollowing result.

Proposition 5.6 A temporal model〈S, E〉 for any programPEDB,H

is stationary if and only ifE = ∅.

Example 5.7 Assume that the projectp1 should start at thetime instant 0 and the projectp2 at the time instant2.This is encoded through the list of envisioned eventsH =[init(p1)@0, init(p2)@2]. Then, the graphic reported in Figure5 shows (the relevant atoms of) a temporal model ofPpm, giventhe extensional databaseEDB in Figure 4 and the listH, where theprojectp1 is staffed at time4, whereas projectp2 is staffed duringthe time instant6. Note that during time6, a number of elemen-tary steps are executed in the second time dimension (at instants〈6, 1〉 and〈6, 2〉) for choosing the employees to be enrolled inp2,namely,e1 ande3.

Note that this temporal model is also stationary as no furtherevents are triggered to occur after the completion of the projects.Thus, its converging time is12, when the last project ends. 2

Proposition 5.8 LetP be aDATALOG!ev program,EDB be an in-put database,H a list of ground events, andI be an interpretation ofP. Then, checking whetherI is a temporal model, as well as check-ing whetherI is a stationary model are polynomial time tasks.

PROOFSKETCH. All the non-deterministic issues can be solvedby considering the actual values in the given interpretationI, bothin the computation of stable models in the case of unstratified pro-grams, and in enforcing the functional dependencies according tothe choice constructs.

The set of all the temporal (resp. stationary) models of a givenprogramPEDB,H is denoted byT M(PEDB,H) (resp.T SM(PEDB,H)).

6. QUERIES AND COMPLEXITY ISSUESLet us now describe how to query aDATALOG!ev program about

its possible evolutions on the basis of a list of envisioned futureevents.DATALOG!ev queriesare formulae involving literals and special

temporal quantifiers, as defined inductively below. Lett be a timeinstant andC a nonempty conjunction of ground literals having timearguments at mostt (w.r.t. to the¹ ordering). Then,∀@tC and∃@tC are queries. Moreover, lett1 andt2 be two time instants suchthat t1 ≺ t2, let C be a (possibly empty) conjunction of groundliterals with time arguments at mostt1, and letQ be a query, whosefirst quantifier is either∃@t2 or∀@t2 . Then,∀@t1C∧Q and∃@t1C∧Qare queries.

A queryQ starting with an existential (resp., universal) quanti-fier is called anexistential (resp., universal) query. Moreover, ifthe maximum number of nested quantifiers alternations inQ is k,then it is called ak-existential (resp.,k-universal) query.

Hereafter, given a modelM = 〈S, E〉 for a DATALOG!ev pro-gram, and a timet, we denote byM@t = 〈S′, E〉 the interpretationconsisting of all the atoms having any temporal argumentt′ ¹ t.

Given two temporal modelsM andN , we say thatN is an evolu-tion ofM from timet if M@t = N@t. The set of all the evolutionsof M is denoted byevols(M).

Let M be a set of temporal models for aDATALOG!ev programP. We say thata queryQ is true with respect toM if one of thefollowing conditions hold:

• Q = ∃@tC, whereC is a nonempty conjunction of groundliterals, and there existsM ∈ M s.t. all the literals inC aretrue w.r.t.M ; or

• Q = ∀@tC, whereC is a nonempty conjunction of groundliterals and, for allM ∈ M, all the literals inC are true w.r.t.M ; or

• Q = ∃@t(C ∧ Q′), whereC is a (possibly empty) conjunctionof ground literals, and there existsM ∈ M s.t. all the literalsin C are true w.r.t.M andQ′ is true w.r.t.evols(M); or

• Q = ∀@t(C ∧ Q′), whereC is a (possibly empty) conjunctionof ground literals and, for allM ∈ M, all the literals inCare true w.r.t.M andQ′ is true w.r.t.evols(M).

Otherwise, we say thatQ is false w.r.t.M.

Definition 6.1 (Query answers)Let P be a DATALOG!ev pro-gram,T a time domain,EDB an extensional database,H a list ofenvisioned events, andQ a query. Theanswer ofQ over the pro-gramP w.r.t. toT , givenEDB andH, denoted byQ(PT

EDB,H) is true(resp., stationarily true) ifQ is true w.r.t. the set of temporal modelsTM(PT

EDB,H) (resp., of stationary modelsTSM(PTEDB,H)).

The following example shows how to queryDATALOG!ev pro-grams looking for suitable evolutions that meet some desired re-quirements.

Example 6.2 Consider again the project management planningprogramPpm, the extensional database of Figure 4, and the listof envisioned eventsH = [init(p1)@0, init(p2)@2].

Then, consider the queryQ1 : ∃@9(end(p1) ∧ ∃@12end(p2)).This query is true over the staffing program, givenEDB andH, iffit is possible to staff and start the projects according to the givenlist of envisioned events, in such a way that there exists a temporalmodel wherep1 is completed within time9, and there is an evo-lution of this model wherep2 is completed within time12. In ourcase,Q1 is in fact true, as witnessed by the temporal modelM1

shown in Figure 6.a. In this model, during the gray time instants,the staffing processes occur, while during the black time instantsthe projects are executed. Note that each gray time instant may in-volve a number of elementary steps that are executed in differenttime instants of the second (finer) time dimension.

not staffable

staffing: e , e1 2

p2

1 2 3 4 5 6p1

staffing: e2

staffing: e , e1 3

(a) (b)

0 7 8 9 10 11 12 p2

1 2 3 4 5 6p1

0 7 8 9 10 11 12

Figure 6: Two evolutions for the programPs.

Now, consider the (more stringent) query∀@9(end(p1) ∧∃@12end(p2)). It is easy to verify that this query evaluates to falsefor the programPs, for the givenEDB andH. Indeed, for instance,the temporal model in Figure 6.b is an evolution (from time6) of atemporal model such thatp1 ends at time9; however, in this modelp2 cannot be executed at all. Indeed,p2 requires a developer, butbothe1 ande2 are already busy for they are participating top1. 2

6.1 Computational ComplexityWe next study the computational complexity of a number of

problems related toDATALOG!ev programs and queries. In par-ticular, following thedata complexityapproach [44], in all resultsstated below we will consider a given problem instance having asits input the temporal domainT, the extensional databaseEDB, andthe list of envisioned eventsH, while the programP and (possibly)the queryQ are fixed.

Moreover, since the general problem is (quite trivially) unde-cidable, we next focus on the problem instances where the timedomainT is T ω1,m, with an unbounded main dimension and anumber of bounded range auxiliary dimensions (see Section 3), andσvars∩σtime vars = ∅, i.e., variables and time variables occurringin P are taken from disjoint sets.

First, we discuss the problem of deciding the existence of tem-poral and stationary temporal models.

Theorem 6.3 (Stationary model existence)Deciding whetherPT

EDB,H has a stationary model isPSPACE-complete. Hardnessholds even ifP is stratified.

Ir is worthwhile noting that the problem is much more easier, ifwe are satisfied with any temporal model, rather than requiring thatthe model is stationary.

Theorem 6.4 (Temporal model existence)Deciding whetherPT

EDB,H has a temporal model isNP-complete. However, ifP isstratified, thenPT

EDB,H always have temporal models. Moreover, atemporal model can be computed in polynomial time.

It turns out that stratified programs have an efficient implemen-tation as far as as the computation of one temporal model is con-cerned. However, if we have to answer a given queryQ, and hencewe are interested in some particular temporal models, then the com-plexity becomes much higher. Actually, it turns out that the com-plexity of answering such temporal queries spans the polynomialhierarchy, as stated by the following theorem.

Theorem 6.5 (Query answering under temporal models)If thequeryQ is k-existential (resp.,k-universal), deciding whether theanswerQ(PT

EDB,H) is true is ΣPk -complete (resp.ΠP

k -complete).Hardness holds even ifP is stratified.

Interestingly, query answering under stationary models is notmore difficult then deciding the existence of a stationary model.

Theorem 6.6 (Query answering under stationary models)Deciding whether the answerQ(PT

EDB,H) is stationarily true isPSPACE-complete.

7. RELATED WORK AND CONCLUSIONWe have presented an extension ofDATALOG with events and

choice, calledDATALOG!ev, which is particularly suitable to ex-press queries on the evolution of a knowledge base, on the basisof a given sequence of events that are envisioned to occur in thefuture. The language allows us to model a number of alternativepotential evolutions of a program by means of dynamic rules thatassert both dynamic facts and actions (i.e., triggered events), usingthe capability ofchoice to express nondeterminism.

A distinguished feature of this language is the ability of handlingmultiple time dimensions. Time granularities has been first intro-duced in Event Calculus (EC). Given a set of event occurrences,EC derives the maximal validity interval (MVIs) over which someproperties hold. The event occurrence as well as the relationshipbetween events and properties are specified by means of suitableclauses, and, in fact, a declarative specification of the derivationof MVIs can be straightforwardly obtained in PROLOG. The ap-proach in [34] extended the single timeline of EC into a totallyordered set of different timelines{T1, ..., Tn}, such that eachTi isof a finer granularity thatTi−1. Similar ideas have been applied in[11], that also considers indeterminacy in the occurrence of events(for this latter aspect see also [18, 10]).

The main novelty w.r.t. to the above mentioned extensions ofEvent Calculus lies in the ability of both defining external eventsand modeling the non-deterministic effects of such events so thatthe actual validity of properties over the time dimensions are testedin a context of evolving knowledge bases. Indeed we face theknowledge representation problem with a different perspective:DATALOG!ev has been not designed for reasoning on maximal va-lidity intervals, but rather for reasoning on the evolution of a given(logically) modelled domain in which the effects of the actions arenot known in advance, as it is often the case in real applications. Infact, our language is closer to Dynamic Logic Programming, whichextends logic programming with amenities for modeling and rea-soning on evolving knowledge bases [2, 4, 3].

In this context, the rules of the program may be updated due tosome events and hence modify the global state of the world. Dif-ferent states sequentially ordered may represent time periods as in

[3], that can be eventually combined with other dimensions, suchas credibility of the sources and specificity of the updates [27]. Inthis field, we mention LUPS [4], whose core language is consti-tuted by update commands (such asassertand retract ) that canbe also made conditional on the occurring of certain conditions bymeans of the clausewhen. Two extensions of LUPS, namely thespecification of commands whose execution depends on other con-current commands and the inclusion of external events, have beenadded into the language EPI [17]. In [2], it has been pointed outthat the above mentioned languages do not adhere deeply at the LPdoctrine, as they are too verbose and make use of many additionalkeywords. In order to provide a more declarative way for specify-ing updates in [2], it is proposed EVOLP, in which we may specifysome rules updating the original program. Each time such rules arein the model of the program, the assertion are done, a new programis computed, and the process continues.

Besides the points in common withDATALOG!ev, we stress twoimportant differences: (i) The paradigm of multidimensional up-dates cannot easily fit the need of representing multiple time dimen-sions; in fact, the above mentioned works assume only one tempo-ral dimension within a single granularity, while the other dimen-sions refers to additional properties of the world. (ii) Languagessuch as EVELOP are not query driven, in the sense that there is nonotion of finding updates to satisfy a query. An EVELOP programis concerned with finding the meaning of a given KB after a suc-cession of updates. Conversely,DATALOG!ev has been specificallydesigned for being queried in order to perform temporal reasoning.

When comparingDATALOG!ev with the growing body of the pro-posals of action languages, we need to emphasize that our languageis able to model astaticknowledge as well as adynamicone and,hence, is able to model actions with both direct and indirect effects,covering the main features of languagesA, B (see, for a compar-ison, [21] andAC [42]). It also provides a set of primitives forreasoning on past events, thus capturing the power ofPast Tempo-ral A. Moreover, it deals with concurrent actions such as languagesC [22] andAC [6], and it enables to reason about actual and hypo-thetical occurrences of concurrent and non-deterministic actions,such as languageL2 [7]. Moreover, a distinguishing feature w.r.t.actual action languages, is the ability of reasoning at any level ofdetails. As pointed out by Baral [5], situation and event calculus,are close in their spirit as they aims at modeling a changing en-vironment at a high level of detail, while the temporal reasoningapproach is designed to work at a low level of details, by takingcare of many aspects (e.g., the actual time of the occurrence of theevents) besides the rough effect of actions.

Depending on the user needs,DATALOG!ev can be used as aframework for abstract reasoning on situations, but it is also ableto plan (at the desired level of details) the actions to perform forachieving a given temporal goal. Hence, the language shares thesame perspective of [5].

We conclude by pointing out thatDATALOG!ev is essentially anextension ofDATALOG and hence should be compared to the dif-ferent proposals of extending logic programming with temporallogics (see [36], for a survey of the different proposals). Amongthe first proposals, we recallDatalog1S [13] andTemplog[1]. Theformer isDATALOG extended with one successor modeling the ad-vance of the time, while the latter is an extension that allows arestricted use of modal temporal operators. Despite their differentsyntax (Datalog1S seems an immediate extension ofDATALOG), ithas been proved that they are equivalent as for expressiveness andcompleteness. Starlog [14] is another logic language that adds anadditional time-argument to every PROLOG predicate, and is de-signed for general purpose programming, for simulation, and for

modeling reactive systems. We point out that none of the aboveapproaches deals with multiple time dimensions, and with com-plex temporal functions besides classical modal operators. More-over, more importantly, none of the above approaches deal withexternal or internal events and with non-deterministic effect of ac-tions. Hence, they appear not suited for modeling complex situa-tions where a knowledge base is updated due to the nondeterminis-tic occurrence of actions.

Finally, it is worth mentioning that we are implementingDATALOG!ev by exploiting the disjunctive Datalog systemdlv [28]as its engine core. This implementation is based on an extension ofthe notion of XY-stratification previously used to model update andactive rules [45].

8. REFERENCES[1] M. Abadi and Z. Manna. Temporal Logic Programming.

Journal of Symbolic Computation, 8(3), pages 277–295,1989.

[2] J. J. Alferes, A. Brogi, J. A. Leite, and L.M. Pereira.Evolving Logic Programs. InProc. of JELIA’02, pages50–61, 2002.

[3] J. J. Alferes, J. A. Leite, L. M. Pereira,H. Przymusinska, andT. C. Przymusinski. Dynamic Logic Programming. InProc.of KR’98, pages 98–111, 1998.

[4] J. J. Alferes, L. M. Pereira,H. Przymusinska, and T. C.Przymusinski. LUPS: A language for updating logicprograms.Artificial Intelligence, 138(1–2):87–116, 2002.

[5] C. Baral. A Systematic Approach to reason with time andsituations.Unpublished.

[6] C. Baral, and M. Gelfond. Reasoning About Effects ofConcurrent Actions.JLP, 31(1-3):85–117, 1997.

[7] C. Baral, M. Gelfond, and A. Provetti. Representing Actions:Laws, Observations and Hypotheses.JLP, 31(1-3):201–243,1997.

[8] C. Bettini, X. Sean Wang, and S. Jajodia. A GeneralFramework for Time Granularity and Its Application toTemporal Reasoning.AMAI, 22(1-2):29–58, 1998.

[9] I. Cervesato, M. Franceschet, and A. Montanari. A GuidedTour through Some Extensions of the Event Calculus.Computational Intelligence, 16(2):307–347, 2000.

[10] I. Cervesato, and A. Montanari. A General ModalFramework for the Event Calculus and Its Skeptical andCredulous Variants.JLP, 38(2):111–164, 1999.

[11] L. Chittaro, and C. Combi. Temporal Granularity andIndeterminacy in Reasoning About Actions and Change: AnApproach Based on the Event Calculus.Annals ofMathematics and Artificial Intelligence, 36(1–2):81–119,2002.

[12] P. Cholewinski, V. Marek, and M. Truszczynski. DefaultReasoning System DeReS. In Proc. of theInternationalConference on Principles of Knowledge Representation andReasoning, pages 518–528, 1996.

[13] J. Chomicki, and T. Imielinski. Relational Specifications ofInfinite Query Answers. InProc. of SIGMOD’89, pages174–183, 1989.

[14] R. Clayton, J. Cleary, B. Pfahringer, and M. Utting. Starloghomepage.http://www.scms.waikato.ac.nz/cs/Research/starlog/.

[15] Curtis E. Dyreson, W. S. Evans, Hong Lin, and R. T.Snodgrass. Efficiently Supported Temporal Granularities.TKDE, 12(4):568–587, 2000.

[16] T. Eiter, W. Faber, N. Leone, G. Pfeifer, and A. Polleres. ALogic Programming Approach to Knowledge-State Planning:Semantics and Complexity.TOCL, 2003. To appear.

[17] T. Eiter, M. Fink, G. Sabbatini, and H. Tompits. AFramework for Declarative Update Specifications in LogicPrograms. InProc. of IJCAI’01, pages 649–654, 2001.

[18] M. Franceschet, and A. Montanari. A graph-theoreticapproach to efficiently reason about partially ordered eventsin (Modal) Event Calculus.AMAI, 30(1-4):93–118, 2000.

[19] A. Gabaldon. Programming Hierarchical Task Networks inthe Situation Calculus. In Proc. ofAIPS’02 Workshop onOn-line Planning and Scheduling, 2002.

[20] M. Gelfond, and V. Lifschitz. The Stable Model Semanticsfor Logic Programming. InProc. of ICLP/SLP’88, pages1070–1080, 1988. MIT Press.

[21] M. Gelfond, and V. Lifschitz. Action Languages.ElectronicTransactions on Artificial Intelligence, 2(3-4):193–210,1998.

[22] E. Giunchiglia, and V. Lifschitz. An Action Language Basedon Causal Explanation: Preliminary Report. InProc. of AAAI’98, pages 623–630, 1998.

[23] I. A. Goralwalla, Y. Leontiev, M. T.Ozsu, D. Szafron, and C.Combi. Temporal Granularity: Completing the Puzzle.Journal of Intelligent Information Systems, 16(1):41–63,2001.

[24] T. Janhunen, I. Niemela, P. Simons, P., and J.H. You.Unfolding partiality and disjunctions in stable modelsemantics. In Proc. of theInternational Conference onPrinciples of Knowledge Representation and Reasoning,pages 411-419, 2000.

[25] S. Hanks, and D. McDermott. Nonmonotonic Logic andTemporal Projection.Artificial Intelligence, 33(3):379–412,1987.

[26] R. A. Kowalski, and M. J. Sergot. A Logic-based Calculus ofEvents.New Generation Computing, 4:67–95, 1986.

[27] J. A. Leite, J. J. Alferes, and L. M. Pereira. MultidimensionalDynamic Knowledge representation. InProc. of LPNMR’01,pages 365–378, 2001. Lecture Notes in AI (LNAI).

[28] N. Leone, G. Pfeifer, W. Faber, F. Calimeri, T. Dell’Armi,T. Eiter, G. Gottlob, G. Ianni, G. Ielpa, C. Koch, S. Perri, andA. Polleres. The DLV System. InProc. of JELIA’02, LNCS2424, pages 537–540, 2002.

[29] H. Levesque, R. Reiter, Y. Lesperance, F. Lin, and R. Scherl.GOLOG: A logic programming language for dynamicdomains.Journal of Logic Programming, 31:59-84, 1997.

[30] V. Lifschitz and H. Turner. Representing transition systemsby logic programs, In Proc. of the5th Int. Conf. on LogicProgramming and Nonmonotonic Reasoning, pages 92–106,1999.

[31] F. Lin and Y. Zhao. ASSAT: Computing Answer Sets of aLogic Program by SAT Solvers, In Proc. of the8th NationalConference on Artificial Intelligence, 112, 2002.

[32] V. W. Marek, and Mirosław Truszczynski. AutoepistemicLogic. Journal of the ACM, 38(3):588–619, 1991.

[33] J. McCarthy, and P. J. Hayes. Some Philosophical Problemsfrom the Standpoint of Artificial Intelligence.MachineIntelligence 4, pages 463–502. Edinburgh University Press,1969.

[34] A. Montanari, E. Maim, E. Ciapessoni, and E. Ratto. Dealingwith time granularity in the Event Calculus. InProc. ofFGCS’92., pages 702–712, 1992.

[35] I. Niemela, P. Simons, and T. Syrjanen. Smodels: A Systemfor Answer Set Programming. In Chitta Baral and MirosławTruszczynski, editors,Proc. of NMR’00, 2000.

[36] M. Ali Orgun, and Wanli Ma. An Overview of Temporal andModal Logic Programming. InProc. of ICTL’94, pages445–479, 1994. Springer-Verlag.

[37] D. Sacca and C. Zaniolo. Stable Models andNon-Determinism in Logic Programs with Negation. InProc. ACM Symp. on Principles of Database Systems, pages205–218, 1990.

[38] E. D. Sacerdoti. Planning in a hierarchy of abstractionspaces.Artificial Intelligence, 5:115-135, 1974.

[39] K. Sagonas, T. Swift, and D.S. Warren. XSB as an EfficientDeductive Database Engine. In Proc. of theACM SIGMODInternational Conference on Management of Data, pages442–453, 1994.

[40] G. J. Sussman. The Virtuous Nature of Bugs.Readings inPlanning, chapter 3, pages 111–117. Morgan Kaufmann,1990.

[41] T. Syrjanen and I. Niemela. The Smodels systems. In Proc.of theInternational Conference on Logic Programming andNonmonotonic Reasoning, pages 434-438, 2001.

[42] H. Turner. Representing Actions in Logic Programs andDefault Theories: A Situation Calculus Approach.Journal ofLogic Programming, 31(1–3):245–298, 1997.

[43] H. Turner. A Logic of Universal Causation.ArtificialIntelligence, 113:87–123, 1999.

[44] M. Vardi. The Complexity of Relational Query Languages.In Proc. of STOC’82, pages 137–146, 1982.

[45] C. Zaniolo. Active Database Rules withTransaction-Conscious Stable Model Semantics. InProc. ofDOOD’95, pages 55–72, LNCS 1013,1995.