1 search. 2 search involves trying to find a particular object from a large number of such objects....

109
1 SEARCH SEARCH

Upload: barnard-scott

Post on 02-Jan-2016

219 views

Category:

Documents


4 download

TRANSCRIPT

1

SEARCHSEARCH

2

Search involves trying to find a particular object from a large number of such objects.

A search space defines the set of objects that we are interested in searching among.

A few Examples:

Board games. The system searches for a move that is likely to lead to winning configuration.

Theorem proving. Given the axioms and the rules of inference, the objective in this case is to find a

proof whose last line is the formula that one wishes to prove.

SEARCHSEARCH

3

• One widely used way to describe

problems is by listing or describing

all possible states.

• Solving a problem means moving

through the state space from a start

state to a goal state.

• Need to devise a set of operators that

move from one state to another.

STATE SPACE PROBLEM STATE SPACE PROBLEM DEFINITIONDEFINITION

4

STATE SPACE PROBLEM STATE SPACE PROBLEM DEFINITIONDEFINITION

• Set of possible states.

• Set of possible operations that

change the state.

• Specification of a starting

state(s).

• Specification of a goal state(s).

5

STATE SPACESTATE SPACE

• It is usually not possible to list all

possible states because of various

constraints:

– Use abstractions to describe states.

– Use a general description of the state

space.

– Describe set of constraints.

6

OPERATIONSOPERATIONS

• The problem solving system moves from

one state to another according to well

defined operations.

• Typically these operations are described as rules

.

• A control system decides which rules are

applicable at any state, and resolves conflicts

and/ or ambiguities.

7

Goal: 2 Gallons Water in the 4 Gallon Jug

EXAMPLE: WATER JUG PROBLEM

3 Gal4 Gal

8

•The state can be represented by 2 integers x and y:

•x = gallons in the 4 gallon jug

•y = gallons in the 3 gallon jug

•State Space = (x, y)

•Such that: •x = {0,1,2,3,4}

•y = {0,1,2,3}

WATER JUG STATE SPACE

9

WATER JUG PROBLEMSTART AND GOAL STATES

• The start state is when both jugs are

empty:

(0,0)

• The goal state is any state that has 2

gallons in the 4 gallon jug:

(2, n) for any n

10

WATER JUG OPERATIONS

• Fill 3 gal. jug from pump (x, y) -> (x, 3)

• Fill 4 gal. jug from pump (x, y) -> (4, y)

• Empty 3 gal. Jug (x, y) -> (x, 0)

• Empty 4 gal. Jug (x, y) -> (0, y)

• Pour contents of 3 gal. Jug (x, y) -> (y+x ,0) into 4

gal. Jug

11

(0,0) (1,0) (2,0) (3,0) (4,0)

(0,1) (1,1) (2,1) (3,1) (4,1)

(0,2) (1,2) (2,2) (3,2) (4,2)

(0,3) (1,3) (2,3) (3,3) (4,3)

WATER JUG STATE SPACEStart State

Goal States

12

WATER JUG TREE (PARTIAL)

0,0

4,0 0,3

4,1 4,2 4,3 1,3 2,3 3,3

13

SEARCH TREES• The search for a solution can be described by

a tree - each node represents one state.

• The path from a parent node to a child node

represents an operation.

• Search Trees provide a convenient

description of the search space, they are not

a data structure stored in memory!!!

14

GRAPH THEORYGRAPH THEORYA graph consists of :-

• A set of nodes N1, N2, N3, … , Nn…

• A set of arcs that connects pair of nodes.

• Arcs are ordered pairs of nodes, i.e. the arc (N3, N4)

connects node N3 to node N4. This means a directed

connection from N3 to N4.

• If a directed arc connects node Nj to node Nk,

– Then Nj is called parent of Nk

– And Nk is called child of Nj.

• If the graph also contains an arc (Nj, Nl) then Nk and

Nl are called siblings.

15

GRAPH THEORYGRAPH THEORYA graph consists of :-

• A rooted graph has a unique node Ns. All paths in the

graph originates from this node. That means Ns has

no parents.

• A tip of a leaf node has no children.

• A path that contains any node more than once, is said

to contain a cycle or loop.

• A tree is a graph in which there is a unique path

between each pair of nodes. The paths in a tree

