340 likes | 467 Views
Using Structures: Example Programs. Notes for Ch.4 of Bratko For C ENG 421 Fall 03 Zeynep Orhan. Retrieving Structured Information. Prolog is a suitable language for retrieving structured information from a database No need to specify all details about the object components
E N D
Using Structures: Example Programs Notes for Ch.4 of Bratko For CENG 421 Fall03 Zeynep Orhan
Retrieving Structured Information • Prolog is a suitable language for retrieving structured information from a database • No need to specify all details about the object components • Unspecified or partially specified objects are allowable • See the examples of the book on page 98-99
Retrieving Structured Information • Examples: Objects we are interested inContent+structure(with unspecifed parts) • Need a better way of interaction with the databaseutility programs • Utility programs can form the user interfaces
Retrieving Structured Information • Each family has three components: husband, wife, and children, e.g.: family( person( tom, fox, date( 7, may, 1960), works( bbc, 15200)), person( ann, fox, date( 9, may, 1961), unemployed), [ person( pat, fox, date( 5, may, 1983), unemployed), person( jim, fox, data( 5, may, 1983), unemployed) ] ). • Database and relations in ch4_1.pl • 3 ?- family( H,W,C), total( [H,W|C],I), length([H,W|C],N), I / N < 10000.
Database family( person( tom, fox, date( 7, may, 1960), works( bbc, 15200)), person( ann, fox, date( 9, may, 1961), unemployed), [ person( pat, fox, date( 5, may, 1983), unemployed), person( jim, fox, data( 5, may, 1983), unemployed) ] ). family( person( marco, valtorta, date( 7, may, 1956), works( usc, 51000)), person( laura, valtorta, date( 12, january, 1958), works( self, 39000)), [ person( clara, valtorta, date( 10, september, 1984), unemployed), person( dante, valtorta, date( 7, april, 1995), unemployed) ] ).
Database-User Interface(cont’d) husband( X) :- family( X, _, _). wife( X) :- family( _, X, _). child( X) :- family( _, _, Children), member( X, Children). exists( Person) :- husband( Person); wife( Person); child( Person). dateofbirth( person( _, _, Date, _), Date). salary( person( _, _, _, works( _, S)), S). salary( person( _, _, _, unemployed), 0). /* total( List_of_people, Sum_of_their_salaries) */ total( [], 0). total( [ Person | List], Sum) :- salary( Person, S), total( List, Rest), Sum is S + Rest.
Doing Data Abstraction • Data abstraction can be viewed as a process of organizing various pieces of information into natural units(possibly hierachically) • Structuring the information into some conceptually meaningfull form • details should be invisible to the user • Programmer must be free and not think about how the information is actually represented
Solution I • Define relations so that the user can access particular components of a family without knowing the details • Selectors can be used to hide details of representation • Name of the selector is an indicator of the component it is selecting. selector_relation(Object,Component_selected) • Selectors given in the book
husband(family(Husband,_,_),Husband). • wife(family(_,Wife,_), Wife). • children(family(_,_,Children), Children ). • firstchild(Family,First):- children(Family,[First|_]). • secondchild(Family, Second):- children(Family,[_,Second|_]). • Generalize to Nth child. • nthchild(N,Family,Child):- children(Family,CL), nth_member(N,CL,Child).
Selectors for person Structure • firstname(person(Name,_,_,_),Name). • surname(person(_,SurName,_,_),SurName). • born(person(_,_,Date,_),Date). • What is the benefit of the selectors then? • Forget about the particular way of info. representation • Form/Manipulate these info:Know the selector names and use them
Benefits • Easier than always referring to the representation explicitly. • Easy modifications of the programs • We need to change the data representation to increase performance • Change the selectors only • The rest of the program will remain as unchanged
Simulating a Non-deterministic Automaton • Non-deterministic finite automaton (NFA) • accepts or rejects a string of symbols • has states • has transitions (possibly silent) • represented by a directed graph with self loops • with distinguished final states and initial state (e.g. fig. 4.3) • string is accepted if there is a transition path s.t. • it starts with the initial state • it ends with a final state • the arc labels along the path correspond to the complete input string
Simulation of NFA (II) • To simulate an NFA in Prolog, we need: • final/1, which defines the finals states • trans/3, s.t. trans(S1,X,S2) means that a transition from S1 to S2 is possible when X is read • silent/2 s.t. silent( S1,S2) means that a silent move is possible from S1 to S2.
nfa.pl • 6 ?- length(Str,7), accepts(S,Str). Str = [a, a, a, a, a, a, b] S = s1 ; • 5 ?- accepts(S, String), length(String, 7). ERROR: Out of local stack • 12 ?- accepts(s1,S). ERROR: Out of local stack • Why? • If the length of the input string is not limited, the recursion will never hit the empty list: the first clause will be missed. When the input string is limited, after exhausting all possible transitions consistent with it, the input will become empty and the first clause will be used.
/* Example of NFA simulation, Bratko, Section 4.3, Figure 4.3 */ final( s3). trans( s1, a, s1). trans( s1, a, s2). trans( s1, b, s1). trans( s2, b, s3). trans( s3, b, s4). silent( s2, s4). silent( s3, s1). accepts( State, []) :- final( State). % Accepts empty string accepts( State, [ X | Rest]) :- trans( State, X, State1), accepts( State1, Rest). accepts( State, String) :- silent( State, State1), accepts( State1, String).
Travel Agent • Program to give advice about air travel • timetable(Place1,Place2,ListOfFlights) • ListOfFlights holds terms of the form • DepartureTime/ArrivalTime/FlightNumber/ListOfDays, where / is an infix operator, e.g., timetable( london, edinburgh, [9:40 / 10:50 / ba4733 / alldays, 19:40 / 20:50 / ba4833 / [mo,tu,we,th,fr,su] ] ).
Finding Routes • route( Place1, Place2, Day, Route), where Route is a sequence of flights that satisfy: • the start point of the route is Place1 • the end point is Place2 • all the flights are on the same Day of the week • all the flights in Route are in the timetable relation • there is enough time for transfer between flights
Auxiliary Predicates • flight( Place1,Place2,Day,FlightNum,DepTime,ArrTime). • deptime( Route, Time). • transfer( Time1, Time2). • Note the similarity between the NFA simulation and the route finding problem: • states <-> cities • transitions <-> flights • path between initial and final state <-> route between start and end city
Route Relation • Direct connection: route( Place1, Place2, Day, [Place1/Place2/Fnum/Dep]) :- flight( Place1, Place2, Day, Fnum, Dep, Arr). • Indirect connection with sufficient transfer time: route( P1,P2,Day,[P1/P3/Fnum1/Dep1 | RestRoute]) :- route( P3,P2,Day,RestRoute), flight( P1,P3,Day,Fnum1,Dep1,Arr1), deptime( RestRoute, Dep2), transfer( Arr1,Dep2).
% Figure 4.5 A flight route planner and an example flight timetable. % A FLIGHT ROUTE PLANNER :- op( 50, xfy, :). % route( Place1, Place2, Day, Route): % Route is a sequence of flights on Day, starting at Place1, ending at Place2 route( P1, P2, Day, [ P1 / P2 / Fnum / Deptime ] ) :- % Direct flight flight( P1, P2, Day, Fnum, Deptime, _). route( P1, P2, Day, [ (P1 / P3 / Fnum1 / Dep1) | RestRoute] ) :- % Indirect connection route( P3, P2, Day, RestRoute), flight( P1, P3, Day, Fnum1, Dep1, Arr1), deptime( RestRoute, Dep2), % Departure time of Route transfer( Arr1, Dep2). % Enough time for transfer
flight( Place1, Place2, Day, Fnum, Deptime, Arrtime) :- timetable( Place1, Place2, Flightlist), member( Deptime / Arrtime / Fnum / Daylist , Flightlist), flyday( Day, Daylist). flyday( Day, Daylist) :- member( Day, Daylist). flyday( Day, alldays) :- member( Day, [mo,tu,we,th,fr,sa,su] ). deptime( [ P1 / P2 / Fnum / Dep | _], Dep). transfer( Hours1:Mins1, Hours2:Mins2) :- 60 * (Hours2 - Hours1) + Mins2 - Mins1 >= 40. member( X, [X | L] ). member( X, [Y | L] ) :- member( X, L).
% A FLIGHT DATABASE timetable( edinburgh, london, [ 9:40 / 10:50 / ba4733 / alldays, 13:40 / 14:50 / ba4773 / alldays, 19:40 / 20:50 / ba4833 / [mo,tu,we,th,fr,su] ] ). timetable( london, edinburgh, [ 9:40 / 10:50 / ba4732 / alldays, 11:40 / 12:50 / ba4752 / alldays, 18:40 / 19:50 / ba4822 / [mo,tu,we,th,fr] ] ). timetable( london, ljubljana, [ 13:20 / 16:20 / jp212 / [mo,tu,we,fr,su], 16:30 / 19:30 / ba473 / [mo,we,th,sa] ] ). timetable( london, zurich, [ 9:10 / 11:45 / ba614 / alldays, 14:45 / 17:20 / sr805 / alldays ] ). timetable( london, milan, [ 8:30 / 11:20 / ba510 / alldays, 11:00 / 13:50 / az459 / alldays ] ). timetable( ljubljana, zurich, [ 11:30 / 12:40 / jp322 / [tu,th] ] ). timetable( ljubljana, london, [ 11:10 / 12:20 / jp211 / [mo,tu,we,fr,su], 20:30 / 21:30 / ba472 / [mo,we,th,sa] ] ). timetable( milan, london, [ 9:10 / 10:00 / az458 / alldays, 12:20 / 13:10 / ba511 / alldays ] ). timetable( milan, zurich, [ 9:25 / 10:15 / sr621 / alldays, 12:45 / 13:35 / sr623 / alldays ] ). timetable( zurich, ljubljana, [ 13:30 / 14:40 / jp323 / [tu,th] ] ). timetable( zurich, london, [ 9:00 / 9:40 / ba613 / [mo,tu,we,th,fr,sa], 16:10 / 16:55 / sr806 / [mo,tu,we,th,fr,su] ] ). timetable( zurich, milan, [ 7:55 / 8:45 / sr620 / alldays ] ).
Full Program • fig4_5.pl • As for the NFA simulation program, to avoid infinite loops, make sure to limit the length of the route. E.g., • 3 ?- route( rome,edinburgh,mo,R). gives an infinite loop, while the following does not: • 6 ?- conc(R,_,[_,_,_,_]), route(rome, edinburgh,mo,R). No • conc generates routes in order of increasing length, so that shorter routes are tried first
More Infinite Looping Trouble • ?- route( ljubljana, edinburgh, th, R). R = [ljubljana/zurich/jp322/11:30, zurich/london/sr806/16:10, london/edinburgh/ba4822/18:40] ; Action (h for help) ? abort % Execution Aborted • ?- conc( R,_,[_,_,_,_]), route( ljubljana, edinburgh, th, R). R = [ljubljana/zurich/jp322/11:30, zurich/london/sr806/16:10, london/edinburgh/ba4822/18:40] ; No
Eight Queens: Program 1 • How to place 8 queens on a cheesboard, so that they do not attack each other • solution(Pos) if Pos is a solution to the problem • Positions are represented by a list of squares where the queen is sitting, e.g: [1/4,2/2,3/7,4/3,5/6,6/8,7/5,8/1] (fig.4.6, a solution) • We generalize to square boards of any size, so that we can use induction
Program 1, ctd. • solution( [ ]). • solution( [X/Y | Others]) :- solution( Others), member( Y, [1,2,3,4,5,6,7,8]), noattack( X/Y, Others). • This shows how to add a queen to extend a partial solution
Program 1, ctd. • noattack( _,[ ]). • noattack( X/Y, [X1/Y1 | Others] ) :- Y =\= Y1, % Different Y-coordinates Y1-Y =\= X1-X, % Different diagonals Y1-Y =\= X-X1, noattack( X/Y, Others). • The full program is in fig4_7.pl • Finds all (92) solutions upon backtracking and stops
% Figure 4.7 Program 1 for the eight queens problem. % solution( BoardPosition) if % BoardPosition is a list of non-attacking queens solution( [] ). solution( [X/Y | Others] ) :- % First queen at X/Y, other queens at Others solution( Others), member( Y, [1,2,3,4,5,6,7,8] ), noattack( X/Y, Others). % First queen does not attack others noattack( _, [] ). % Nothing to attack noattack( X/Y, [X1/Y1 | Others] ) :- Y =\= Y1, % Different Y-coordinates Y1-Y =\= X1-X, % Different diagonals Y1-Y =\= X-X1, noattack( X/Y, Others). member( Item, [Item | Rest] ). member( Item, [First | Rest] ) :- member( Item, Rest). template( [1/Y1,2/Y2,3/Y3,4/Y4,5/Y5,6/Y6,7/Y7,8/Y8]). % template/1 is just for easy use of the program. • Asking for a solution: • ?- template(S), solution(S). • S = [1/4, 2/2, 3/7, 4/3, 5/6, 6/8, 7/5, 8/1] ; • S = [1/5, 2/2, 3/4, 4/7, 5/3, 6/8, 7/6, 8/1] ; • S = [1/3, 2/5, 3/2, 4/8, 5/6, 6/4, 7/7, 8/1] ; • S = [1/3, 2/6, 3/4, 4/2, 5/8, 6/5, 7/7, 8/1] ; • S = [1/5, 2/7, 3/1, 4/3, 5/8, 6/6, 7/4, 8/2] ; • S = [1/4, 2/6, 3/8, 4/3, 5/1, 6/7, 7/5, 8/2] ; • ... • In the book and the example programs there are two more 8-queens programs. Compare them yourself!
Eight Queens: Program 2 • Represent X queen position by their position in the position list: • [1/Y1, 2/Y2, …., 8/Y8] is replaced by • [Y1, Y2, …., Y8] • Generate an ordering of the Y positions, then test that position: solution( S) :- permutation( [1,2,3,4,5,6,7,8], S), %generate safe(S). %test
Program 2, ctd. • noattack/2 is generalized to noattack/3, where the third argument represents the X distance (column distance) of two queens • Full program in fig4_9.pl • To get all solutions, do: ?- setof( S, solution(S), L), length( L,N). S = _G405 L = [[1, 5, 8, 6, 3, 7, 2, 4], [1, 6, 8, 3, 7, 4, 2|...], [1, 7, 4, 6, 8, 2|...], [1, 7, 5, 8, 2|...], [2, 4, 6, 8|...], [2, 5, 7|...], [2, 5|...], [2|...], [...|...]|...] N = 92
% Figure 4.9 Program 2 for the eight queens problem. % solution( Queens) if % Queens is a list of Y-coordinates of eight non-attacking queens solution( Queens) :- permutation( [1,2,3,4,5,6,7,8], Queens), safe( Queens). permutation( [], [] ). permutation( [Head | Tail], PermList) :- permutation( Tail, PermTail), del( Head, PermList, PermTail). % Insert Head in permuted Tail % del( Item, List, NewList): deleting Item from List gives NewList del( Item, [Item | List], List). del( Item, [First | List], [First | List1] ) :- del( Item, List, List1). % safe( Queens) if % Queens is a list of Y-coordinates of non-attacking queens safe( [] ). safe( [Queen | Others] ) :- safe( Others), noattack( Queen, Others, 1). noattack( _, [], _). noattack( Y, [Y1 | Ylist], Xdist) :- Y1-Y =\= Xdist, Y-Y1 =\= Xdist, Dist1 is Xdist + 1, noattack( Y, Ylist, Dist1).
Eight Queens: Program 3 • Program 3 uses a redundant representation of the board, with • columns, x, 1 through 8 • rows, y, 1 through 8 • upward diagonals, u = x – y, -7 through 7 • downward diagonals, v = x + y, 2 through 16 • When a queen is placed, its column, row, and diagonals are removed from consideration • pl4_11.pl
% Figure 4.11 Program 3 for the eight queens problem. % solution( Ylist) if % Ylist is a list of Y-coordinates of eight non-attacking queens solution( Ylist) :- sol( Ylist, % Y-coordinates of queens [1,2,3,4,5,6,7,8], % Domain for X-coordinates [1,2,3,4,5,6,7,8], % Domain for Y-coordinates [-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7], % Upward diagonals [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] ). % Downward diagonals sol( [], [], Dy, Du, Dv). sol( [Y | Ylist], [X | Dx1], Dy, Du, Dv) :- del( Y, Dy, Dy1), % Choose a Y-coordinate U is X-Y, % Corresponding upward diagonal del( U, Du, Du1), % Remove it V is X+Y, % Corresponding downward diagonal del( V, Dv, Dv1), % Remove it sol( Ylist, Dx1, Dy1, Du1, Dv1). % Use remaining values del( Item, [Item | List], List). del( Item, [First | List], [First | List1] ) :- del( Item, List, List1).
Eight Queens: Efficiency • The second program is the least efficient: ?- time( setof( S, solution(S), L)). % 1,139,743 inferences in 1.10 seconds (1034640 Lips) • In general, generate-and-test is inefficient: it is best to introduce constraints as early as possible in the solution design process • First program: ?- time( setof( S, solution1(S), L)). % 171,051 inferences in 0.22 seconds (776387 Lips) • Third program: 1 ?- time( setof( S, solution(S), L)). % 120,544 inferences in 0.15 seconds (802471 Lips)