Artificial Intelligence - Prolog Programming - Ryo Hatano JAIST Oct 16, 2012.

Slides:



Advertisements
Similar presentations
Artificial Intelligence: Natural Language and Prolog
Advertisements

First Order Logic Logic is a mathematical attempt to formalize the way we think. First-order predicate calculus was created in an attempt to mechanize.
Some Prolog Prolog is a logic programming language
Logic Programming Lecture 1: Getting started. Getting started We’ll use SICStus Prolog Free for UofE students Available on all DICE machines
SLD-resolution Introduction Most general unifiers SLD-resolution
1 Part 1 The Prolog Language Chapter 2 Syntax and Meaning of Prolog programs.
Prolog.
Introduction to PROLOG ME 409 Lab - 1. Introduction to PROLOG.
11/10/04 AIPP Lecture 6: Built-in Predicates1 Combining Lists & Built-in Predicates Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture.
COMMONWEALTH OF AUSTRALIA Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf of Monash University.
1 Introduction to Prolog References: – – Bratko, I., Prolog Programming.
Automated Reasoning Systems For first order Predicate Logic.
1 Logic Programming. 2 A little bit of Prolog Objects and relations between objects Facts and rules. Upper case are variables. parent(pam, bob).parent(tom,bob).
CS 484 – Artificial Intelligence1 Announcements Choose Research Topic by today Project 1 is due Thursday, October 11 Midterm is Thursday, October 18 Book.
About prolog  History  Symbolic Programming Language  Logic Programming Language  Declarative Programming Language.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
For Friday Read “lectures” 1-5 of Learn Prolog Now: prolog-now/
Constraint Logic Programming Ryan Kinworthy. Overview Introduction Logic Programming LP as a constraint programming language Constraint Logic Programming.
Programming Language Semantics Mooly SagivEran Yahav Schrirber 317Open space html://
1 CILOG User Manual Bayesian Networks Seminar Sep 7th, 2006.
Programming Logic and Design, Introductory, Fourth Edition1 Understanding Computer Components and Operations (continued) A program must be free of syntax.
(9.1) COEN Logic Programming  Logic programming and predicate calculus  Prolog statements  Facts and rules  Matching  Subgoals and backtracking.
Formal Models of Computation Part II The Logic Model
Notes for Chapter 12 Logic Programming The AI War Basic Concepts of Logic Programming Prolog Review questions.
LING 388: Language and Computers Sandiway Fong Lecture 4.
Evolution of Programming Languages Generations of PLs.
1 Lecture 15: Introduction to Logic Programming with Prolog (Section 11.3) A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill.
CS 330 Programming Languages 11 / 21 / 2006 Instructor: Michael Eckmann.
1 Lecture 6 Logic Programming introduction to Prolog, facts, rules Ras Bodik Shaon Barman Thibaud Hottelier Hack Your Language! CS164: Introduction to.
Chapter Twenty-ThreeModern Programming Languages1 Formal Semantics.
30/09/04 AIPP Lecture 3: Recursion, Structures, and Lists1 Recursion, Structures, and Lists Artificial Intelligence Programming in Prolog Lecturer: Tim.
Artificial Intelligence Programming in Prolog Lecture 1: An Introduction 23/09/04.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Formal Semantics Chapter Twenty-ThreeModern Programming Languages, 2nd ed.1.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now Chapter 9, exs 4 and 6. –6 must be in Horn clause form Prolog Handout 2.
Introduction To PROLOG World view of imperative languages. World view of relational languages. A PROLOG program. Running a PROLOG program. A PROLOG.
1 Knowledge Based Systems (CM0377) Lecture 3 (Last modified 5th February 2001)
PROLOG SYNTAX AND MEANING Ivan Bratko University of Ljubljana Faculty of Computer and Info. Sc. Ljubljana, Slovenia.
Prolog Kyle Marcotte. Outline What is Prolog? Origins of Prolog (History) Basic Tutorial TEST!!! (sort of…actually not really at all) My example Why Prolog?
Logic Programming CSC 358/ Outline Pattern matching Unification Logic programming.
Logic Programming and Prolog Goal: use formalism of first-order logic Output described by logical formula (theorem) Input described by set of formulae.
Automated Reasoning Early AI explored how to automated several reasoning tasks – these were solved by what we might call weak problem solving methods as.
Ch. 13 Ch. 131 jcmt CSE 3302 Programming Languages CSE3302 Programming Languages (notes?) Dr. Carter Tiernan.
Introduction to Prolog. Outline What is Prolog? Prolog basics Prolog Demo Syntax: –Atoms and Variables –Complex Terms –Facts & Queries –Rules Examples.
COMP307 Artificial Intelligence Xiaoying Gao Victoria University of Wellington Lecture 2:1 
1 Knowledge Based Systems (CM0377) Lecture 6 (last modified 20th February 2002)
LING/C SC/PSYC 438/538 Lecture 15 Sandiway Fong. Did you install SWI Prolog?
Knowledge Based Information System
In The Name Of Allah Lab 03 1Tahani Aldweesh. objectives Searching for the solution’s. Declaration. Query. Comments. Prolog Concepts. Unification. Disjunction.
Artificial Intelligence CIS 342 The College of Saint Rose David Goldschmidt, Ph.D.
For Friday No reading Prolog Handout 2. Homework.
Prolog 3 Tests and Backtracking 1. Arithmetic Operators Operators for arithmetic and value comparisons are built-in to Prolog = always accessible / don’t.
Logic Programming Lecture 8: Term manipulation & Meta-programming.
07/10/04 AIPP Lecture 5: List Processing1 List Processing Artificial Intelligence Programming in Prolog Lecturer: Tim Smith Lecture 5 07/10/04.
Copyright © Curt Hill Other Trees Applications of the Tree Structure.
1 TP #2: How does Prolog answer questions? n Miscellaneous info; n Last TP exercises solved; n How does Prolog answer questions? n Recursive Prolog programs;
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Prolog Fundamentals. 2 Review Last Lecture A Prolog program consists of a database of facts and rules, and queries (questions). –Fact:.... –Rule:... :-....
Logic Programming Lecture 2: Unification and proof search.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Section 16.5, 16.6 plus other references
Fundamentals of Programming I Overview of Programming
Chapter 2 - Introduction to C Programming
For Friday No reading Prolog handout 3 Chapter 9, exercises 9-11.
For Wednesday Read “lectures” 7-10 of Learn Prolog Now:
PROLOG.
Chapter 2 - Introduction to C Programming
Tests, Backtracking, and Recursion
Basic Syntax and Semantics
Representations & Reasoning Systems (RRS) (2.2)
Presentation transcript:

Artificial Intelligence - Prolog Programming - Ryo Hatano JAIST Oct 16, 2012

About this Lecture Today only No report, no examination today –But midterm examination contains some quiz about Prolog TA: Ryo Hatano, D1 student of Tojo lab Lecture matelials: 1

Objectives Study about the basic usage of Prolog –Understand the basics of logic programming Become able to study Prolog by yourself –Today, I’ll teach only introduction 2

3 Reference I. Bratko, Prolog Programming for Artificial Intelligence Shapiro et al, The Art of Prolog P. Blackburn et al, Learn Prolog Now! S. Russell et al, Artificial Intelligence A Modern Approach I. Bratko, Prolog への入門 古川康一 他, 帰納論理プログラミング S. Russell 他, エージェントアプローチ人工知能 You can find some books about Prolog in JAIST Library or online via Google. ( わかりやすい ) ( 短くまとまっている ) (8 章が背景に詳しい ) (chap. 9 contains some background info) (be available online) (contains advanced topics) (easy)

4 What is the Prolog ? PRO grammation en LOGique –Programming language which based on predicate logic –The implementation is a kind of automated proving system –It specializes in logical processing and knowledge representation It suitable for the problems to handle relation between some objects Symbol processing is better

5 There is a person in a room He wants to catch a banana hanging from a ceiling He have to find a way to the banana Simple Planning System Definition of predicates for solving move(state(Before), command, state(After)). state(X, Y, BOX, Has). canget(state):- ←Recursion rule The problem can solve using only these predicates !