therefore contains no cycles or loops.

16

• A graph consists of a set of nodes and a set of arcs or

links connecting pairs of nodes.

• In the stats space model of problem solving the nodes of

a graph are taken to represent discrete states of a

problem solving process. Such as:-

– Results of logical inferences

– Configurations of a game board.

GRAPH THEORYGRAPH THEORY

17

• The arcs of graph represent transitions between states

or the act of applying a rule, such as:-

– Logical inferences.

– Legal moves of a game.

GRAPH THEORYGRAPH THEORY

18

GRAPH THEORYGRAPH THEORY

A labeled directed graph.

19A rooted tree, exemplifying family relationships.

GRAPH THEORYGRAPH THEORY

20

STATE SPACE SEARCHSTATE SPACE SEARCH

21

• The theory of state space search is our

primary tool for successful design and

implementation of search algorithms.

• We can use graph theory to analyze the

structure and complexity of both the

problem and the procedure used to solve

it by representing the problem as a state

space graph.

STATE SPACE SEARCHSTATE SPACE SEARCH

22

EXAMPLES OF EXAMPLES OF

STATE SPACESTATE SPACE

23

• We studied predicate calculus as an example of an

artificial intelligence representational language.

• Well formed predicate calculus expressions provides a

means of describing objects and relations in a problem

domain, and inference rules such as modus ponens

allow us to infer new knowledge from these

descriptions.

• These inferences define a space that is searched to find

a problem solution.

STATE SPACE STATE SPACE

24

A R T I F I C I A L I N T E L L I G E N C E: Structure and Strategies for Complex Problem Solving, 4th Edition George F. Luger © 2002 Addison Wesley

Slide II.7

Figure II.5: Portion of the state space for tic-tac-toe.

25

•There are 39 (19683) ways to arrange (Blank, X, O) in nine spaces.

•State space is a graph.

•The graph is a “directed acyclic graph”.

•Complexity of Problem (No of possible move paths)

•Nine possible first moves.

•Eight possible responses to each first move at 2nd level.

•Seven possible responses to each 2nd level move at 3rd level. And so on …

•So 9 x 8 x 7 …, or 9! = 362,880 possible games paths can be generated.

DESCRIPTION OF STATE SPACEDESCRIPTION OF STATE SPACE

TIC- TAC-TOETIC- TAC-TOE

26

•Tic-Tac-Toe has 9! possible games paths.

•Chess has 10120 possible game paths.

•Checker has 1040 possible game paths.

•Problem spaces with these large number of possible paths, are difficult or impossible to search exhaustively.

•Strategies must be defined to reduce the complexity of the problem.

•These strategies, however, rely on heuristics to reduce the complexity of the search.

DESCRIPTION OF STATE SPACEDESCRIPTION OF STATE SPACE

TIC- TAC-TOETIC- TAC-TOE

27

State space of the 8-puzzle generated by “move blank” operations.

28

4 possible moves for Blank , , ,

State space is a graph.

More than one paths may exist to reach to one node (state) or most states may have multiple parents. Therefore cycles are possible.

GD is a particular state or board configuration. When this state is found on a path the search terminates.

The path from START to the GOAL is the desired series of moves.

EXAMPLE OF 8- PUZZLE.EXAMPLE OF 8- PUZZLE.

29

A salesperson needs to visit five cities and then return home.

GD Find shortest possible path for the sales person to travel to cities and then return home.

Sales person lives in city ‘A’. He will return to city ‘A’ after completing the tour. So the state space consists of (n-1) nodes.

One possible path.A, D, C, B, E, A = 450 miles.

GD requires a complete circuit with minimum distance covered.

GD in this example is a property of entire path.

THE TRAVELING SALESPERSON THE TRAVELING SALESPERSON

30

An instance of the traveling salesperson problem.

31

Search of the traveling salesperson problem. Each arc is marked with the total weight of all paths from the start node (A) to its endpoint.

32

Complexity

Complexity of exhaustive search in this problem is (N-1)!, i.e. 5! (120) paths.

For small number of cities the search is possible exhaustively.

But for, problem instances, for example, where N = 50 simple exhaustive search cannot be restored to.

For a N! search grows so fast that very soon the search combinations become intractable.

THE TRAVELING SALESPERSON THE TRAVELING SALESPERSON

