0% found this document useful (0 votes)
12 views32 pages

Module 4 Notes and Question Bank

This document discusses the nature of representation languages in artificial intelligence, focusing on first-order logic as a more expressive alternative to propositional logic. It outlines the syntax and semantics of first-order logic, including models, terms, atomic sentences, complex sentences, and quantifiers. The document emphasizes the differences between propositional and first-order logic in terms of ontological and epistemological commitments.

Uploaded by

abtahisayed2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views32 pages

Module 4 Notes and Question Bank

This document discusses the nature of representation languages in artificial intelligence, focusing on first-order logic as a more expressive alternative to propositional logic. It outlines the syntax and semantics of first-order logic, including models, terms, atomic sentences, complex sentences, and quantifiers. The document emphasizes the differences between propositional and first-order logic in terms of ontological and epistemological commitments.

Uploaded by

abtahisayed2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

lOMoARcPSD|45581143

Module 4 Notes AND Question BANK

22 scheme vtu 5th sem AI notes (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

Module4:FIRST-ORDERLOGIC
.
REPRESENTATIONREVISITED

In this section, we discuss the nature of representation languages. Our discussion motivates the
developmentoffirst-orderlogic,amuchmoreexpressive language thanthe propositional logic.
Programming languages (such as C++ or Java or Lisp) are by far the largest class of formal
languages in common use. Data structures within programs can represent facts; for example, a
program could use a 4 × 4 array to represent the contents of the wumpus world. Thus, the
programminglanguagestatementWorld[2,2]←Pitisafairlynatural waytoassert that there is a pit in
square [2,2].

Firstdrawbackis programming languages lack is any general mechanism for deriving facts
fromotherfacts; eachupdate toadata structure isdonebyadomain-specific procedure.

Aseconddrawbackofdatastructuresinprograms isthelackofanyeasywayto say, forexample, “There


is a pit in [2,2] or [3,1]” or “If the wumpus is in [1,1] then he is not in [2,2].” Programs
canstoreasinglevalueforeachvariable,andsomesystemsallowthevaluetobe“unknown,”but they lack
the expressiveness required to handle partial information.

Propositional logic is a declarative language because its semantics is based on a truth relation
betweensentencesandpossibleworlds.Italsohassufficientexpressivepowertodealwithpartial
information, using disjunction and negation.
Propositional logic has a third property that is desirable in representation languages, namely,
compositionality. In a compositional language, the meaning of a sentence is a function of the
meaningofitsparts.Forexample,themeaningof“S1,4∧S1,2”isrelatedtothemeaningsof
“S1,4”and “S1,2.”

i. Thelanguageofthought

 Naturallanguages(suchasEnglishorSpanish)areveryexpressive indeed.
 Themodernviewofnaturallanguageisthatitservesaasamediumforcommunicationrather than
pure representation.
 Naturallanguagesalsosufferfromambiguity,aproblemforarepresentationlanguage.

In a first-order logic reasoning system that uses CNF, we can see that the linguistic form “¬(A ∨
B)” and “¬A ∧ ¬B” are the same because we can look inside the system and see that the two
sentences are stored as the same canonical CNF form.

ii. Combiningthebestofformal andnaturallanguages

We can adopt the foundation of propositional logic—a declarative, compositional semantics that
is context-independentand unambiguous—and build amoreexpressive logic on that foundation,
and borrowing representational ideas from natural language while avoiding its drawbacks.

When we look at the syntax of natural language, the most obvious elements are nouns and noun
phrases that refer to objects (squares, pits, wumpuses) and verbs and verb phrases that refer to
relationsamongobjects(isbreezy,isadjacentto,shoots).Someoftheserelationsarefunctions—
relations in which there is onlyone “value” for a given “input.”

Itiseasytostartlistingexamplesofobjects,relations,andfunctions:

1
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

• Objects:people,houses,numbers,theories,RonaldMcDonald,colors,baseballgames,wars,
centuries ...
• Relations: these can be unary relations or properties such as red, round, bogus, prime,
multistoried...,ormoregeneraln-aryrelationssuchasbrotherof,biggerthan,inside,partof, has
color, occurred after, owns, comes between, ...
• Functions:fatherof,bestfriend,thirdinningof,onemorethan,beginningof... Some
examples follow:
• “Oneplustwo equalsthree.”
Objects:one,two,three,oneplustwo;Relation:equals; Function:plus.(“Oneplustwo” is a
name for the object that is obtained by applying the function “plus” to the objects “one”
and “two.” “Three” is another name for this object.)

• “Squaresneighboringthe wumpusaresmelly.”
Objects:wumpus,squares;Property:smelly; Relation:neighboring.

• “Evil KingJohn ruled England in 1200.”


Objects:John,England,1200;Relation:ruled;Properties:evil,king.

The primary difference between propositional and first-order logic lies in the ontological
commitment made by each language—that is, what it assumes about the nature of reality.
Mathematically, this commitment is expressed through the nature of the formal models with
respect to which the truth of sentences is defined.
 Forexample,propositionallogicassumesthattherearefactsthateitherholdordonothold in the
world. Each fact can be in one of two states: true or false, and each model assigns true or
false to each proposition symbol.
 First-order logic assumes more; namely, that the world consists of objects with certain
relations among them that do or do not hold.
 Temporallogicassumesthatfactsholdatparticulartimesandthatthosetimes(whichmay be
points or intervals) are ordered.
 Higher-order logic views the relations and functions referred to by first-order logic as
objects in themselves.

Logic can also be characterized by its epistemological commitments—the possible states of


knowledge that it allows with respect to each fact.
Systems usingprobabilitytheory, on the other hand,can have anydegree of belief, rangingfrom 0
(total disbelief) to 1 (total belief).

2
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

SyntaxandSemanticsofFirst-OrderLogic

i. Modelsforfirst-orderlogic

The models of a logical language are the formal structures that constitute the possible worlds under
consideration. Each model links the vocabulary of the logical sentences to elements of the possible
world, so that the truth of anysentence can be determined. Thus, models for propositional logic link
proposition symbols to predefined truth values.
Models for first-order logic are much more interesting. First, they have objects in them! The
domain of a model is the set of objects. The domain is required to be nonempty—everypossible
world must contain at least one object.

1. Richardthe Lionheart,KingofEnglandfrom1189to1199;
2. Theevil KingJohn, whoruled from 1199to 1215;
3. Theleftlegsof Richard
4. Theleftlegsof John;
5. Acrown

The objects in the model may be related in various ways. In the figure, Richard and John are
brothers.
A relation is just the set of tuples of objects that are related. (A tuple is a collection of objects
arranged in a fixed order and is written with angle brackets surrounding the objects.)

Thus,thebrotherhoodrelation inthismodelistheset
{<Richard theLionheart, KingJohn>,<KingJohn,RichardtheLionheart >}(8.1)

ThecrownisonKingJohn’shead, sothe“on head”relationcontainsjust one tuple,


<thecrown,KingJohn>.

The “brother” and “on head” relations are binary relations—that is, they relate pairs of objects.
Themodelalsocontainsunaryrelations,orproperties:the“person”propertyistrueofboth Richard and
John; the “king” propertyis true onlyof John (presumablybecause Richard is dead at this point);
and the “crown” propertyis true onlyof the crown.

Certainkindsofrelationshipsarebestconsideredasfunctions,inthatagivenobjectmustbe

3
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
relatedtoexactlyoneobjectin thisway.
Forexample,eachpersonhasoneleftleg,sothemodelhasaunary“leftleg”functionthatincludes the
following mappings:
<Richardthe Lionheart> →Richard’sleftleg (8.2)
<KingJohn>→ John’sleftleg

ii. Symbolsandinterpretations

The basic syntactic elements of first-order logic are the symbols that stand for objects, relations,
and functions.The symbols, therefore, come in three kinds:
 Constantsymbols,whichstandforobjects;
 Predicatesymbols,whichstandforrelations; and
 Functionsymbols,whichstandforfunctions.

Weadopttheconventionthatthesesymbolswillbeginwithuppercaseletters. For
example, we might use
 constant symbolsRichardandJohn;
 predicatesymbols Brother,OnHead,Person,King,andCrown;and
 functionsymbolLeftLeg.

As in propositional logic,everymodel must provide theinformation requiredto determineif any


given sentence is true or false.
Thus, in addition to its objects, relations, and functions, each model includes an interpretation
that specifies exactly which objects, relations and functions are referred to by the constant,
predicate, and function symbols.
One possible interpretation for our example—which a logician would call the intended
interpretation—is as follows:

4
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
• RichardreferstoRichardtheLionheart andJohnreferstotheevilKingJohn.
• Brother refers to the brotherhood relation, that is, the set of tuples of objects given in Equation
(8.1); OnHead refers to the “on head” relation that holds between the crown and King John;
Person, King, and Crown refer to the sets of objects that are persons, kings, and crowns.
• LeftLegreferstothe “leftleg”function,thatis, the mappinggiveninEquation (8.2).

There are many other possible interpretations, of course. For example, one interpretation maps
RichardtothecrownandJohntoKingJohn’sleftleg.Therearefiveobjectsinthemodel,sothere are 25
possible interpretations just for the constant symbols Richard and John.

Insummary,amodelinfirst-orderlogicconsistsofasetofobjectsandaninterpretationthatmaps
constantsymbolstoobjects,predicatesymbolstorelationsonthoseobjects,andfunctionsymbols to
functions on thoseobjects. Toget anidea of what the setof all possible models looks like, see
Figure8.4.Itshowsthatmodelsvaryinhowmanyobjectstheycontain—fromoneuptoinfinity— and in
the way the constant symbols map to objects. If there are two constant symbols and one
object,then both symbols must refer to the same object; but this can still happeneven with more
objects. When there are more objects than constant symbols, some of the objects will have no
names. Because the number of possible models is unbounded, checking entailment by the
enumeration of all possible models is not feasible for first-order logic.

iii. Terms

• Atermisalogicalexpressionthatreferstoanobject.Constantsymbolsarethereforeterms,
butitisnotalwaysconvenienttohaveadistinctsymboltonameeveryobject.Forexample, in
English we might use the expression “KingJohn’s left leg” rather than givinga name to his
leg.
• This is what function symbols are for: instead of using a constant symbol, we use
LeftLeg(John).
• In the general case, a complex term is formed by a function symbol followed by a
parenthesized list of terms as arguments to the function symbol.
• The formal semantics of terms is straightforward. Consider a term f(t1,...,tn). The function
symbolfreferstosomefunctioninthemodel(callitF);theargumenttermsrefertoobjects in the
domain (call them d1,...,dn); and the term as a whole refers to the object that is the value of
the function F applied to d1,...,dn.
For example, suppose the LeftLeg function symbol refers to the function shown in
Equation(8.2)andJohnreferstoKingJohn,then LeftLeg(John)referstoKingJohn’s left leg.
In this way, the interpretation fixes the referent of everyterm.

5
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

iv. Atomicsentences
Atomicsentence(oratomforshort)isformedfromapredicatesymboloptionallyfollowedbya parenthesized
list ofterms, such as
Brother(Richard,John).

Thisstates,undertheintendedinterpretationgivenearlier,thatRichardtheLionheartisthebrother of
King John. Atomic sentences can have complex terms as arguments. Thus,
Married(Father(Richard),Mother(John))
statesthatRichardtheLionheart’sfatherismarriedtoKingJohn’smother(again,underasuitable
interpretation).
An atomic sentenceis truein a given model if the relation referred to by thepredicatesymbol holds
among the objects referred to by the arguments.

v. Complexsentences

We can use logical connectives to construct more complex sentences, with the same syntax
andsemantics as in propositional calculus.
Hereare foursentencesthataretrue inthemodelofFigure8.2underourintended interpretation:

¬Brother(LeftLeg(Richard),John)
Brother(Richard,John)𝖠Brother
(John, Richard)King(Richard) ∨
King(John)
¬King(Richard)⇒King(John) .

vi. Quantifiers
Quantifiers are used express properties of entire collections of objects in natural way, instead of
enumerating the objects by name.
First-orderlogiccontainstwostandardquantifiers,calleduniversalandexistential.

A. Universalquantification(∀)

Therule,“Allkingsarepersons,”iswritteninfirst-orderlogic as
∀xKing(x) ⇒Person(x).∀isusuallypronounced“For all ...”
Thus, the sentence says, “For all x, if x is a king, then x is a person.” The symbol x is called a
variable. By convention, variables are lowercase letters. A variable is a term all by itself, and as
such can also serve as the argument of a function—for example, LeftLeg(x). A term with no
variables is called a ground term.

Thesentence∀ x P,where Pisanylogicalexpression,saysthatPistrueforeveryobjectx.More precisely,


∀ x P is true in a given model if P is true in all possible extended interpretations constructed from
the interpretation given in the model, where each extended interpretation specifies a domain
element to which x refers.

Wecanextendtheinterpretationinfiveways:
 x →RichardtheLionheart,
 x→KingJohn,
 x→Richard’sleftleg,
 x →John’sleftleg,
 x → thecrown.

6
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

The universallyquantified sentence ∀ x King(x) ⇒ Person(x) is true in the original model if the
sentence King(x) ⇒ Person(x) is true under each of the five extended interpretations.
Thatis,theuniversallyquantifiedsentenceisequivalenttoassertingthefollowingfivesentences:
 Richardthe Lionheartisa king⇒RichardtheLionheartisaperson.
 KingJohn isaking⇒KingJohn isaperson.
 Richard’sleftlegisaking⇒Richard’s leftlegisaperson.
 John’sleft legisaking⇒John’sleftlegisaperson.
 Thecrown isaking⇒thecrown isaperson.

B. Existentialquantification(∃)

Universalquantificationmakesstatementsabouteveryobject.Similarly,wecanmakeastatement about
some object in the universe without naming it, byusing an existential quantifier.
Tosay,forexample,thatKingJohnhasa crownonhishead,we write

∃xCrown(x)𝖠OnHead(x,John).

∃xispronounced“There existsanxsuchthat ...”or“Forsomex...”.


Intuitively,thesentence ∃xPsaysthatPistrueforatleastoneobject x.Moreprecisely,∃x Pis true ina
givenmodelifPistrue inatleastone extendedinterpretationthatassignsx toa domain element.

Thatis,atleastoneofthefollowingistrue:
 RichardtheLionheartisacrown𝖠RichardtheLionheartisonJohn’shead;
 KingJohnisa crown 𝖠KingJohnisonJohn’shead;
 Richard’sleftlegisacrown 𝖠Richard’sleft legison John’s head;
 John’sleftlegisa crown𝖠John’sleft legisonJohn’s head;
 Thecrownisacrown𝖠thecrown isonJohn’shead.

Logicalconnector⇒appearstobethenaturalconnectivetousewith∀,𝖠isthenaturalconnective to use
with ∃.
Using𝖠 as themain connectivewith∀ led to an overly strong statementin theexample in the previous
section; using ⇒ with ∃ usuallyleads to a veryweak statement, indeed.

Considerthefollowingsentence:∃xCrown(x)⇒OnHead(x,John).
Applyingthe semantics,weseethatthesentencesaysthatatleastoneofthefollowingassertions is true:
 Richardthe Lionheart isacrown⇒RichardtheLionheartisonJohn’s head;
 KingJohnisacrown⇒KingJohn isonJohn’shead;
 Richard’sleftlegisacrown ⇒Richard’sleft legison John’shead

C. Nestedquantifiers

We will often want to express more complex sentences using multiple quantifiers. The simplest
case is where the quantifiers are of the same type. For example, “Brothers are siblings” can be
written as

∀x∀yBrother(x,y)⇒Sibling(x,y).

Consecutivequantifiersofthesametypecanbewrittenasonequantifierwithseveralvariables. For
example, to saythat siblinghood is a symmetric relationship, we can write

7
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
∀x,ySibling(x,y)⇔Sibling(y,x).

Inothercaseswewillhavemixtures.“Everybodylovessomebody”meansthatforeveryperson, there is
someone that person loves:
∀x∃yLoves(x,y).
Onthe otherhand,tosay“Thereissomeonewhoislovedbyeveryone,”wewrite

∃y∀xLoves(x,y).

Theorderofquantificationis thereforeveryimportant.
Itbecomesclearerifweinsertparentheses.∀x(∃yLoves(x,y))saysthateveryonehasaparticular property,
namely, the property that they love someone.

Ontheotherhand,∃y(∀xLoves(x,y))saysthatsomeoneintheworldhasaparticularproperty, namely the


property of being loved by everybody.

D. Connections between∀and∃

Twoquantifiersareactuallyintimatelyconnectedwitheachother,throughnegation.

Asserting that everyone dislikes parsnips is the same as asserting there does not exist someone
who likes them, and vice versa:
∀x¬Likes(x,Parsnips)isequivalentto¬∃xLikes(x,Parsnips).
We can go one step further:“Everyone likes icecream” means that there is no onewho does not
like ice cream:
∀xLikes(x,IceCream)isequivalentto¬∃x¬Likes(x,IceCream).
Because∀ isreallyaconjunctionovertheuniverseofobjectsand∃ isadisjunction,itshouldnot be
surprising that they obey De Morgan’s rules.

TheDeMorganrulesforquantifiedandunquantifiedsentencesare asfollows:
∀x¬P≡¬∃xP ¬(P∨Q)≡¬P𝖠¬Q
¬∀xP≡∃x¬P ¬(P𝖠Q)≡¬P∨¬Q
∀xP≡¬∃x¬P P𝖠Q≡¬(¬P∨¬Q)
∃xP≡¬∀x¬P P∨Q≡¬(¬P𝖠¬Q).

Thus, wedo not reallyneed both∀and ∃, just as wedonotreallyneed both𝖠and∨.

vii. Equality

First-order logic includes one more way to make atomic sentences, other than using a predicate
and terms as described earlier. We can use the equalitysymbol to signify that two terms refer to
the same object.
Forexample,
Father(John)=Henry

saysthattheobjectreferredtobyFather(John)andtheobjectreferredtobyHenryarethesame. Because
an interpretation fixes the referent of any term, determining the truth of an equality sentence is
simply a matter of seeing that the referents of the two terms are the same object.

Theequalitysymbolcanbeusedtostatefactsaboutagivenfunction,aswejustdidfortheFather

8
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
symbol. Itcan alsobeusedwithnegationtoinsist thattwotermsarenotthesameobject. To
saythat Richard has at least two brothers, we would write
∃x,yBrother(x,Richard)𝖠Brother(y,Richard)𝖠¬(x=y).

viii. Analternative semantics?

SupposethatwebelievethatRichardhastwobrothers,JohnandGeoffrey Assert
Brother (John, Richard ) 𝖠Brother (Geoffrey , Richard ) ?
Notquite
1. ThisassertionistrueinamodelwhereRichardhasonlyonebrother—weneedtoaddJohn!=
Geoffrey.
2. Thesentencedoesn’truleoutmodelsinwhichRichardhasmanymorebrothersbesidesJohn
andGeoffrey.
3. Thecorrecttranslationof“Richard’sbrothersareJohnandGeoffrey”isasfollows:
Brother(John,Richard)𝖠Brother(Geoffrey,Richard)𝖠John≠Geoffrey𝖠
∀xBrother(x,Richard)⇒(x=John∨x=Geoffrey)

ix. DatabaseSemantics

Oneproposalthatisverypopularindatabasesystemsworksasfollows.
• First,weinsistthateveryconstantsymbol refertoadistinctobject—theso-calledunique- names
assumption.
• Second,weassumethatatomicsentencesnotknowntobetrueareinfactfalse—theclosed- world
assumption.
• Finally,weinvoke domainclosure,meaningthateachmodelcontainsnomoredomain
elements than those named by the constant symbols.

USINGFIRST-ORDERLOGIC

i. Assertionsandqueriesinfirst-order logic

Sentences areaddedto aknowledgebaseusing TELL,exactly as inpropositionallogic.Such sentences are


called assertions.
Forexample,wecanassertthatJohnisaking,Richardisaperson,andallkingsarepersons:

TELL(KB, King(John)) .
TELL(KB,Person(Richard)).
TELL(KB,∀xKing(x)⇒Person(x)).

WecanaskquestionsoftheknowledgebaseusingASK. For
example,
ASK(KB,King(John))returnstrue.

QuestionsaskedwithASKarecalledqueriesorgoals.Generallyspeaking,anyquerythatis logically entailed


by the knowledge base should be answered affirmatively.

Forexample, giventhetwoprecedingassertions,thequery
ASK(KB,Person(John))shouldalsoreturntrue.

Wecanaskquantifiedqueries, suchas
ASK(KB,∃xPerson(x)).

The answeristrue,butthisisperhapsnotashelpfulaswewould like.

9
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
It is ratherlike answering“Can you tellmethe time?”with“Yes.” If wewanttoknowwhatvalueof x
makes the sentence true, we will need a different function, ASKVARS, which we call with
ASKVARS(KB,Person(x))
andwhichyieldsastreamofanswers.Inthiscasetherewillbetwoanswers:{x/John}and
{x/Richard}. Such an answer is called a substitution or binding list. ASKVARS is usually
reservedforknowledgebasesconsistingsolelyof Hornclauses,becauseinsuchknowledgebases
everyway of making the querytrue will bind the variables to specific value.

ii. Thekinshipdomain

The first example we consider is the domain of family relationships, or kinship. This domain
includesfactssuch as“Elizabeth isthemother of Charles” and “Charlesisthe fatherof William” and
rules such as “One’s grandmother is the mother of one’s parent.”

Clearly, the objects in our domain are people. We have two unary predicates, Male and Female.
Kinship relations—parenthood, brotherhood, marriage, and so on—are represented by binary
predicates: Parent, Sibling, Brother, Sister, Child, Daughter, Son, Spouse, Wife, Husband,
Grandparent, Grandchild, Cousin, Aunt, and Uncle.
Wecangothrougheachfunctionandpredicate,writingdownwhatweknowintermsoftheother symbols.
Forexample,
one’smotherisone’sfemaleparent:
∀m,cMother(c)=m⇔Female(m)𝖠Parent(m,c).
One’shusbandisone’smale spouse:
∀w,hHusband(h,w)⇔Male(h)𝖠Spouse(h,w).
Male andfemalearedisjointcategories:
∀xMale(x)⇔¬Female(x).
Parentandchildareinverserelations:
∀p,cParent(p,c)⇔Child(c,p).
Agrandparentisaparentofone’s parent:
∀g,cGrandparent(g,c)⇔∃pParent(g,p)𝖠Parent(p,c).
Asiblingisanotherchildofone’sparents:
∀x,ySibling(x,y)⇔x=y𝖠∃pParent(p,x)𝖠Parent(p,y).

Eachofthesesentencescanbeviewedasanaxiomofthekinshipdomain.Axiomsarecommonly
associated with purely mathematical domains.
Ourkinshipaxiomsarealsodefinitions;theyhavetheform∀x,yP(x,y)⇔….Theaxiomsdefine
theMotherfunctionandtheHusband,Male,Parent,Grandparent,andSiblingpredicates interms of
other predicates.

Notalllogicalsentencesaboutadomainareaxioms.Somearetheorems—thatis,theyareentailed bythe
axioms. For example, consider the assertion that siblinghood is symmetric:
∀x,ySibling(x,y)⇔Sibling(y,x)
Not all axioms are definitions. Some provide more general information about certain predicates
withoutconstitutingadefinition.Indeed,somepredicateshavenocompletedefinitionbecausewe do
not know enough to characterize them fully.
Forexample,thereisnoobviousdefinitive waytocompletethe sentence
∀xPerson(x)⇔...
Fortunately,first-orderlogicallowsustomakeuseofthePersonpredicatewithoutcompletely
definingit.Instead,wecanwritepartialspecificationsofpropertiesthateverypersonhasand

10
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
propertiesthatmakesomethingaperson:
∀xPerson(x)⇒...∀x...⇒Person(x).
Axiomscanalsobe“justplainfacts,”suchasMale(Jim)andSpouse(Jim,Laura).Suchfactsform the
descriptions of specific problem instances, enabling specific questions to be answered.

iii. Numbers,sets,andlists

Numbers are perhaps the most vivid example of how a large theorycan be built up from a tiny
kernel of axioms. We describe here the theoryof natural numbers or non-negative integers.
 ApredicateNatNumthatwillbetrueofnatural numbers.
 Oneconstantsymbol, 0;and
 Onefunctionsymbol,S(successor).
 0isa naturalnumber, andforeveryobjectn,
 ifnisa naturalnumber,thenS(n)isanaturalnumber.
 Thenatural numbersare0, S(0),S(S(0)),andsoon
 axiomstoconstrainthesuccessor function
∀n0≠S(n).
∀m,nm≠n⇒S(m)≠S(n).

Naturalnumbersaredefinedrecursively:
NatNum(0).
∀nNatNum(n)⇒NatNum(S(n)).
Additionintermsofthesuccessor function: (0-zero)
∀mNatNum(m)⇒+(0,m)= m
∀m,nNatNum(m)𝖠NatNum(n)⇒+(S(m),n)=S(+(m,
n))writeS(n)asn+1
∀m,nNatNum(m)𝖠NatNum(n)⇒(m+1)+n=(m+n)+1.
• Theuseofinfixnotationisanexampleofsyntacticsugar,thatis,anextensiontoorabbreviation of the
standard syntax that does not change the semantics.
• Addition, it is straightforward to define multiplication as repeated addition, exponentiation as
repeated multiplication, integer division and remainders, prime numbers, and so on.

Sets:The domainof setsisalsofundamentaltomathematicsaswellastocommonsense reasoning.


• Normal vocabularyofsettheoryassyntacticsugar.
• Emptyset{ }.
• Oneunarypredicate,Set,whichistrueofsets.
• The binary predicates are x ∈s (x is a member of sets) and s1⊆s2(set s1is a subset, not
necessarily proper, of set s2).
• Thebinaryfunctionsares1∩s2(theintersectionoftwosets),s1𝖴s2(theunionoftwosets), and {x|s}
(the set resulting from adjoining element x to set s).

Onepossible setofaxiomsisasfollows:
1. Theonlysetsaretheemptysetandthosemadebyadjoiningsomethingtoaset:
∀sSet(s)⇔(s={})∨(∃x,s2Set(s2)𝖠s={x|s2}).
2. Theemptysethasnoelementsadjoinedintoit.Inotherwords,thereisnowayto
decompose
{}intoasmaller setandanelement:
¬∃x,s{x|s}= {}.
3. Adjoininganelementalreadyinthe sethasnoeffect:
∀x,sx∈s⇔s={x|s}.

4. Theonlymembersof asetarethe elementsthatwereadjoinedinto it.

11
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
∀x,sx∈s⇔∃y,s2(s={y|s2}𝖠(x=y∨x∈s2)).
5. Asetisa subset ofanothersetifand onlyifallofthefirst set’smembersare members of
thesecond set:
∀s1,s2s1 ⊆s2 ⇔( ∀xx ∈s1 ⇒x ∈s2).
6. Twosetsareequal ifand onlyifeach is asubset ofthe other:
∀s1,s2(s1=s2)⇔(s1⊆s2𝖠s2⊆s1).
7. Anobjectisintheintersectionoftwosetsifandonlyifitisa memberofbothsets:
∀x,s1,s2x ∈(s1∩s2) ⇔(x ∈s1 𝖠x ∈s2).
8. Anobject isintheunion oftwo setsifandonlyifit isa memberof either set:
∀x,s1,s2x ∈(s1 𝖠s2) ⇔(x ∈s1 ∨x ∈s2).

Listsaresimilartosets.Thedifferencesarethatlistsareorderedandthesameelementcanappear more
than once in a list
 List ?isa predicate that istrueonlyof lists.
 lists:Nilistheconstantlistwithnoelements;
 Cons,Append,First,andRestarefunctions; and
 Findisthepredicatethatdoesforlistswhat Memberdoesforsets.
 Cons(x,y),where yisanonemptylist,iswritten[x|y]
 Cons(x,Nil)(i.e.,the list containingtheelementx)iswrittenas[x]
 NestedtermCons(A,Cons(B,Cons(C,Nil )))

iv. Thewumpus world

Wumpusagentreceivesapercept vectorwithfiveelements:
Percept([Stench,Breeze,Glitter,None,None],5)
• Theactionsinthe wumpusworldcanberepresentedbylogical terms:
Turn(Right),Turn(Left ),Forward,Shoot ,Grab,Climb.
• Todeterminewhichisbest,theagent programexecutesthequery
ASKVARS(∃aBestAction(a,5))---------- returnsa bindinglistsuchas{a/Grab}.
• Therawperceptdataimpliescertainfactsaboutthecurrentstate
example:
∀t,s,g,m,cPercept([s,Breeze,g,m,c],t)⇒Breeze(t),
∀t,s,b,m,cPercept([s,b,Glitter,m,c],t)⇒Glitter(t),…….
• Theserulesexhibita trivialformofthereasoningprocesscalledperception
• Simple“reflex”behaviorcanalsobeimplementedbyquantified implication sentences.
Example:∀tGlitter(t)⇒BestAction(Grab,t)
• Torepresenttheenvironmentitself
Adjacencyof anytwo squarescan bedefinedas
∀x,y,a,bAdjacent([x,y],[a,b])⇔
(x=a𝖠(y=b−1∨y=b+1))∨(y=b𝖠(x=a−1∨x=a+1))
• Theagent’slocationchangesovertimeAt(Agent,s,t)tomeanthattheagentisatsquaresat
time t
• Fixthe wumpus’slocationwith∀tAt(Wumpus,[2,2],t)
• objectscan onlybeatonelocationat atime
∀x,s1,s2,tAt(x,s1,t)𝖠At(x,s2,t)⇒s1=s2
• Ifthe agentisata squareandperceivesa breeze,thenthatsquareisbreezy
∀s,tAt(Agent,s,t)𝖠Breeze(t)⇒Breezy(s)
• First-orderlogicjustneedsoneaxiomtodeduce wherethepitsare:
∀sBreezy(s)⇔∃rAdjacent(r,s)𝖠Pit(r)
• Theaxiomforthe arrow
∀tHaveArrow(t+1)⇔(HaveArrow(t)𝖠¬Action(Shoot, t))

12
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence
INFERENCEINFIRST-ORDER LOGIC
1. PropositionalVsFirstOrderInference
Earlier inference in first orderlogic is performed with Propositionalization which is a process of
converting the Knowledgebase present in First Order logic into Propositional logic and on that
using any inference mechanisms of propositional logic are used to check inference.
Inferencerulesforquantifiers:
TherearesomeInferencerulesthatcanbeappliedtosentenceswithquantifierstoobtainsentences without
quantifiers. These rules will lead us to make the conversion.
Supposeourknowledgebasecontainsthestandardfolkloricaxiomstatingthatallgreedykingsare evil:
∀xKing(x)∧Greedy(x)⇒Evil(x).
Thenitseemsquitepermissibletoinferanyofthefollowingsentences:
King(John) ∧Greedy(John) ⇒Evil(John) King(Richard
)∧Greedy(Richard) ⇒Evil(Richard)
King(Father(John))∧Greedy(Father(John))⇒Evil(Father(John)).
..
UniversalInstantiation(UI):
The rule says that we can infer any sentence obtained by substituting a ground term (a term
withoutvariables)forthevariable.LetSUBST(θ, α)denotetheresultofapplyingthesubstitution θ to the
sentence α. Then the rule is written

Foranyvariablevandgroundtermg.Forexample,thethreesentencesgivenearlierareobtainedwith the
substitutions {x/John}, {x/Richard }, and {x/Father (John)}.

Thusauniversallyquantifiedsentencecanbereplacedbythesetof allpossibleinstantiations.

ExistentialInstantiation(EI):

The existential sentence says there is some object satisfying a condition, and the instantiation
processisjustgivinganametothatobject,thatnamemustnotalreadybelongtoanotherobject.
Thisnewnameiscalleda Skolemconstant. Existential Instantiationisaspecialcaseofamore general
process called “skolemization”.
Forany sentencea,variablev,andconstantsymbolkthatdoesnotappearelsewhereinthe knowledge base,

Forexample,fromthesentence

13
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

So,wecaninferthesentence

As long as C1does not appear elsewhere in the knowledge base. Thus an existentiallyquantified
sentence can be replaced by one instantiation
Elimination of Universaland Existentialquantifiersshould give newknowledge base whichcan be
shown to be inferentially equivalentto oldin the sense that it is satisfiable exactly when the
original knowledge base is satisfiable.

Reductiontopropositionalinference:
Once we have rules for inferring non quantified sentences from quantified sentences, it becomes
possible to reduce first-order inference to propositional inference. For example, suppose our
knowledge base contains just the sentences

Then we apply UI to the first sentence using all possible ground term substitutions from the
vocabularyof the knowledge base-in this case, {xl John) and {x/Richard). We obtain

We discard the universally quantified sentence. Now, the knowledge base is essentially
propositional if we view the ground atomic sentences-King (John), Greedy (John), and Brother
(Richard,John)aspropositionsymbols.Therefore,wecanapplyanyofthecompletepropositional
algorithms to obtain conclusions such as Evil (John).

Disadvantage:
Iftheknowledgebaseincludesafunctionsymbol,thesetofpossible groundtermsubstitutionsis infinite.
Propositional algorithms will have difficultywith an infinitelylarge set of sentences.
NOTE:
Entailment for first-order logic is semi decidablewhich means algorithms exist that say yes to
everyentailedsentence, but noalgorithmexists thatalso saysnotoeverynonentailed sentence.

2. UnificationandLifting
Considertheabovediscussedexample,ifweaddSiblings(Peter,Sharon)totheknowledgebase then it
will be

14
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

Removing Universal Quantifier will add new sentences to the knowledge base which are not
necessary for the query Evil (John)?

Henceweneedtoteachthecomputertomakebetterinferences. ForthispurposeInferencerules were


used.

FirstOrderInferenceRule:
Thekeyadvantageof lifted inference rules over propositionalization isthattheymakeonlythose
substitutions which are required to allow particular inferences to proceed.

GeneralizedModusPonens:
If there is some substitution θ that makes the premise of the implication identical to sentences
alreadyintheknowledgebase,thenwecanasserttheconclusionoftheimplication,afterapplying θ. This
inference process can be captured as a single inference rule called Generalized Modus Ponens
which is a lifted version of Modus Ponens-it raises Modus Ponens from propositional to first-
order logic
For atomic sentences pi, pi ', and q, where there is a substitution θ such that SUBST( θ , pi ) =
SUBST(θ , pi '), for all i,

ThereareN+1premisestothisrule,Natomic sentences+oneimplication.ApplyingSUBST (θ, q)


yields the conclusion we seek. It is a sound inference rule.
SupposethatinsteadofknowingGreedy(John)inourexampleweknowthateveryoneis greedy:
∀yGreedy(y)
WewouldconcludethatEvil(John).
Applyingthesubstitution {x/John,y/ John)tothe implicationpremisesKing(x)andGreedy(x
) and the knowledge base sentences King(John) and Greedy(y)will makethem identical. Thus, we
can infer the conclusion of the implication.

Forexample,

Unification:

Itistheprocessusedtofindsubstitutionsthatmakedifferentlogicalexpressionslookidentical.
Unificationisakeycomponentofallfirst-orderInferencealgorithms.

15
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

ArtificialIntelligence

UNIFY(p,q) =θwhere SUBST(θ,p)=SUBST(θ,q)θisourunifiervalue(ifoneexists). Ex:


―Who doesJohn know?‖
UNIFY(Knows(John,x), Knows(John,Jane))={x/Jane}.UNIFY(Knows(John,x),Knows (y, Bill))
= {x/Bill, y/ John}.
UNIFY(Knows(John,x),Knows(y,Mother(y)))={x/Bill, y/John}UNIFY(Knows(John,x), Knows
(x, Elizabeth)) = FAIL

 The lastunificationfailsbecausebothusethesamevariable,X.Xcan’tequalbothJohn and Elizabeth.


Toavoidthischange thevariable Xto Y (oranyothervalue)in Knows(X,Elizabeth)
Knows(X,Elizabeth)→Knows(Y,Elizabeth)

Stillmeansthesame.Thisiscalledstandardizingapart.
 sometimesitispossibleformorethanoneunifier returned:
UNIFY(Knows(John,x),Knows(y,z))=???

This can return two possible unifications: {y/ John, x/ z} which means Knows (John, z) OR {y/
John, x/ John, z/ John}. For each unifiable pair of expressions there is a single most general
unifier (MGU), In this case it is {y/ John, x/z).
Analgorithmforcomputingmostgeneralunifiersisshownbelow.

Figure 2.1 The unification algorithm. The algorithm works by comparing the structures of the
inputs,elementbyelement.Thesubstitution0thatistheargumenttoUNIFYisbuiltupalongthe way and
is used to make sure that later comparisons are consistent with bindings that were
establishedearlier.Inacompoundexpression,suchasF (A,B),thefunctionOPpicksoutthe
functionsymbolFandthefunctionARCSpicksouttheargument list(A,B).

16
Downloaded by Abtahi Sayed ([email protected])
lOMoARcPSD|45581143

Artificial Intelligence

The process is very simple: recursively explore the two expressions simultaneously "side by side,"
building up a unifier along the way, but failing if two corresponding points in the structures do not
match. Occur check step makes sure same variable isn’t used twice.

Storageandretrieval
 STORE(s)storesasentencesintotheknowledge base
 FETCH(s)returnsallunifierssuchthatthequeryqunifieswithsomesentenceintheknowledge base.
Easy way to implement these functions is Store all sentences in a long list, browse list one
sentence at a time with UNIFY on an ASK query. But this is inefficient.
TomakeFETCHmoreefficientbyensuringthatunificationsareattemptedonlywithsentences that
have some chance of unifying. (i.e. Knows(John, x) vs. Brother(Richard, John) are not
compatible for unification)
 Toavoidthis,asimpleschemecalledpredicateindexingputsalltheKnowsfactsinonebucket and all
the Brother facts in another.
 Thebucketscanbestoredinahashtableforefficientaccess.Predicateindexingisusefulwhen there are
manypredicate symbols but only a few clauses for each symbol.

Butifwe havemany clauses for agivenpredicatesymbol,facts canbestored under multiple index


keys.
ForthefactEmploys(AIMA.org, Richard),thequeriesareEmploys(AIMA.org,Richard)
DoesAIMA.orgemployRichard?Employs(x,Richard)whoemploys Richard?
Employs(AIMA.org,y)whomdoesAIMA.orgemploy?
EmploysY(x),whoemployswhom?

Wecanarrangethisintoasubsumptionlattice,asshownbelow.

Figure 2.2 (a) The subsumption lattice whose lowest node is the sentence Employs
(AIMA.org,Richard).(b)ThesubsumptionlatticeforthesentenceEmploys(John,John).
Asubsumptionlatticehasthefollowingproperties:

17

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

 childofanynodeobtainedfromitsparentsbyonesubstitution
 the―highest‖commondescendantofanytwonodesistheresultofapplyingtheirmost general
unifier.
 predicate with n arguments contains O(2n ) nodes (in our example, we have two
arguments, so our lattice has four nodes)
 Repeatedconstants=slightlydifferentlattice.

3. ForwardChaining
First-OrderDefiniteClauses:
A definite clause either is atomic or is an implication whose antecedent is a conjunction of positive
literalsandwhoseconsequentisasinglepositiveliteral.Thefollowingarefirst-orderdefiniteclauses:
Unlike propositional literals, first-order literals can include variables, in which case those variables
are assumed to be universally quantified.

Considerthefollowingproblem;
“The law says that it is a crime for an American to sell weapons to hostile nations. The country
Nono, an enemy of America, has some missiles, and all of its missiles were sold to it by Colonel
West, who is American.”
Wewillrepresentthefactsasfirst-orderdefiniteclauses
"...ItisacrimeforanAmericantosellweaponstohostile nations":
ExampleKnowledgeBase:
 ….it isa crimeforanAmericantosellweaponstohostilenations:
Rule1.American(x)𝖠Weapon(y)𝖠Sells(x, y,z)𝖠Hostile(z)⇒Criminal(x)
 Nono. .. hassomemissiles,
i.e.,∃x Owns(Nono,x)𝖠Missile(x):
Rule 2. Owns(Nono, M1) and
Rule 3.Missile(M1)
 ... allof itsmissileswere sold toit byColonel West
Rule4.∀xMissile(x)𝖠Owns(Nono,x)⇒Sells(West,x,Nono)
 Missilesareweapons:
Rule5.Missile(x)⇒Weapon(x)
 AnenemyofAmericacountsas “hostile”:
Rule6. Enemy(x,America)⇒Hostile(x)
 West,whoisAmerican...
Rule7. American(West)
 ThecountryNono,anenemyofAmerica...
Rule8. Enemy(Nono,America)

18

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Asimpleforward-chainingalgorithm:
 Startingfromtheknownfacts,ittriggersalltheruleswhosepremisesaresatisfied, adding their
conclusions lo the known facts
 Theprocessrepeatsuntil thequeryisansweredornonewfactsareadded.Noticethatafact is not
"new" if it is just renamingof a known fact.

WewilluseourcrimeproblemtoillustratehowFOL-FC-ASKworks.Theimplication sentences are


(1), (4), (5), and (6). Two iterations are required:
 Onthefirstiteration,rule(1)hasunsatisfiedpremises.
Rule(4)issatisfiedwith{x/Ml),andSells(West,M1,Nono)isadded.Rule(5)issatisfied with
{x/M1)andWeapon(M1)isadded.
Rule(6)issatisfiedwith{x/Nono},andHostile(Nono)isadded.
 Ontheseconditeration,rule(1)issatisfiedwith{x/West,Y/MI,z/Nono),andCriminal
(West)isadded.
It is sound, because every inference is just an application of Generalized Modus Ponens, it is
completefordefiniteclauseknowledgebases;thatis,itanswerseveryquerywhoseanswersare
entailed by any knowledge base of definite clauses

19

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Efficientforwardchaining:
Theabovegivenforwardchainingalgorithmwaslackwithefficiencyduetothethe three sources of
complexities:
 PatternMatching
 Recheckingof everyrule on everyiterationevenafew additionsaremadeto rules
 Irrelevantfacts

1. Matchingrulesagainstknownfacts:
Forexample,considerthisrule,
Missile(x)AOwns(Nono,x)=>Sells(West,x,Nono).

The algorithm will check all the objects owned by Nono in and then for each object, it could
check whether it is a missile. This is the conjunct ordering problem:
―Findanorderingtosolvetheconjunctsoftherulepremisesothatthetotalcostisminimized‖. The
most constrainedvariable heuristic used for CSPswould suggest orderingthe conjuncts to
look for missiles first if there are fewer missiles than objects that are owned byNono.
Theconnectionbetweenpatternmatchingandconstraintsatisfactionisactuallyveryclose.We can
view eachconjunct asaconstraint onthe variables thatitcontains-for example,Missile(x) is a
unary constraint on x. Extending this idea, we can express everyfinite-domain CSP as a single
definite clause together with some associated ground facts. Matching a definite clause against
a set of facts is NP-hard.

20

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

2. Incrementalforwardchaining:
Ontheseconditeration,therule Missile(x)=>Weapon(x)
Matches against Missile (M1) (again), and of course the conclusion Weapon(x/M1) is already
known so nothing happens. Such redundant rule matching can be avoided if we make the
following observation:
―Everynew fact inferred on iteration t must be derived from at leastone new fact inferred on
iteration t – 1‖.
This observation leads naturally to an incremental forward chaining algorithm where, at
iteration t, we check a rule onlyif its premise includes a conjunct p, that unifies with a fact p:
newlyinferredatiterationt-1.Therulematchingstepthenfixesp,tomatchwithp’,butallows the other
conjuncts of the rule to match with facts from any previous iteration.

3. Irrelevantfacts:
 Onewaytoavoiddrawingirrelevantconclusionsistousebackward chaining.
 Anothersolution istorestrict forwardchainingtoaselectedsubset ofrules
 Athirdapproach,istorewrite theruleset,usinginformationfromthegoal.sothat only
relevant variable bindings-those belonging to a so-called magic set-are considered during
forward inference.
For example, if the goal is Criminal (West), the rule that concludes Criminal (x) will be
rewritten to include an extra conjunct that constrains the value of x:

Magic(x)AAmerican(z)AWeapon(y)ASells(x,y,z) AHostile(z)=>Criminal(x)

ThefactMagic(West)isalsoaddedtotheKB. Inthisway,eveniftheknowledgebasecontains facts


about millions of Americans, only Colonel West will be considered during the forward
inference process.

4. BackwardChaining

Thisalgorithmworkbackwardfromthegoal,chainingthroughrulestofindknownfactsthatsupport the
proof. It is called with a list of goals containing the original query, and returns the set of all
substitutions satisfyingthe query. The algorithmtakesthefirst goalin the list andfinds everyclause in
the knowledge base whose head, unifies with the goal. Each such clause creates a new recursive call
in which body, of the clause is added to the goal stack .Remember that facts are clauses with a
headbutnobody, so whena goalunifies witha knownfact,nonew sub goalsare addedtothe stack
andthegoalissolved.Thealgorithmforbackwardchainingandprooftreeforfindingcriminal(West) using
backward chaining are given below.

21

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

22

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Logicprogramming:
 Prologisbyfarthemostwidelyusedlogicprogramminglanguage.
 Prologprogramsaresetsofdefiniteclauseswritteninanotationdifferentfromstandardfirst- order
logic.
 Prologusesuppercaselettersforvariablesandlowercaseforconstants.
 Clausesarewrittenwiththe headprecedingthebody; ":-"isusedforleftimplication,
commas separate literals in the body, and a period marks the end of a sentence.
Prologincludes"syntacticsugar"forlistnotationandarithmetic.Prologprogramforappend

criminal(X):-american(X),weapon(Y),sells(X,Y,Z), hostile(Z).

(X,Y,Z),whichsucceeds iflistZistheresultofappendinglistsxand Y

append([],Y,Y).
append([A|X],Y,[A|Z]):-append(X,Y,Z).

Forexample,wecanaskthequeryappend(X,Y,[1,2]):whattwolistscanbeappendedtogive [1, 2]?


We get back the solutions

X=[] Y=[1,2];
X=[1] Y=[2];
X=[1,2] Y=[]

 TheexecutionofPrologprogramsisdoneviadepth-firstbackwardchaining
 Prolog allows a form of negation called negation as failure. A negated goal not P is
considered proved if the system fails to prove p. Thus, the sentence
Alive(X):-notdead(X)canbereadas"Everyoneisaliveifnotprovablydead."
 Prologhas anequalityoperator,=,butitlacksthe fullpoweroflogicalequality. An equalitygoal
succeeds if the two terms are unifiable and fails otherwise. So X+Y=2+3 succeeds with x bound
to 2 and Y bound to 3, but Morningstar=evening star fails.
 TheoccurcheckisomittedfromProlog'sunificationalgorithm.

Efficientimplementationoflogicprograms:
TheexecutionofaPrologprogramcanhappenintwomodes:interpretedandcompiled.
 Interpretation essentially amounts to running the FOL-BC-ASK algorithm, with the program as
the knowledge base. These are designed to maximize speed.

23

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

First, instead of constructing the list of all possible answers for each sub goal before
continuingtothenext,Prologinterpretersgenerateoneansweranda"promise"togeneratetherest when
the current answer has been fully explored. This promise is called a choice point.
FOL-BC-ASK spends a good deal of time in generating and composing substitutionswhena
pathinsearchfails.Prologwillbackuptopreviouschoicepointandunbindsomevariables.
Thisiscalled―TRAIL‖.So,newvariableisboundbyUNIFY-VAR anditispushed onto trail.

 PrologCompilers compile intoan intermediatelanguage i.e., Warren Abstract Machine or WAM


named after David. H. D. Warren who is one of the implementers of first prolog compiler. So,
WAM is an abstract instruction set that is suitable for prolog and can be either translated or
interpreted into machine language.
Continuationsareusedtoimplementchoicepoint’scontinuationaspackagingupaprocedureand a list
of arguments that together define what should be done next whenever the current goal succeeds.
 Parallelizationcanalsoprovidesubstantialspeedup.Therearetwoprincipalsourcesofparallelism
1.Thefirst,calledOR-parallelism,comesfromthepossibilityofagoalunifyingwithmanydifferent clauses
in the knowledge base. Each gives rise to an independent branch in the search space that can lead
to a potential solution, and all such branches can be solved in parallel.
2.The second, called AND-parallelism, comes from the possibilityof solving each conjunct in the
bodyofanimplicationinparallel.AND-parallelismismoredifficulttoachieve,becausesolutions for the
whole conjunction require consistent bindings for all the variables.
Redundantinferenceandinfiniteloops:
Considerthefollowinglogicprogramthatdecidesifapathexistsbetweentwopointsonadirected graph.
path(X,Z):- link(X,Z).
path(X,Z):-path(X,Y), link(Y,Z).

Asimplethree-node graph, describedbythefactslink(a,b)andlink (b, c)

24

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Itgeneratesthequerypath(a,c)
Henceeachnodeisconnectedtotworandomsuccessorsinthenextlayer.

Constraintlogicprogramming:
The Constraint Satisfaction problem can be solved in prolog as same like backtracking
algorithm.
Becauseitworks only for finitedomain CSP’s inprolog terms theremustbefinitenumberof
solutions for any goal with unbound variables.
triangle(X,Y,Z):-
X>0,Y>0,Z>0,X+Y>=Z,Y+Z>=X,X+Z>=Y.

 Ifwehave aquery,triangle (3,4, and5)worksfinebutthequerylike,triangle(3,4,Z)no solution.


 Thedifficultyisvariablein prologcan bein oneoftwo statesi.e.,Unboundor bound.
 Bindingavariabletoaparticulartermcanbeviewedasanextremeformofconstraintnamely
―equality‖.CLPallowsvariablestobeconstrainedratherthanbound. The
solution to triangle (3, 4, Z) is Constraint 7>=Z>=1.

5. Resolution
Asinthepropositionalcase,first-orderresolutionrequiresthatsentencesbeinconjunctive normal
form(CNF) that is, a conjunctionof clauses, where eachclauseis a disjunctionof literals.

Literalscancontain variables, whichareassumed to beuniversallyquantified.Everysentenceof

25

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

first-orderlogic canbeconvertedintoaninferentiallyequivalent CNFsentence.Wewillillustrate the


procedure by translating the sentence
"Everyonewholovesallanimalsislovedbysomeone,"or
∀x[∀yAnimal(y)⇒Loves(x,y)]⇒[∃yLoves(y, x)].
Thestepsareasfollows:
Step1. Eliminateimplications:
∀x[¬∀y¬Animal(y)∨Loves(x,y)]∨[∃yLoves(y, x)].
Step 2. MoveNegationinwards:Inadditiontotheusualrulesfornegatedconnectives,weneed rules
for negated quantifiers. Thus, we have
¬∀xpbecomes∃x¬p
¬∃xpbecomes∀x¬p.
Oursentencegoesthroughthefollowingtransformations:

∀x[∃y¬(¬Animal(y)∨Loves(x,y))]∨[∃yLoves(y,x)].
∀x[∃y¬¬Animal(y)∧¬Loves(x,y)]∨[∃yLoves(y,x)].
∀x[∃yAnimal(y)∧¬Loves(x,y)]∨[∃yLoves(y,x)].

Step 3. Standardize variables: For sentences like (∃x P(x)) ∨(∃x Q(x))which use the same
variable name twice, change the name of one of the variables. This avoids confusion later when
we drop the quantifiers. Thus, we have
∀x[∃yAnimal(y)∧¬Loves(x,y)]∨[∃zLoves(z,x)].
Step 4. Skolemize: Skolemization is the process of removing existential quantifiers by
elimination. Translate 3 x P(x) into P(A), where A is a new constant. If we apply this rule to our
sample sentence, however, we obtain

∀x[Animal(A)∧¬Loves(x,A)]∨Loves(B,x),

Whichhasthewrongmeaningentirely:it saysthateveryoneeitherfailstoloveaparticularanimal A or is
loved bysome particular entity B. In fact, our original sentence allows eachperson to fail to love a
different animal or to be loved by a different person.
Thus,wewanttheSkolementitiestodependonx:

∀x[Animal(F(x))∧¬Loves(x,F(x))]∨Loves(G(z),x).
HereFandGareSkolemfunctions.ThegeneralruleisthattheargumentsoftheSkolemfunction are all
the universallyquantified variables in whose scope the existential quantifier appears.

26

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Step 5. Dropuniversal quantifiers:At this point, all remainingvariablesmust be universally


quantified.Moreover,the sentence isequivalenttoone inwhichallthe universalquantifiershave been
moved to the left. We can therefore drop the universal quantifiers
[Animal(F(x))∧¬Loves(x,F(x))]∨Loves(G(z),x).

Step6. Distribute∨over𝖠

[Animal(F(x))∨Loves(G(z),x)]∧[¬Loves(x,F(x)) ∨Loves(G(z),x)] .

ThisistheCNFformofgivensentence.
Theresolutioninference rule:
The resolution rule for first-order clausesis simplya lifted version of the propositional resolution
rule.Propositionalliteralsarecomplementaryifoneisthenegationoftheother;first-orderliterals
arecomplementary ifoneunifies withthenegationof theother. Thus wehave

WhereUNIFY(li,mj)==θ.
Forexample,wecanresolvethetwoclauses
[Animal(F(x))∨Loves(G(x),x)]and[¬Loves(u,v)∨¬Kills(u,v)]
ByeliminatingthecomplementaryliteralsLoves(G(x),x)and¬Loves(u,v),withunifier θ
={u/G(x), v/x), to produce the resolvent clause

[Animal(F(x))∨¬Kills(G(x),x)].
Exampleproofs:
ResolutionprovesthatKB/=aby provingKBAlaunsatisfiable,i.e.,by derivingtheempty clause. The
sentences in CNF are

27

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Theresolutionproofisshowninbelowfigure;

Noticethestructure:single"spine"beginningwiththegoalclause,resolvingagainstclausesfrom the
knowledge base until the empty clause is generated. Backward chaining is really just a specialcase
of resolution with a particular control strategyto decide which resolution to perform next.
Example2:
Everyonewholovesallanimalsislovedbysomeone. Anyone
who kills an animal is loved by no one.
Jacklovesallanimals.
EitherJackorCuriositykilledthecat,whoisnamedTuna. Did
Curiosity kill the cat?
First,expresstheoriginalsentences,somebackgroundknowledge, andthenegatedgoalGinfirst-orderlogic:
• Ax[AyAnimal(y)⇒Loves(x,y)]⇒[∃yLoves(y,x)]
• Ax[∃zAnimal(z)∧Kills(x,z)]⇒[Ay¬Loves(y,x)]
• AxAnimal(x)⇒Loves(Jack,x)
• Kills(Jack,Tuna)∨Kills(Curiosity,Tuna)
• Cat(Tuna)
• AxCat(x) ⇒Animal(x)
¬G. ¬Kills(Curiosity,Tuna)

28

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

NowapplytheconversionproceduretoconverteachsentencetoCNF: A1.

Animal(F (x)) ∨ Loves(G(x), x)


A2. ¬Loves(x,F(x))∨Loves(G(x),x)
B. ¬Loves(y,x)∨¬Animal(z)∨¬Kills(x,z)
C. ¬Animal(x)∨Loves(Jack,x)
D. Kills(Jack,Tuna)∨Kills(Curiosity,Tuna)
E. Cat(Tuna)

F. ¬Cat(x)∨Animal(x)
¬G. ¬Kills(Curiosity,Tuna)
TheresolutionproofthatCuriosity killedthecatisgiveninFigure9.12.

29

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

Artificial Intelligence

Completenessofresolution

Tocarryoutthefirststep, weneedthreenewconcepts:
• Herbranduniverse: If Sisasetof clauses,thenHS,theHerbranduniverseof S,istheset of all ground
terms constructable from the following:
a. ThefunctionsymbolsinS,ifany.
b. TheconstantsymbolsinS,ifany;ifnone,thentheconstantsymbol A.
Forexample,ifScontainsjusttheclause¬P(x,F(x,A))∨¬Q(x,A)∨R(x,B),then
HSisthefollowinginfinitesetofground terms:
{A,B, F(A,A),F(A, B),F(B,A),F(B,B),F (A,F(A,A)),. ..}.
• Saturation:IfSisasetofclausesand P isasetofground terms, then P (S),thesaturation of S with
respecttoP,isthesetof allgroundclausesobtainedbyapplyingallpossibleconsistentsubstitutions of
ground terms in Pwith variables in S.
• Herbrandbase:ThesaturationofasetSofclauseswithrespecttoitsHerbranduniverseiscalledthe Herbrand
base of S, written as HS(S).For example, if S contains solely the clause just given, then HS(S) is the
infinite set of clauses
{¬P(A,F(A,A))∨¬Q(A,A)∨R(A,B),
¬P(B,F(B,A))∨¬Q(B,A)∨R(B,B),
¬P(F(A,A),F(F(A,A),A))∨¬Q(F(A,A),A)∨R(F(A,A),B),
¬P(F(A,B),F(F(A,B),A))∨¬Q(F(A,B),A)∨R(F(A,B),B),...}

30

Downloaded by Abtahi Sayed ([email protected])


lOMoARcPSD|45581143

ArtificialIntelligence

QuestionBank

1. ExplainthesyntaxandsemanticsofFirstOrderLogic.Provideexamplestoillustratethestructure of
FOL statements.[Jan 2024]
2. ExplainUniversalandExistentialquantifiersandalsoexplainconnectionsbetweenthem.
3. Explainthefollowingwithrespecttofirst-orderlogic: [Jan2024]
i) Assertions and queries ii) The Kinship domain iii) Numbers, Sets and Lists iv)Wumpus
world
4. CompareandcontrastpropositionalinferencewithFirstOrderLogicinference.Whatadditionalcapabilities
does FOL inference offer?
5. Defineinference in thecontextof FirstOrderLogic.How does inferencecontributeto deriving new
knowledge from existing knowledge?
6. Provideexamplesofhowinferencecanbeappliedtodrawconclusionsinagivenknowledgebase represented in
FOL.
7. Discuss scenarios where Propositional Logic is more suitable and where First Order Logic is necessary
for effective inference.
8. Explain the concept of unification in First Order Logic. How does unification contribute to the process
of reasoning? Write unification algorithm.
9. ExplainUnificationandSimpleforwardchainingalongwiththeexamples.[Jan2024]
(write algorithms)
10. Explainsimpleforwardchaining algorithmandproof treegeneratedwith example.
11. DescribetheprinciplesofforwardchaininginFOL.Provideexamplestoillustratehowforwardchaining works
in practice.
12. Explainbackwardchainingalgorithmandprooftreeconstructedbybackwardchaining.[Jan 2024]
13. OutlinetheprocessofbackwardchaininginFirstOrderLogic.Howisitdifferentfromforwardchaining?
14. ExplaintheconceptofresolutioninFOL.Howdoesresolutioncontributetotheresolution-based inference
process?
15. Explainthe Structure ofcompletenessproofforresolution.

31

Downloaded by Abtahi Sayed ([email protected])

You might also like