6 Monkey & Banana problem (details, for reference) state(atdoor, onfloor, atwindow, hasnot) state(atwindow, onbox, atwindow, hasnot) state(P2’, onfloor, P2’, hasnot) state(P2’, onbox, P2’, hasnot) state(middle, onbox, middle, has) walk(atdoor, P2) push(atwindow, P2’) climb Grasp P2’ = middle state(P2, onfloor, atwindow, hasnot) climb(onfloor, onbox) P2 = atwindow state(atwindow, onfloor, atwindow, hasnot) Backtrack(onbox→onfloor) Other backtracks are ommitted

Overview of the Prolog Using of the Prolog environment start, stop, load, execution Many Syntaxes –Basics Data structure, operators and recursion Evaluation process –Advanced list, cut, syntax sugar, user defined operator, extra logical predicates, set predicates, failure driven loop 7 Today’s Topics and some samples

Overview of the Prolog (cont, for reference) Theoretical Backgrounds –History –Formal Semantics of Prolog –Warren Abstract Machine –Herbrand’s Theorem –Evaluation Algorithms Advanced topics –Meta programming (Higher order programming, Meta interpreter) –Grammar parsing with DCG (Definition Clauses Grammar) –Theorem proving and its application with user defined axiomatic system –Other Logic programming (Inductive logic programming, Probabilistic logic programming) –etc… 8

9 About the Prolog environment Implementation –SICStus Prolog –SWI Prolog –GNU Prolog Development environment –Prolog mode of Emacs –PDT of Eclipse –Text editor + Prolog interpreter Not free, performance is good, but not easy to use Free, easy to use, recommend Note: some built-in libraries are not same

10 Basic Usage of the Prolog Environment Using interpreter –You can control the prolog system interactively –First we load the program first. Then input a query after outputs of “?-”. ?- [sample_1e.pl]. % sample_1e.pl compiled 0.00 sec, 1,004 bytes ?- foo(bar). true. ?- foo(X). X = bar; X = baz ?- halt. ←load program by short notation ←query which input by user ←If other answer exists, input “;” then search next answer ←load then compile Example

11 Basic usage of the Prolog Environment (cont.) Start –%prolog [-l] [filename] Exit –halt. –Ctrl + ‘d’ Interrupt and termination –Ctrl + ‘c’ then ‘a’ File load –chdir(‘dir_path’). Change the current directory (ex.‘c:\\test’) –consult[‘file_name’]. or [‘file_name’]. Execute the file load File reload –make. Reload the edited file Trace –trace. It shows all steps of evaluation. “notrace” is for exit. In OS shell, -l is option for loading a prolog program (See also: official manual)

12 Syntax of the Prolog program Arithmetic, Comparison, Substitution, User defined Unification, Control of backtrack Comment Operators + Data structures Clauses Head :- Body. Predicate(Term, Term, …, Term) Variable Constant Function + Some technics (ex. Recursion)

13 Comment One line comment –From “%” to end of the line Multi line comment –From “/*” to “*/” Write the comment in the source code and give the readability. It is important habit in software engineering. /* Multi line comment */ foo(bar) %comment to end of the line Example in Prolog programs

14 Syntax of the Prolog program Arithmetic, Comparison, Substitution, User defined Unification, Control of backtrack Comment Operators + Data structures Clauses Head :- Body. Predicate(Term, Term, …, Term) Variable Constant Function + Some technics (ex. Recursion)

15 Prolog program consists of the set of “Horn clauses” –Horn clause is clause which has zero or one positive conclusion Prolog system has 3 types of clauses –Facts, Rules, Goals(Query) Clauses These formula are expressed to the form of Prolog In the real program Example in predicate logic Program clauses

16 Example of Program Notation of clauses in Prolog Head :- Body. % All of these are horn clauses ! vegetable(carrot). fruit(apple). vegetable(tomato). fruit(tomato). plant(X) :- vegetable(X). plant(X) :- fruit(X). plant(X) :- fruit(X), vegetable(X). ?- plant(X). Program Interpreter ← Goal clauses(query) Rule clauses Fact clauses It is equivalent to implication operator “→” in predicate logic. But the direction is opposite (Body→Head). Write the period end of the each clauses