33

Data Driven and Goal Driven Search

•State space may be searched in two directions:-

•From given data of a problem instance towards a goal

Data of a problem Goal

•From a goal back to the data

Goal Data

STRATEGIES FOR STATE SPACE SEARCHSTRATEGIES FOR STATE SPACE SEARCH

34

Data Driven Search (Also Called Forward Chaining)

The problem solver begins with given facts of the problem and

a set of legal moves or rules for changing states.

Search proceeds as follows:-

Applying rules to facts to produce new facts.

New facts are used by rules to produce more new facts.

Process continues until it generates a path or state that

satisfies the goal condition.

Data driven search uses the knowledge and constraints found

in the given data of a problem to guide search along lines known

to be true.

STRATEGIES FOR STATE SPACE SEARCHSTRATEGIES FOR STATE SPACE SEARCH

35

Goal Driven Search (Also Called Backward Chaining)

Take the goal that we want to solve.

See what rules or legal moves could be used to generate this goal. Also determine what conditions must be true to use these rules.

These conditions become the new goals or subgoals for the search.

Reaching subgoals, determining new subgoals and so on…

Search continues, working backward through successive subgoals until it works back to the facts of the problem.

Goal driven search thus uses knowledge of the desired goal to guide the search through relevant rules and eliminate branches of the space.

STRATEGIES FOR STATE SPACE SEARCHSTRATEGIES FOR STATE SPACE SEARCH

36

• Both data-driven an goal-driven problem solvers

search the same state space graph, however, the

order and actual number of states searched can be

different.

• The preferred strategy is determined by the

properties of the problem itself. These includes:-

– The complexity of the rules.

– The shape of the state space.

– The nature and availability of the problem data.

STRATEGIES FOR STATE SPACE SEARCHSTRATEGIES FOR STATE SPACE SEARCH

37

• Data-driven search will by preferred for problems in which:-

– All are most of the data are given in the initial problem

statement.

– There are a large number of potential goals, but there

are only a few ways to use the facts and given

information of a particular problem instance.

– It is difficult to form a goal or hypothesis.

STRATEGIES FOR STATE SPACE SEARCHSTRATEGIES FOR STATE SPACE SEARCH

38

• Goal-driven search will be preferred for problems in which:-

– A goal or hypothesis is given in the initial problem statement or can easily be formulated.

– There are a large number of rules that match the facts of the problem and thus produce an increasing number of conclusions or goals. Early selection of a goal can eliminate most of these branches, making goal driven search more effective.

– Problem data are not given but must be acquired by the problem solver. In this case goal driven search can help guide data acquisition.

STRATEGIES FOR STATE SPACE SEARCHSTRATEGIES FOR STATE SPACE SEARCH

39

State space in which goal-directed search effectively prunes extraneous search paths.

40

State space in which data-directed search prunes irrelevant data and their consequents and determines one of a number of possible goals.

41

IMPLEMENTING SEARCHIMPLEMENTING SEARCHALGORITHMSALGORITHMS

42

In solving a problem using either Goal-or-Data

based search, a problem solver must find a path

from a start to a goal through the state space graph.

The sequence of the arcs in this path corresponds

to the ordered steps of the solution.

A problem solver must consider different paths

until it finds a goal.

SEARCH ALGORITHMSSEARCH ALGORITHMS

43

Backtracking Search The algorithm begins at start state, pursue a path until reaches

either a goal or a dead end.

If it finds a goal, it returns the path.

It it finds a dead end:-

It backtracks to the most recent node on the path (node S).

Pursue a new path along one of unexamined child of node S.

If the backtrack does not find a goal in this subgraph repeat the procedure for all siblings of node S.

If none of the siblings leads to a goal. Then backtrack to the parent node of node S.

The procedure may be applied to all siblings of node S, and so on.

SEARCH ALGORITHMSSEARCH ALGORITHMS

44

Backtracking search of a hypothetical state space.

45

An algorithm which performs a backtrack search uses

three lists to keep track of nodes in the state space:-

SL (State List). Lists the states in the current path

being tried. If the goal is found, SL contains

the ordered list of states on the solution path.

NSL (New State List). Contains nodes awaiting

evaluation, i.e. nodes whose descendants have not

yet been generated and searched.

ALGORITHM ALGORITHM FOR BACKTRACK SEARCHFOR BACKTRACK SEARCH

46

• DE (Dead End). Lists the states whose

descendant have failed to contain a goal node. It

is used to detect any re-entry of such a state.

• CS (Current State). Data structure to hold state being

currently explored.

• To avoid re-entry of a state already occurred (to avoid

loops), each newly generated state is tested for

membership in above lists. If new state belongs to any

of these lists, it has already been visited so may be

ignored.

ALGORITHM ALGORITHM FOR BACKTRACK SEARCHFOR BACKTRACK SEARCH

47

Function backtrack algorithm

48

A trace of backtrack on the graph of figure 3.12

49

BLIND SEARCHBLIND SEARCH(UNINFORMED SEARCH)(UNINFORMED SEARCH)

50

BLIND SEARCHBLIND SEARCH• These search methods are called blind

because they make no use of information

concerning where the goal might be located

in the search space.

• Instead they exhaustively search the space,

checking each object for a possible goal.

• These methods include:-

• Breadth First Search.

• Depth First Search.

• Depth First Iterative Deepening Search.

51

In addition to specifying a search direction

(data-driven or goal-driven), a search

algorithm must determine the order in which

states are examined in the graph.

Two possibilities for the order in which the

nodes of the graph may be considered:-

Depth-first search.

Breadth-first search.

DEPTH-FIRST AND BREADTH-FIRST SEARCH

52

STATE SPACE

53

This explores the space in a level-by-level fashion.

Only when there are no more states to be explored

at a given level does the algorithm move on to the

next level.

For this search the graph of Figure considers the

states in the order A, B, C, D, E, F, G, H, I, J, K, L,

M, N, O, P, Q, R, S, T, U.

BREADTH-FIRST SEARCH

54

Breadth-first search can be implemented with two

lists to keep track of progress through the state

space.

List OPEN

lists the states that have been generated but whose

children have not been examined.

The order in which states are removed from OPEN

determines the order of the search.

List CLOSED This list records states that have

already been examined.

BREADTH-FIRST SEARCH

55

BREADTH-FIRST SEARCH

Algorithm

56

A Trace of Breadth_First_Search Algorithm

BREADTH-FIRST SEARCH

57Breadth-First Search at Iteration 6.

States on OPEN and CLOSED are highlighted.

BREADTH-FIRST SEARCH

58Breadth First Search of the 8-puzzle

Showing Order in Which States Were Removed From OPEN.

BREADTH-FIRST SEARCH

59

Child states are generated by inference rules, legal moves of a game, or other state transition operators.

Each iteration produces all children of the state X and adds them to OPEN.

OPEN is maintained as a queue, or first-in-first-out (FIFO) data structure. States are added to the right of the list and removed from the left. This biases search toward the states that have been on OPEN the longest, causing the search to be breadth-first.

Child states that have already been discovered (already appeared on either OPEN or CLOSED) are eliminated.

If the algorithm terminates because the condition of the While Loop is no longer satisfied (OPEN = [ ] ) then it has searched the entire graph without finding the desired goal; meaning the search has failed.

BREATH-FIRST SEARCH

60

Breadth-first search considers every node at each level of the graph before going deeper into the space, all states are first reached along the shortest path from the start state.

Breadth-first search is therefore guaranteed to find the shortest path from the start state to the goal.

If the path is required for a solution, it can be returned by the algorithm.

This can be done by storing ancestor information along with each state.

A state may be saved along with a record of its parent state, i.e. as a (state, parent) pair.

If this is done in the search of Figure, the contents of OPEN and CLOSED at the fourth iteration would be:

OPEN = [(D, A), (E, B), (F, B), (D, C), (H, C)]

CLOSED = [(C, A), (B, A) , A, nil)]

BREATH-FIRST SEARCH

61

When a goal is found, the algorithm may construct the solution path by tracing back along parents from the goal to the start state.

A has a parent of nil, indicating that it is a start state: this stops reconstruction of the path.

Because breadth-first search finds each state along the shortest path and retains the first version of each state, this is the shortest path form a start to a goal.

BREATH-FIRST SEARCH

62

When a state is examined, all of its children and their descendants are examined before any of its siblings.

This goes deeper into the search space whenever this is possible. Only when no further descendants of a state can be found are its siblings considered.