17 Fact clauses vegetable(carrot). %Carrot is a kind of vegetables fruit(apple). %Apple is a kind of fruits vegetable(tomato). fruit(tomato). %Tomato is a kind of fruits and vegetables Example of Prolog program Explain about predicates is later Equivalent form of predicate formula The clause express about the facts –Clauses has empty body (condition) ⇔ Head (conclusion) only. –It contains predicates and constants which value is always true Empty value means “true” in Prolog system

18 Rule clauses plant(X) :- vegetable(X). plant(X) :- fruit(X). plant(X) :- vegetable(X), fruit(X). Example in Prolog programs Equivalent form of predicate formula The clauses express about rules –The clause has head and non empty body –It offers the function of Modus Ponens like implication operator –True/False value is depends on the contents of the body Comma “,” means “and” condition. Semi colon “;” means “or” condition. If there are some same heads of fact and rule clauses, it means “or” condition Important notations are “ . ”, “ , ” and “:-”.

19 Goal clauses ?- vegetable(carrot). true. Example in interpreter (“Yes/No” type of query) Equivalent form of predicate formula The clause express about query –The clause has only body –It consists of at least one goal –There are 2 types of queries Yes/No type, What type ←Query which ask the fact exists ←System answers Yes or No Example in interpreter (“What” type of query) Prolog system tries to find the answer of this arrow. ?- vegetable(X). X = carrot. ←Query which contains valiable ←System answers the value of variable If the answer doesn’t exists, system answers error.

20 Syntax of the Prolog program Arithmetic, Comparison, Substitution, User defined Unification, Control of backtrack Comment Operators + Data structures Clauses Head :- Body. Predicate(Term, Term, …, Term) Variable Constant Function + Some technics (ex. Recursion)

21 Data structures All data objects treats as “term” in Prolog system There are 3 types of terms –Constant –Variable –Function (= It is the complex data structure which consists of some elements)

22 Atoms There are 3 types of atoms –Character string which starts with lower case or number –Special character string +, -, *, /,, =, :,., &, _, ~ –Quoted string ←This is exceptional case. It depends on environment carrot. miss_mary ======>. ‘Mr. Tom’. 日本語の定数. ←If you need constants which starts with upper case, “‘” is suitable ←Some atoms already used by system such as “:-” Example of constants There are some special constants such as “true”, “end_of_file”. It depends on environment.

23 Variables There are 2 types of variables –Normal variables which starts with upper case or under score –Anonymous variables which only express in under score Temporary name of variables which appears only one time in the clause When it appear, it allocates different number by the system Anonymous variables in query ignores when answer ←Anonymous variable excludes from evaluation X Result _Arg1 hoge( _, X):-... Memory allocates when variables evaluated Example of variables

24 Function Structural data which has some elements –Functor(Term1, Term2, …) –The naming rule is same as constants –The number of arguments calls “arity” –Function only refers other terms. It doesn’t have truth value. fruit(apple). plant(eatable(X)):- fruit(X). Example of function FunctorTerm ←Function and predicate are not same Another name is “Compound term” Predicate Interpreter ?- plant(Func). Func = eatable(apple). ←It only directs other terms. “eatable(apple)” is not returns true.

25 Function (cont.) The data structure consider as tree –When all elements of some trees are same, they treat as same data Example of tree structure father(parent(X, Y), male(X)) father parentmale X Y X The root of tree calls to Principal functor It depends on matching operation

26 Predicates Structural data which express relation between terms –Predicate symbol(Term1, Term2, …) –The naming rule is same as constants –Predicate symbols and terms constructs atomic formula. It has truth value. fruit(carrot). plant(X):- fruit(X). father(X):- parent(X, Y), male(X). Example of predicates Predicate symbolTerms ←It can contains some variables and constants.