This examines the states in the graph of Figure, in the order A, B, E, K, S, L, T, F, M, C, G, N, H, O, P, U, D, I, Q, J, R.

This search can be implemented with backtrack algorithm.

DEPTH-FIRST SEARCH

63

STATE SPACE

64

• The descendant states are both added and

removed from the left end of OPEN.

• OPEN is maintained as a stack, or last-in-

first-out (LIFO) structure.

• The organization of OPEN as a stack,

biases search toward the most recently

generated states, giving search a depth-

first order.

DEPTH-FIRST SEARCH

Algorithm

65

DEPTH-FIRST SEARCH

Algorithm

66

A Trace of Depth_First_Search Algorithm

DEPTH-FIRST SEARCH

67

DEPTH-FIRST SEARCH

depth-first search at iteration 6. States on OPEN and CLOSED are highlighted.

68Depth-first search of the 8-puzzle with a depth bound of 5.

DEPTH-FIRST SEARCH

69

Breadth-First Search

• Because it always examines all the nodes at level n before proceeding to level n + 1, it always finds the shortest path to a goal node.

• In a problem where it is known that a simple solution exists, this solution will be found.

• If there is a bad branching factor, i.e. states have a high average number of descendants, the combinatorial explosion may prevent the algorithm from finding a solution using the available space.

• The space utilization measured in terms of the number of states on OPEN, is an exponential function of the length of the path at any time.

COMPARISON

70

Breadth-First Search

• If each state has an average of B children, the

number of states on a given level is B times the

number of states on the previous level. This gives

Bn states on level n.

• Breadth-first search would place all of these on

OPEN when it begins examining level n. This can

be prohibitive if solution paths are long.

COMPARISON

71

Branching Factor = B = 2

N = 1Bn = 21 = 2

N = 2Bn = 22 = 4

N = 3Bn = 23 = 8

SPACE USAGE BY BREADTH FIRST SEARCH

72

COMPARISON

Depth-First Search

• This strategy gets quickly into a deep search space.

• If it is known that the solution path will be long, it will not waste time searching a large number of “shallow” states in the graph.

• On the other hand, it can get “lost” deep in a graph missing shorter path to a goal or even becoming stuck in an infinitely long path that does not lead to goal.

• It is much more efficient for search spaces with many branches because it does not have to keep all the nodes at a given level on the OPEN list

73

COMPARISON

Depth-First Search

• The space usage of depth-first search is a linear

function of the length of the path.

• At each level, OPEN retains only the children of a

single state.

• If a graph has an average of B children per state,

this requires a total space usage of B x n states to

go n levels deep into space.

74

Branching Factor = B = 2

N = 1B x N = 2 x 1 = 2

N = 22 x 2 = 4

N = 32 x 3 = 6

SPACE USAGE BY DEPTH FIRST SEARCH

75

DEPTH FIRST SEARCH WITH ITERATIVE DEEPENING

• As the depth search is likely to lost deep into a path,

therefore it is logical to use a depth-bound on the depth

first search at certain level.

• This causes a breadth like sweep of the search space at

that search level.

• When it is known that a solution lies within a certain depth

or when time constraints limit the number of states that

can be considered in a large space then a depth first

search with a depth-bound may be important.

76

DEPTH FIRST SEARCH WITH ITERATIVE DEEPENING

Algorithm• It performs a depth first search of the space with a depth

bound of 1. if it fails to find a goal, it performs another depth

first search with a depth bound of 2.

• This continues increasing the depth bound by one at each

iteration.

• At each iteration the algorithm performs a complete depth first

search to the current depth bound.

• Because the algorithm searches the space in a level by level

fashion, it is guaranteed to find a shortest path to a goal.

• Because it does only depth first search at each iteration, the

space usage at any level n is B x n, where B is the average

number of children of a node.

77

USING THE STATE SPACE TO REPRESENT

REASONING WITH THE PREDICATE

CALCULUS

78

State Space Description Of A Logical System

• Graph Theory defines that nodes must be distinguishable from one another, with each node representing state of the solution process.

• Predicate calculus can be used as the formal specification language for making these distinctions

• Predicate calculus can also be used for mapping the nodes of a graph onto the state space.

• Inference rules can be used to create and describe the arcs between states.

• In this fashion problems in the predicate calculus, determining whether a particular expression is a logical consequence of a given set of assertions, may be solved using search.

• The soundness and completeness of predicate calculus inference rules guarantee the correctness of conclusions derived through this form of graph-based reasoning.

79

Example. How a set of logical relationship may be viewed by defining a graph using propositional calculus.If p, q, r … are propositions, assume the assertions :-

From this set of assertions and the inference rule modus ponens,

certain propositions p, r and u have been inferred.

Propositions v and q may not be inferred and indeed do not

logically follow from these assertions, as v is not known to be true.

The relationship between the initial assertions and inferences is

expressed in the directed graph in the figure.

80

• The arcs correspond to logical implications (). • Propositions that are given as true (s and t) correspond to the give

data of the problem.• Propositions that are logical consequences of this set of assertions,

correspond to the nodes that may be reached along a directed path from a state representing a true proposition.

• Such a path corresponds to a sequence of applications of modus ponens.

• For example, the path (s,r,p) corresponds to the sequence of inferences :-

s and s r yields r r and r p yields p

81

AND / OR GRAPH• And / or graphs are an important tool for describing the search spaces generated by many AI problems.

• In expressions of the form q r p, both q and r must be true for p to be true.

• In expression of the form q r p the truth of either q or r is sufficient to prove that p is true.

• To represent these different relationships graphically, and/or graphs distinguish between and nodes and or nodes.

• If the premises of an implication are connected by an operator, they are called and nodes in the graph and the arcs from this node are joined by a curved link.

• The expression q r p is represented by the

and /or graph in the figure

• The link connecting the arcs captures the idea

that both q and r must be true to prove p.

82

• In case of or graph the premises are connected by an or operator, they are regarded as or nodes in the graph.

• As such implication q r p can also be represented as q p, and r p separately.

• This captures the notion that the truth of any one of the premises is independently sufficient to determine the truth of the conclusion.

AND / OR GRAPH

83

• In the example a goal–directed strategy for determining the truth of h

first attempts to prove both a and e.

• The truth of a is immediate, but the truth of e requires the truth of

both c and a, these are given as, true.

• Once the problem solver has traced all these-arcs down to true

propositions, the true values are recombined at the and nodes to

verify the truth of h.

EXAMPLE. Assume a situation in the world where the following propositions are true :

a e h

84

• A data-directed strategy for determining the truth of

h. on the other hand, begins with the known, facts

c,a and b and begins adding new propositions to

this set of known facts according to the constraints

of the and/or graph.

• The ‘e’ or ‘d’ might be the first proposition added to

the set of facts.

• These additions make it possible to infer new facts.

• This process continues until the desired goal, h,

has been proved.

85

FACTS AND THEIR PREDICATES

• Fred is a collie. collie (fred).

• Sam is Fred's master. master(fred,sam).

• It is Saturday. day(saturday).

• It is a cold Saturday. ( warm(saturday) ).

• Fred is a trained dog. trained (fred).

EXAMPLE

KNOWLEDGE BASE

• The example is taken from the predicate calculus and represents

a goal-driven graph search where the goal to be proved true is a

predicate calculus expression.

• The axioms are the logical descriptions of a relationship between

a dog Fred, and his master, Sam.

86

RULES AND THEIR PREDICATE EXPRESSIONS

• Spaniels or collies that are trained are good dogs.

X [spaniel (X) (collie (X) trained (X)) gooddog(X)]

• If a dog is a good dog and has a master then he will be with his master.

(X,Y,Z)[ gooddog (X) master (X,Y) location (Y,Z) location (X,Z)]

• If it is Saturday and warm, then Sam is at the park.day(saturday) warm(saturday) location(sam,park).

• If it is Saturday and not warm, then Sam is at the museum.day(saturday) ( warm(saturday) ) location(sam, museum).

87

• The goal is the expression X location (fred, X). Meaning “location of Fred”.

• A backward search algorithm examines alternative means of establishing the following goal:-

“If Fred is a good dog and Fred has a master and Fred’s master is at a location then Fred is at that location also.”

(X,Y,Z)[ gooddog (X) master (X,Y) location (Y,Z) location (X,Z)]

• The premises of this rule are then examined:

What does it mean to be a “good dog”