27 Predicate (cont.) Distinguish the same predicate or not is by predicate symbol and arity –Short notation “predicate symbol/arity” has used plant(X) :- vegetable(X). plant(Y) :- vegetable(Y), fruit(Y). Example Body and variable name are same, but each predicate Treat as same by plant/1 Note: The problem of distinguish predicates and tree structure of functions are not same.

28 Syntax of the Prolog program Arithmetic, Comparison, Substitution, User defined Unification, Control of backtrack Comment Operators + Data structures Clauses Head :- Body. Predicate(Term, Term, …, Term) Variable Constant Function + Some technics (ex. Recursion)

29 Arithmetic operator X +YAddition X -YSubtraction X *YMultiplication X /YDivision X // YQuotient of the natural number division X mod YRemainder of the natural number division X is YY substitute to X (Y need to be bind) ?- Result is Result = 5. ?- Result = Result = Example of arithmetic formula In general, the arithmetic operator writes in infix notation ←it is not correct. “ = ” is not arithmetic operation. So it is not evaluated. ←example of correct arithmetic operation and substitution

30 Comparison operators X > YX is greater than Y X < YX is less than Y X >= YX is greater than or equal to Y X =< YX is less than or equal to Y X =:= Y(Arithmetic formula) value of X and Y are equals X =\= Y(Arithmetic formula) value of X and Y are not equals X == YTerms X and Y are equals X \== YTerms X and Y are not equals

31 Unification X = YMatching X and Y, then if it matches true otherwise false Matching of the Prolog is near to predicate logic ?-date(_Day, _Month, 2012) = date(9, april, _Year). _Day = 9 _Month = april _Year = 2012 Example of unification ←it returns most general solution

32 Recursion The evaluation process calls itself –The rule which calls itself in the body –Usually, it uses as loop –The condition (address of variables and values) of each predicates are saved on memory When returns, the process take the values from memory Example of recursion factorial(0, 1). factorial(N, Result):- N2 is N – 1, factorial(N2, Result2), Result is N * Result2. ←Stop condition. It needs to write above recursion.

Outline of the evaluation process Prolog system is a kind of automated theorem proving system It mainly consists of 4 technics –Depth first backward search –Unification –Backtracks –Closed world assumption 33

34 Depth first backward search %Definition of facts fruit(apple). fruit(tomato). vegetable(tomato). %Definition of rules plant(X) :- fruit(X). plant(X) :- vegetable(X). InterpreterSource code ?- trace. true. ?- plant(X). Call: (6) plant(_G466) ? creep Call: (7) fruit(_G466) ? creep Exit: (7) fruit(apple) ? creep Exit: (6) plant(apple) ? creep X = apple plant fruitvegetable It searches from query to defined facts by depth first apple tomato Search tree

35 Unification %Definition of facts fruit(apple). fruit(tomato). vegetable(tomato). %Definition of rules plant(X) :- fruit(X). plant(X) :- vegetable(X). InterpreterSource code ?- trace. true. ?- plant(X). Call: (6) plant(_G466) ? creep Call: (7) fruit(_G466) ? creep Exit: (7) fruit(apple) ? creep Exit: (6) plant(apple) ? creep X = apple plant fruitvegetable It matches variables and terms. The scope is only same clause. apple tomato X= apple Search tree

36 Backtracks %Definition of facts fruit(apple). fruit(tomato). vegetable(tomato). %Definition of rules plant(X) :- fruit(X). plant(X) :- vegetable(X). InterpreterSource code X = apple ; Redo: (7) fruit(_G466) ? creep Exit: (7) fruit(tomato) ? creep Exit: (6) plant(tomato) ? creep X = tomato plant fruitvegetable It backs to former branch then search other answers. apple tomato Search tree

37 Closed world assumption %Definition of facts fruit(apple). fruit(tomato). vegetable(tomato). %Definition of rules plant(X) :- fruit(X). plant(X) :- vegetable(X). InterpreterSource code ?- plant(X). X = apple ; X = tomato ; X = tomato. ?- plant fruitvegetable There are no more things substitute to X. In the prolog, there are assumption which Means not defining things are all false. Therefore, the result of this example is false. apple tomato ←Waiting for next query It is called closed world assumption No more choices Search tree