• As we know from the given data that Fred is a collie and it is trained as well: collie (fred).

trained (fred).

• And we also know the assertion that:

X [spaniel (X) (collie (X) trained (X)) gooddog(X)]

so it implies that Fred is a good dog.

88

• We also know from the given data that Fred has a master Sam.

master(fred,sam)

So it implies that Fred has a master.

• We also know the facts that on every Saturday, Sam is away from his home as follows:

– If it is Saturday and warm, then Sam is at the park.

day(saturday) warm(saturday) location(sam,park).

– If it is Saturday and not warm, then Sam is at the museum.

day(saturday) ( warm(saturday) ) location(sam, museum).

• We also know that it is a cold Saturday.

( warm(saturday) )

So It implies that Sam is at the museum.

So Fred is a good dog and Fred has a master and Fred’s master is at the museum, then Fred is at the museum.

(X,Y,Z)[ gooddog (X) master (X,Y) location (Y,Z) location (X,Z)]

• This situation may be represented in a and/or graph as:

89

90

FARMER WOLF GOAT AND CABBAG FARMER WOLF GOAT AND CABBAG PROBLEMPROBLEM

• A farmer comes with his wolf, goat and cabbage to the river bank he wishes to cross with above animals and vegetable.

• A boat is available to cross the river.

• Boat can carry only two things at a time including the farmer.

• If wolf is left alone with the goat, the wolf will eat the goat.

• If cabbage is left alone with the goat, the goat will eat the cabbage.

91

• States are represented as lists of four elements.

Where each element denotes the location of the

farmer, wolf, goat, or cabbage respectively.

Farmer, wolf, goat and cabbage => (f w g c)

• Thus state (e w e w) represent:-

– Farmer is on the eastern bank

– Wolf is on the western bank.

– Goat is on the eastern bank.

– Cabbage is on the western bank.

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

92

Function Solve-fwgc initiates the search.

(defun solve-fwgc (state goal)

(path state goal nil))

Function make-state define states of the world

(defun make-state (f w g c)

(list f w g c))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

93

Following functions define states of the world as an abstract data types.

(defun farmer-side ( state )

(nth 0 state))

(defun wolf-side ( state )

(nth 1 state))

(defun goat-side ( state )

(nth 2 state))

(defun cabbage-side ( state )

(nth 3 state))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

94

The function "opposite" takes a side and return the opposite side of the river.

(defun opposite (side)

(cond ((equal side 'e) 'w)

((equal side 'w) 'e)))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

95

Function Safe returns nil if a state is not safe; it returns the state unchanged if the state is safe.

(defun safe (state)

(cond ((and(equal(goat-side state)(wolf-side state))

(not (equal (farmer-side state) (wolf-side state)))) nil)

((and (equal (goat-side state) (cabbage-side state))

(not (equal (farmer-side state) (goat-side state))))nil)

(t state)))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

96

These functions define legal moves in the state space

(defun farmer-takes-self (state) (safe (make-state (opposite (farmer-side state))

(wolf-side state)

(goat-side state)

(cabbage-side state))))

(defun farmer-takes-wolf (state) (cond ((equal (farmer-side state) (wolf-side state))

(safe (make-state (opposite (farmer-side state)) (opposite (wolf-side state))

(goat-side state)

(cabbage-side state)))

(t nil)))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

97

These functions define legal moves in the state space(defun farmer-takes-goat (state) (cond ((equal (farmer-side state) (goat-side state)) (safe (make-state (opposite (farmer-side state))

(wolf-side state)(opposite (goat-side state))

(cabbage-side state))) (t nil)))

(defun farmer-takes-cabbage (state) (cond ((equal (farmer-side state) (cabbage-side state)) (safe (make-state (opposite (farmer-side state))

(wolf-side state) (goat-side state) (opposite (cabbage-side state))) (t nil)))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

98

The recursive path algorithm searches the space in a depth first fashion.

(defun path (state goal been-list)

(cond ((null state) nil)

((equal state goal)(reverse (cons state been-list)))

((not(member state been-list :test #'equal))

(or (path(farmer-takes-self state)goal(cons state been-list))

(path(farmer-takes-wolf state)goal(cons state been-list))

(path(farmer-takes-goat state)goal(cons state been-list))

(path(farmer-takes-cabbage state)goal(cons state been-list))))))

FARMER WOLF GOAT AND CABBAGE FARMER WOLF GOAT AND CABBAGE PROBLEMPROBLEM

99

THE STATE SPACEW W W W

W W E W

E E E W

E W W EE W E WE E W W E W W W

W W W W

W E W WW W E WW E E W

E W E EE W E W

W E W WW W W EW E W E

E E W EE E E WE E W W

E E E EE E W E

PATH = {(W W W W) (E W E W) (W W E W) (E E E W) (W E W W) (E E W E) (W E W E) (E E E E)}

100

BREADTH FIRST SEARCH

(setq *moves*

(farmer-takes-self farmer-takes-wolf

farmer-takes-goat farmer-takes-cabbage))

(defun run-breadth (start goal)

(setq *open* (list start))

(setq *closed* nil)

(setq *goal* goal)

(breadth-first))

101

(defun breadth-first ()

(cond ((null *open*) nil)

(t (let ((state (car *open*)))

(cond ((equal state *goal*) 'success)

(t (setq *closed* (cons state *closed*))

(setq *open*(append (cdr *open*)

(generate-descendants state

*moves*))) (breadth-first) ))))))

BREADTH FIRST SEARCH

102

(defun generate-descendants (state moves) (cond ((null moves) nil)

(t (let ((child (funcall (car moves) state))

(rest (generate-descendants state (cdr moves))))

(cond ((null child) rest)

((member child rest :test #'equal) rest)

((member child *open* :test #'equal) rest)

((member child *closed* :test #'equal) rest)

(t (cons child rest)))))))

(run-breadth ‘(w w w w) ‘(e e e e))SUCCESS

BREADTH FIRST SEARCH

103

DEPTH FIRST SEARCH

(defun depth-first ()

(cond ((null *open*) nil)

(t (let ((state (car *open*)))

(cond ((equal state *goal*) 'success)

(t (setq *closed* (cons state *closed*))

(setq *open* (append (generate-

descendants state *moves*)

(cdr *open*))) (depth-first) ))))))

104

BREADTH FIRST SEARCHWITH PARENT INFORMATION ATTACHED

(defun run-breadth (start goal moves)

(declare (special *open*))

(declare (special *closed*))

(declare (special *goal*))

(setq *open* (list (build-record start nil)))

(setq *closed* nil)

(setq *goal* goal)

(breadth-first moves))

105

BREADTH FIRST SEARCHWITH PARENT INFORMATION ATTACHED

These functions handle the creation and access of (state parent) pairs.

(defun build-record (state parent) (list state parent))

(defun get-state (state-tuple) (nth 0 state-tuple))

(defun get-parent (state-tuple) (nth 1 state-tuple))

106

(defun retrieve-by-state (state list) (cond ((null list) nil) ((equal state (get-state (car list))) (car list)) (t (retrieve-by-state state (cdr list)))))

(defun breadth-first (moves) (declare (special *open*)) (declare (special *closed*)) (declare (special *goal*)) (cond ((null *open*) nil) (t (let ((state (car *open*))) (setq *closed* (cons state *closed*))

BREADTH FIRST SEARCHWITH PARENT INFORMATION ATTACHED

107

(cond ((equal (get-state state) *goal*)

(reverse (build-solution *goal*)))

(t (setq *open*

(append (cdr *open*)

(generate-descendants

(get-state state)

moves)))

(breadth-first moves) ))))))

BREADTH FIRST SEARCHWITH PARENT INFORMATION ATTACHED

108

(defun generate-descendants (state moves) (declare (special *open*))

(declare (special *closed*))

(cond ((null moves) nil)

(t (let ((child (funcall (car moves) state))

(rest (generate-descendants state (cdr (moves))))

(cond ((null child) rest)

((retrieve-by-state child rest) rest)

((retrieve-by-state child *open*) rest)

((retrieve-by-state child *closed*) rest)

(t (cons (build-record child state) rest)))))))

BREADTH FIRST SEARCHWITH PARENT INFORMATION ATTACHED

109

(defun build-solution (state)

(declare (special *closed*))

(cond ((null state) nil)

(t (cons state (build-solution (get-parent

(retrieve-by-state state *closed*)))))))

BREADTH FIRST SEARCHWITH PARENT INFORMATION ATTACHED