SlideShare ist ein Scribd-Unternehmen logo
1 von 52
Downloaden Sie, um offline zu lesen
tuProlog (2P)
A Java-based Prolog System for Pervasive Intelligence


                                       alessandro ricci
                                          PhD at DEIS
                                  aricci@deis.unibo.it
Outline

• Introduction: 2P Objectives & Design
  - 2P technology & tools
• Using 2P from Java
  - 2P API
• Extending 2P: Libraries
• Using Java from 2P: The JavaLibrary
• 2P in context
  - AI, DAI, MAS

                                         2P Intro - 200311
What is 2P

• Java-Based Prolog Virtual Machine
  - minimality & dynamic/open extesibility/configurability
  - bidirectional Java integration
• Java API to use Prolog From Java
  - alice.tuprolog package
• 2P Extensions/Tools
  - alice.tuprologx.* package
  - IDEs
  - Extensions (libraries, theories)
                                              2P Intro - 200311
2P Targets
• As components to be integrated in Java
  development for intelligent application
  - Symbolic Reasoning in a OOP context
  - “Intelligence + Interaction”
• Internet Applications
  - as lightweight component for applet, servlet, mobile
    code, network-enabled devices
• Intelligent Infrastructures
  - Building agent systems
  - ReSpecT Coordination framework & TuCSoN
    Infrastructure
                                               2P Intro - 200311
Getting Started

• 2P is open source
• Download from
  - http://lia.deis.unibo.it/research/tuprolog
  - http://tuprolog.sourceforge.net
• -Download what
    tuprolog.jar, tuprologx.jar, 2P.jar
  - Full package: 2p-X.Y.Z.zip
    •   src/build/lib/bin


                                                 2P Intro - 200311
Getting Started:
            2P from Java
• From Java
  - Using 2P engines in the context of Java applications
  - Include the package 2p.jar in the classpath
    •   or tuprolog.jar + tuprologx.jar

  - Package to import: alice.tuprolog

                                               2P Intro - 200311
The 2P Tools: IDEs

• Command Line IDE
  - alice.tuprologx.ide.CUIConsole application
  - java -cp 2p.jar alice.tuprologx.ide.CUIConsole
• GUI based IDE (with 2P alfa version 1.2.1)
  - alice.tuprologx.ide.GUILauncher application
  - java -cp 2p.jar alice.tuprologx.ide.GUILauncher
• GUI based IDE (with 2P version 1.2.0)
  - alice.tuprologx.ide.GUIConsole application
  - java -cp 2p.jar alice.tuprologx.ide.GUIConsole


                                          2P Intro - 200311
The 2P Tools: Others

• Spawning an agent
  - alice.tuprolog.Agent application
   java -cp tuprolog.jar
          alice.tuprolog.Agent PrologTheoryTextFile {Goal}



• Examples
  - text file hello.pl containing
  - spawning the agent:
   java -cp tuprolog.jar
          alice.tuprolog.Agent hello.pl go.




                                                       2P Intro - 200311
2P Main Elements
• Core Inferential Engine
  - class Prolog
• Theories
  - class Theory
• Libraries
  - class Library (abstract)
• Prolog Data Types
  - class Term (abstract), Number (abstract),
    Int/Long/Float/Double (concrete), Struct
    (concrete),Var (concrete)
                                                2P Intro - 200311
2P Data Types

        Term



Var   Struct   Number



       Long    Int      Float        Double



                                2P Intro - 200311
2P Engine Design

• Self-Contained, with no static links
  - Enabling multiple engines, independently configured
    (theory, libraries), in the same computational context
• Minimal Interface
  - setting, retrieving, adding theories
  - solving goal
  - load & unload libraries


                                              2P Intro - 200311
An example: a theory for expression
    derivation & evaluation (1)

dExpr(T,X,DT):-dTerm(T,X,DT).
dExpr(E+T,X,[DE+DT]):-dExpr(E,X,DE), dTerm(T,X,DT).
dExpr(E-T,X,[DE-DT]):-dExpr(E,X,DE), dTerm(T,X,DT).
dTerm(F,X,DF):-dFactor(F,X,DF).
dTerm(T*F,X,[[DT*F]+[T*DF]]):-dTerm(T,X,DT), dFactor(F,X,DF).
dTerm(T/F,X,[[F*DT]-[T*DF]]/[F*F]):-dTerm(T,X,DT),
dFactor(F,X,DF).
dFactor(-E,X,-DE):-dExpr(E,X,DE).
dFactor([E],X,DE):-dExpr(E,X,DE).
dFactor(N,X,0):-number(N).
dFactor(X,X,1).
dFactor(F^N,X,[[N*[F^M]]*DF]):-M is N-1, dFactor(F,X,DF).
dFactor(sin(E),X,[cos(E)*DE]):-dExpr(E,X,DE).
dFactor(cos(E),X,[-sin(E)*DE]):-dExpr(E,X,DE).

(cont)




                                                2P Intro - 200311
An example: a theory for expression
       derivation & evaluation (2)
(cont)

evalExpr(T,V,R):-evalTerm(T,V,R).
evalExpr(E+T,V,R):-evalExpr(E,V,R1), evalTerm(T,V,R2), R is R1+R2.
evalExpr(E-T,V,R):-evalExpr(E,V,R1), evalTerm(T,V,R2), R is R1-R2.
evalTerm(F,V,R):-evalFactor(F,V,R).
evalTerm(T*F,V,R):-evalTerm(T,V,R1), evalFactor(F,V,R2), R is R1*R2.
evalTerm(T/F,V,R):-evalTerm(T,V,R1), evalFactor(F,V,R2), R is R1/R2.
evalFactor(-E,V,R):-evalExpr(E,V,R1), R is -R1.
evalFactor([E],V,R):-evalExpr(E,V,R).
evalFactor(N,V,N):-number(N).
evalFactor(x,V,V).
evalFactor(F^E,V,R):-evalFactor(F,V,R1),evalExpr(E,V,R2),R is R1^R2.
evalFactor(sin(E),V,R):-evalExpr(E,V,R1),R is sin(R1).
evalFactor(cos(E),V,R):-evalExpr(E,V,R1),R is cos(R1).




                                                    2P Intro - 200311
Using the theory from Java




                    2P Intro - 200311
2P API: The Engine




                2P Intro - 200311
Data Types API Example




                  2P Intro - 200311
2P Libraries
           (ver. 1.2.1)



• Structure
• Developing a Library
• Default Libraries
• The JavaLibrary

                          2P Intro - 200311
Library Structure
• Name
• Set of built-in predicates
  - only one (boolean) solution (no open choices)
  - loosing non-determinism
• Set of built-in functors
• Theory
  - typically providing rules on top of the built-in
    predicates/functors
  - recovering non-determinism

                                                 2P Intro - 200311
Developing a Library
•   Extending alice.tuprolog.Library abstract class
    - provides some basic services
       •   Unification: boolean unify(Term arg0, Term arg1)

•   Writing built-in predicates as methods
    - boolean predicateName_arityN(Term arg1,..., Term argN)
       •   fails if exceptions are thrown

•   Writing built-in funtors as methods
    - Term functorName_arityN(Term arg1,..., Term argN)
       •   fails if exceptions are thrown

•   Defining the theory
    - overriding String getTheory() method
    - default = empty theory = empty string
•   Defining the name
    - overriding String getName() method
    - default = class name
Example
package alice.test.tuprolog;

import alice.tuprolog.*;

public class StringLibrary extends Library {

    public boolean to_lower_case_2(Term arg0, Term arg1){
      String dest = arg0.toString().toLowerCase();
      return unify(arg1, new Struct(dest));
    }
}



                                          2P Intro - 200311
Example (2)
package alice.test.tuprolog;

import alice.tuprolog.*;
import alice.tuprolog.Number;

public class TestLibrary extends StringLibrary {

    public Term sum_2(Number arg0, Number arg1){
      int sum = arg0.intValue()+arg1.intValue();
      return new Int(sum);
    }

    public String getTheory(){
      return “print_sum(A,B):- N is sum(A,B), n”+
                  “write(N),nl. n”;
}
                                                   2P Intro - 200311
Remarks

• Libraries as bridge to legacy libreries & code
    - not only Java
      • exploiting JNI
•   Solution for specialised & performant computation
    - Math libraries
    - Graphics 3D/2D libraries (e.g. OpenGL)
    - Multimedia libraries
      •   sound, video streaming, etc


                                               2P Intro - 200311
Standard Libraries
•   Package alice.tuprolog.lib
•   Basic Library
    - alice.tuprolog.lib.BasicLibrary
    - basic & frequent builtins
•   ISO Library
    - alice.tuprolog.lib.ISOLibrary
    - ISO standard builtins
•   IO Library
    - alice.tuprolog.lib.IOLibrary
    - Input/Output Builtins (File, Console, etc)

• Java Library
    - alice.tuprolog.lib.JavaLibrary
    - Using Java from 2P
The JavaLibrary

• Goals
  - reusing all the Java world from Prolog
  - OOP-oriented access style
    •   object creation
    •   method invocation
  - full dynamism
    •   classes/objects created/linked at run-time
  - Java Event Management (1.2.1 version)

                                                     2P Intro - 200311
JavaLibrary Design Goal
• Mapping 1-1 with Java operation
  - simple object creation
  - method invocation
  - field access
• Keeping the two paradigms separated
  - Object references are denotated by simple terms
  - The terms refer to Java objects only in the context of
    JavaLibrary builtins predicates/operators
    •   not embedding an OOP model inside the Prolog virtual
        machine

                                                  2P Intro - 200311
Simple class used
         for the examples
public class Counter {
  private int value;
  public String name;

    public Counter(){}
    public Counter(String n){ name=n; }

    public   void   setValue(int val){ value=val; }
    public   int    getValue() { return value; }
    public   void   inc()      { value++; }
    public   void   setName(String s) { name = s;}

    static public String getVersion() { return quot;1.0quot;; }
}


                                             2P Intro - 200311
Creating Java Objects
• Syntax
   java_object(@ClassName,@ArgumentList,?ObjectRef)

• Semantics
  - the predicate is true if ObjectRef denotates a new
    instance of a Java object of class ClassName created
    with arguments ArgumentList
• Example
     ?- java_object(’Counter’,[],MyCounter).
     ?- java_object(’Counter’,[],aCounter).
     ?- java_object(’Counter’,[’pippo’],pippoCounter).

• For arrays
   java_object(@ClassName[],@ArgumentList,?ObjectRef)
  - Example
    ?- java_object(’Counter[]’,[10],MyArray).
                                                2P Intro - 200311
Method Invocation
• Syntax
  @TargetRef <- @MethodName(@Arguments)
  @TargetRef <- @MethodName(@Arguments) returns ?Result
  class(@ClassName) <- @MethodName(...) ...


• Semantics
  - the predicate is true if the method MethodName can be
    invoked on the object referenced by TargetRef
    possibly obtaining a result unifying with Result.

• Examples
  ?- MyCounter <- setValue(303).
  ?- pippoCounter <- getValue returns Value.
  ?- class(’Counter’) <- getVersion returns Version.
                                                2P Intro - 200311
Accessing Fields
• Syntax
  @TargetRef . @Field <- set(@Content)
  @TargetRef . @Field <- get(?Content)



• Semantics
  - the predicates are true if the content of the field Field
    of the object referenced by TargetRef can be set with
    the value Content or can be read and its value unifies
    the Content value.

• Examples
   ?- MyCounter.name <- get(Name).
   ?- pippoCounter.name <- set(’pippo2’).

                                               2P Intro - 200311
Dynamic Compilation
• Compiling dynamically a Java class given its source
• Syntax
  java_class(@Source,@FullClassName,@ClassPathList,-ClassRef)


• Semantics
  - the predicate is true if ClassRef is the reference to an
    object class whose name is FullClassName and it can be
    obtained by compiling the source Source with class
    pathes of the list ClassPathList.

• Example


                                                 2P Intro - 200311
JavaLibrary: Overall Example
test:-
    java_object('Counter',['ANiceCounter'],myCounter),
    myCounter <- setValue(5),
    myCounter <- inc,
    myCounter <- getValue returns Value,
    write(Value),
    class('Counter') <- getVersion returns Version,
    class('java.lang.System').out <- get(StdOut),
    StdOut <- println(Version),
    myCounter.name <- get(MyName),
    StdOut <- println(MyName),
    myCounter.name <- set('NicerCounter'),
    java_object('Counter[]', [10], ArrayCounters),
    java_array_set(ArrayCounters, 3, myCounter).



                                           2P Intro - 200311
JavaLibrary: Examples (1)

Opening a swing dialog for choosing a file:




                                             2P Intro - 200311
Java Library: Examples (2)
• Using RMI Infrastructure
 ?- java_object(’java.rmi.RMISecurityManager’,[],Manager),
    class(’java.lang.System’) <- setSecurityManager(Manager),
    class(’java.rmi.Naming’) <- lookup(’pippoCounter’) returns MyCounter,
    MyCounter <- inc,
    MyCounter <- getValue returns Val,
    write(Val),nl.



• In Java...
    ...
    RMISecurityManager rman = new RMISecurityManager();
    System.setSecurityManager(rman);
    Counter core=(Counter)Naming.lookup(quot;pippoCounterquot;);
    counter.inc();
    long val = counter.getValue();
    System.out.println(val);



                                                       2P Intro - 200311
JavaLibrary: Examples (3)
      “Find the minimum path between two cities.
       City distances are stored in a standard DB
    (table ‘distances’, city_from/city_to/length row)”

find_path( From, To ):-
  init_dbase( ’jdbc:odbc:distances’, Connection,’’,’’),
  exec_query( Connection,
     ’SELECT city_from, city_to, distance FROM distances.txt’,ResultSet ),
  assert_result( ResultSet ),
  findall( pa(Length,L), paths(From,To,L,Length), PathList ),
  current_prolog_flag( max_integer, Max ),
  min_path( PathList, pa(Max,_), pa(MinLength, MinList) ),
  outputResult( From, To, MinList, MinLength ).




                                                      2P Intro - 200311
JavaLibrary: Examples (3)
% Access to Database
init_dbase( DBase, Username, Password, Connection ) :-
    class(’java.lang.Class’) <- forName( ’sun.jdbc.odbc.JdbcOdbcDriver’ ),
    class(’java.sql.DriverManager’) <- getConnection( DBase, Username, Password)
                                       returns Connection,
    write( ’[ Database ’ ), write(DBase), write(’ connected ]’ ), nl.

exec_query( Connection, Query, ResultSet ):-
    Connection <- createStatement returns Statement,
    Statement <- executeQuery( Query ) returns ResultSet,
    write( ’[ query ’ ), write(Query), write( ’ executed ]’ ), nl.

assert_result( ResultSet ) :-
    ResultSet <- next returns Valid, Valid == true, !,
    ResultSet <- getString( ’city_from’ ) returns From,
    ResultSet <- getString( ’city_to’ ) returns To,
    ResultSet <- getInt( ’distance’ ) returns Dist,
    assert( distance(From, To, Dist) ),
    assert_result( ResultSet ).
    assert_result(_).


                                                             2P Intro - 200311
JavaLibrary: Examples (3)
paths( A, B, List, Length ):- path( A, B, List, Length, [] ).
path( A, A, [], 0, _).
path( A, B, [City|Cities], Length, VisitedCities):-
   distance( A, City, Length1 ),
   not( member(City, VisitedCities) ),
   path( City, B, Cities, Length2, [City|VisitedCities] ),
   Length is Length1 + Length2.

min_path( [], X, X) :- !.
min_path( [ pa(Length, List) | L ], pa(MinLen, MinList), Res):-
   Length < MinLen, !,
   min_path( L, pa(Length,List), Res ).

min_path( [_|MorePaths], CurrentMinPath, Res) :-
min_path( MorePaths, CurrentMinPath, Res).

writeList( [] ) :- !.
writeList( [X|L] ) :- write(’,’), write(X), !, writeList( L ).


                                                    2P Intro - 200311
JavaLibrary: Examples (3)

outputResult( From, To, [], _) :- !,
   write(’no path found from ’), write(From),
   write(’ to ’), write(To), nl.

outputResult( From, To, MinList, MinLength) :-
   write(’min path from ’), write(From),
   write(’ to ’), write(To), write(’: ’),
   write(From), writeList(MinList),
   write(’ - length: ’), write(MinLength).




                                                 2P Intro - 200311
Other JavaLibrary features

     • Casting Reference Types
     • Built-ins to access arrays
     • Predefined Object Bindings
   (Refer to 2P user manual for detailed information)



                                                        2P Intro - 200311
Thesis on 2P
• Concluded
  - 2Pme = 2P on Cellular phones (J2ME)
  - 2Pstorm = 2P controlling LEGO Mindstorm Robots
• Ongoing
  - 2P on a web server
• Available
  -   Applications on top of 2Pme
  -   Extending 2P toward Exceptions
  -   Extending the JavaLibrary toward Java Events
  -   Improving 2P performance
  -   MAS on 2P
                                               2P Intro - 200311
2P in Context
•
• 2P for Logic Programming
  - An example: Working with trees

• 2P for AI
• 2P for experiments in DAI/MAS

                                     2P Intro - 200311
An Example of Data Structure:
  Working with Binary Trees

• -A rappresentation:
      tree(Element, Left, Right)
  -   Empty tree: void

• A basic theory
  - Defining a tree
      •   binary_tree(T)

  - Testing for membership
      •   tree_membership(X,T).

  - Visiting a tree
      •   preorder(T,List) / inorder (T,List) / postorder(T,List)




                                                   2P Intro - 200311
A Tree theory (1)
%
% Defining a binary tree
%
binary_tree(void).
binary_tree(tree(Element,Left,Right)):-
    binary_tree(Left), binary_tree(Right).


%
% Testing membership
%
tree_member(X,tree(X,_,_)).
tree_member(X,tree(_,Left,Right)):-tree_member(X,Left).
tree_member(X,tree(_,Left,Right)):-tree_member(X,Right).




                                               2P Intro - 200311
A Tree theory (2)
%
% Visiting a tree
%

% pre-order
preorder(void,[]).
preorder(tree(X,L,R),List):-
    preorder(L,Ls), preorder(R,Rs),
    append([X|Ls],Rs,List).

% in-order
inorder(void,[]).
inorder(tree(X,L,R),List):-
    inorder(L,Ls), inorder(R,Rs),
    append(Ls,[X|Rs],List).

% post-order
postorder(void,[]).
postorder(tree(X,L,R),List):-
    postorder(L,Ls), postorder(R,Rs),
    append(Ls,Rs,L1),
    append(L1,[X],List).


                                        2P Intro - 200311
2P for AI: classic themes
 •   Problem-Solving Strategies
     - depth first, breadth-first, best-first (heuristics)
 •   Game Playing
     - min-max strategy & alpha-beta algorithm
 •   Meta-Programming
     - meta-intepreters
     - implementing foreign paradigms
        • OOP, Pattern-directed Programming, etc
 •   Planning
    - Means-ends algorithm
 • Expert Systems & Knowledge Representation
    - Frames
 • Language Processing & Grammar Rules
 • Machine Learning
(Goodf reference: “Prolog for AI” - Ivan Bratko, Addison Wesley)
                                                           2P Intro - 200311
2P for Rapid Prototyping


    • Interpreters
    • Compilers

                     2P Intro - 200311
2P for experiments
         in DAI & MAS
• 2P for building agents
  - reasoning capabilities
• TuCSoN for communication/coordination
  - alice.tucson.api.TucsonLibrary
    for using TuCSoN from 2P (ver 1.2.1, dist-
    1.3.1)
  - basic TuCSoN primitives
     • TC @ Node ? Operation
     • TC ? Operation (local node)
     • Operation (local node, default tuple centre)


                                              2P Intro - 200311
Simple Agents
                         init(Args):-
                               <init>,
• A simple agent loop          main_loop.
                         main_loop:-
                               <percept>,
                               <reason/plan>,
                               <act>,
                               main_loop.


• Action/Perception through TuCSoN primitives
  (out,in,rd,inp,rdp,set_spec,get_spec)

• Reasoning/planning by means of the agent theory
                                          2P Intro - 200311
A simple task-oriented pattern


• Agents individually are able to solve a problem or
  achieving a task. The basic loop becomes
        main_loop:-
              <in/rd task/problem info>,
              <reason/work>,
              <out results>,
              main_loop.

• Task/Problem info described with logic tuples
• Task/Problem result described with logic tuples

                                           2P Intro - 200311
An example
  • simple task: dumb counting
       :- load_library('alice.tucson.api.TucsonLibrary').

       produce(0):-
           test ? out(count(0)),!.
       produce(N):-
           test ? out(count(N)),
           N1 is N - 1,
           produce(N1).


       init(AgentName):-
           stdout<-print(AgentName),
           stdout<-println(quot; starts working.quot;),
           main_loop.

       main_loop:-
           test ? in(counting_task(N)),
           produce(N),
           main_loop.

spawn the agent from build directory of the distribution with
java alice.tuprolog.Agent producer.pl ‘init(pippo).’
                                                              2P Intro - 200311
Some ideas
• Mobile logic agents
  - Using tuple centres to ‘move’ agent behaviour
    •   continuation-style agent behaviour
         - Theory + NextGoal
    •   request_to_move(Who, AgentTheory, NextGoal)
    •   welcome Tuple Centre in hosting nodes as a glue

  - A simple protocol
    •   welcome @ NodeDest ? out(request_to_move(Me, MyTheory, MyNextGoal))
    •   welcome @ NodeDest ? in(request_result(Me,ok|fail))

  - agent spawner to collect move requests and to spawn
    agents
    •   using agent builtin predicate of BasicLibrary
    •   agent theory (as text) + next goal
                                                              2P Intro - 200311
References

• “The Art of Prolog”, Shapiro et al, Addison Wesley
• “Prolog for AI”, Bratko, Addison Wesley
• “An Introduction to Multi-agent systems”,
  Wooldridge, Wiley


                                            2P Intro - 200311
This is the end


• aricci@deis.unibo.it            for questions, ideas,
  themes, proposals, thesis

• Download the seminar material from
http://alicelab.ing2.unibo.it/downloads/2p-1.2.1-alfa




                                           2P Intro - 200311

Weitere ähnliche Inhalte

Was ist angesagt?

New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Kaunas Java User Group
 
Java Platform Module System
Java Platform Module SystemJava Platform Module System
Java Platform Module SystemVignesh Ramesh
 
DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaHenri Tremblay
 
JCConf 2018 - Retrospect and Prospect of Java
JCConf 2018 - Retrospect and Prospect of JavaJCConf 2018 - Retrospect and Prospect of Java
JCConf 2018 - Retrospect and Prospect of JavaJoseph Kuo
 
TWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java Versions
TWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java VersionsTWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java Versions
TWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java VersionsJoseph Kuo
 
Pure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools RacePure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools RaceBaruch Sadogursky
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 

Was ist angesagt? (20)

Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 
Java Platform Module System
Java Platform Module SystemJava Platform Module System
Java Platform Module System
 
DevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern JavaDevNexus 2020: Discover Modern Java
DevNexus 2020: Discover Modern Java
 
JCConf 2018 - Retrospect and Prospect of Java
JCConf 2018 - Retrospect and Prospect of JavaJCConf 2018 - Retrospect and Prospect of Java
JCConf 2018 - Retrospect and Prospect of Java
 
TWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java Versions
TWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java VersionsTWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java Versions
TWJUG x Oracle Groundbreakers 2019 Taiwan - What’s New in Last Java Versions
 
Pure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools RacePure Java RAD and Scaffolding Tools Race
Pure Java RAD and Scaffolding Tools Race
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
04 sorting
04 sorting04 sorting
04 sorting
 
Java after 8
Java after 8Java after 8
Java after 8
 
All experiment of java
All experiment of javaAll experiment of java
All experiment of java
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 

Ähnlich wie 2 P Seminar

[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cooljavablend
 
Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009Bastian Feder
 
Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.Michal Malohlava
 
Php Development With Eclipde PDT
Php Development With Eclipde PDTPhp Development With Eclipde PDT
Php Development With Eclipde PDTBastian Feder
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsMiles Sabin
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Sparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with SparkSparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with Sparkfelixcss
 
Doctrine Php Object Relational Mapper
Doctrine Php Object Relational MapperDoctrine Php Object Relational Mapper
Doctrine Php Object Relational MapperJonathan Wage
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsJarrod Overson
 
GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015Fabrízio Mello
 
0396 oracle-goldengate-12c-tutorial
0396 oracle-goldengate-12c-tutorial0396 oracle-goldengate-12c-tutorial
0396 oracle-goldengate-12c-tutorialKlausePaulino
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG ManiaplAnkur Shrivastava
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
How to lock a Python in a cage? Managing Python environment inside an R project
How to lock a Python in a cage?  Managing Python environment inside an R projectHow to lock a Python in a cage?  Managing Python environment inside an R project
How to lock a Python in a cage? Managing Python environment inside an R projectWLOG Solutions
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Martijn Verburg
 
Adopting GraalVM - Scale by the Bay 2018
Adopting GraalVM - Scale by the Bay 2018Adopting GraalVM - Scale by the Bay 2018
Adopting GraalVM - Scale by the Bay 2018Petr Zapletal
 

Ähnlich wie 2 P Seminar (20)

Ropython-windbg-python-extensions
Ropython-windbg-python-extensionsRopython-windbg-python-extensions
Ropython-windbg-python-extensions
 
[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool[Strukelj] Why will Java 7.0 be so cool
[Strukelj] Why will Java 7.0 be so cool
 
Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009Eclipse Pdt2.0 26.05.2009
Eclipse Pdt2.0 26.05.2009
 
Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.
 
Php Development With Eclipde PDT
Php Development With Eclipde PDTPhp Development With Eclipde PDT
Php Development With Eclipde PDT
 
Apache Zeppelin, Helium and Beyond
Apache Zeppelin, Helium and BeyondApache Zeppelin, Helium and Beyond
Apache Zeppelin, Helium and Beyond
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Sparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with SparkSparkly Notebook: Interactive Analysis and Visualization with Spark
Sparkly Notebook: Interactive Analysis and Visualization with Spark
 
Doctrine Php Object Relational Mapper
Doctrine Php Object Relational MapperDoctrine Php Object Relational Mapper
Doctrine Php Object Relational Mapper
 
How to Reverse Engineer Web Applications
How to Reverse Engineer Web ApplicationsHow to Reverse Engineer Web Applications
How to Reverse Engineer Web Applications
 
GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015GSoC2014 - Uniritter Presentation May, 2015
GSoC2014 - Uniritter Presentation May, 2015
 
0396 oracle-goldengate-12c-tutorial
0396 oracle-goldengate-12c-tutorial0396 oracle-goldengate-12c-tutorial
0396 oracle-goldengate-12c-tutorial
 
Python Workshop. LUG Maniapl
Python Workshop. LUG ManiaplPython Workshop. LUG Maniapl
Python Workshop. LUG Maniapl
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
How to lock a Python in a cage? Managing Python environment inside an R project
How to lock a Python in a cage?  Managing Python environment inside an R projectHow to lock a Python in a cage?  Managing Python environment inside an R project
How to lock a Python in a cage? Managing Python environment inside an R project
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
 
Kommons
KommonsKommons
Kommons
 
Adopting GraalVM - Scale by the Bay 2018
Adopting GraalVM - Scale by the Bay 2018Adopting GraalVM - Scale by the Bay 2018
Adopting GraalVM - Scale by the Bay 2018
 

Kürzlich hochgeladen

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 

Kürzlich hochgeladen (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 

2 P Seminar

  • 1. tuProlog (2P) A Java-based Prolog System for Pervasive Intelligence alessandro ricci PhD at DEIS aricci@deis.unibo.it
  • 2. Outline • Introduction: 2P Objectives & Design - 2P technology & tools • Using 2P from Java - 2P API • Extending 2P: Libraries • Using Java from 2P: The JavaLibrary • 2P in context - AI, DAI, MAS 2P Intro - 200311
  • 3. What is 2P • Java-Based Prolog Virtual Machine - minimality & dynamic/open extesibility/configurability - bidirectional Java integration • Java API to use Prolog From Java - alice.tuprolog package • 2P Extensions/Tools - alice.tuprologx.* package - IDEs - Extensions (libraries, theories) 2P Intro - 200311
  • 4. 2P Targets • As components to be integrated in Java development for intelligent application - Symbolic Reasoning in a OOP context - “Intelligence + Interaction” • Internet Applications - as lightweight component for applet, servlet, mobile code, network-enabled devices • Intelligent Infrastructures - Building agent systems - ReSpecT Coordination framework & TuCSoN Infrastructure 2P Intro - 200311
  • 5. Getting Started • 2P is open source • Download from - http://lia.deis.unibo.it/research/tuprolog - http://tuprolog.sourceforge.net • -Download what tuprolog.jar, tuprologx.jar, 2P.jar - Full package: 2p-X.Y.Z.zip • src/build/lib/bin 2P Intro - 200311
  • 6. Getting Started: 2P from Java • From Java - Using 2P engines in the context of Java applications - Include the package 2p.jar in the classpath • or tuprolog.jar + tuprologx.jar - Package to import: alice.tuprolog 2P Intro - 200311
  • 7. The 2P Tools: IDEs • Command Line IDE - alice.tuprologx.ide.CUIConsole application - java -cp 2p.jar alice.tuprologx.ide.CUIConsole • GUI based IDE (with 2P alfa version 1.2.1) - alice.tuprologx.ide.GUILauncher application - java -cp 2p.jar alice.tuprologx.ide.GUILauncher • GUI based IDE (with 2P version 1.2.0) - alice.tuprologx.ide.GUIConsole application - java -cp 2p.jar alice.tuprologx.ide.GUIConsole 2P Intro - 200311
  • 8. The 2P Tools: Others • Spawning an agent - alice.tuprolog.Agent application java -cp tuprolog.jar alice.tuprolog.Agent PrologTheoryTextFile {Goal} • Examples - text file hello.pl containing - spawning the agent: java -cp tuprolog.jar alice.tuprolog.Agent hello.pl go. 2P Intro - 200311
  • 9. 2P Main Elements • Core Inferential Engine - class Prolog • Theories - class Theory • Libraries - class Library (abstract) • Prolog Data Types - class Term (abstract), Number (abstract), Int/Long/Float/Double (concrete), Struct (concrete),Var (concrete) 2P Intro - 200311
  • 10. 2P Data Types Term Var Struct Number Long Int Float Double 2P Intro - 200311
  • 11. 2P Engine Design • Self-Contained, with no static links - Enabling multiple engines, independently configured (theory, libraries), in the same computational context • Minimal Interface - setting, retrieving, adding theories - solving goal - load & unload libraries 2P Intro - 200311
  • 12. An example: a theory for expression derivation & evaluation (1) dExpr(T,X,DT):-dTerm(T,X,DT). dExpr(E+T,X,[DE+DT]):-dExpr(E,X,DE), dTerm(T,X,DT). dExpr(E-T,X,[DE-DT]):-dExpr(E,X,DE), dTerm(T,X,DT). dTerm(F,X,DF):-dFactor(F,X,DF). dTerm(T*F,X,[[DT*F]+[T*DF]]):-dTerm(T,X,DT), dFactor(F,X,DF). dTerm(T/F,X,[[F*DT]-[T*DF]]/[F*F]):-dTerm(T,X,DT), dFactor(F,X,DF). dFactor(-E,X,-DE):-dExpr(E,X,DE). dFactor([E],X,DE):-dExpr(E,X,DE). dFactor(N,X,0):-number(N). dFactor(X,X,1). dFactor(F^N,X,[[N*[F^M]]*DF]):-M is N-1, dFactor(F,X,DF). dFactor(sin(E),X,[cos(E)*DE]):-dExpr(E,X,DE). dFactor(cos(E),X,[-sin(E)*DE]):-dExpr(E,X,DE). (cont) 2P Intro - 200311
  • 13. An example: a theory for expression derivation & evaluation (2) (cont) evalExpr(T,V,R):-evalTerm(T,V,R). evalExpr(E+T,V,R):-evalExpr(E,V,R1), evalTerm(T,V,R2), R is R1+R2. evalExpr(E-T,V,R):-evalExpr(E,V,R1), evalTerm(T,V,R2), R is R1-R2. evalTerm(F,V,R):-evalFactor(F,V,R). evalTerm(T*F,V,R):-evalTerm(T,V,R1), evalFactor(F,V,R2), R is R1*R2. evalTerm(T/F,V,R):-evalTerm(T,V,R1), evalFactor(F,V,R2), R is R1/R2. evalFactor(-E,V,R):-evalExpr(E,V,R1), R is -R1. evalFactor([E],V,R):-evalExpr(E,V,R). evalFactor(N,V,N):-number(N). evalFactor(x,V,V). evalFactor(F^E,V,R):-evalFactor(F,V,R1),evalExpr(E,V,R2),R is R1^R2. evalFactor(sin(E),V,R):-evalExpr(E,V,R1),R is sin(R1). evalFactor(cos(E),V,R):-evalExpr(E,V,R1),R is cos(R1). 2P Intro - 200311
  • 14. Using the theory from Java 2P Intro - 200311
  • 15. 2P API: The Engine 2P Intro - 200311
  • 16. Data Types API Example 2P Intro - 200311
  • 17. 2P Libraries (ver. 1.2.1) • Structure • Developing a Library • Default Libraries • The JavaLibrary 2P Intro - 200311
  • 18. Library Structure • Name • Set of built-in predicates - only one (boolean) solution (no open choices) - loosing non-determinism • Set of built-in functors • Theory - typically providing rules on top of the built-in predicates/functors - recovering non-determinism 2P Intro - 200311
  • 19. Developing a Library • Extending alice.tuprolog.Library abstract class - provides some basic services • Unification: boolean unify(Term arg0, Term arg1) • Writing built-in predicates as methods - boolean predicateName_arityN(Term arg1,..., Term argN) • fails if exceptions are thrown • Writing built-in funtors as methods - Term functorName_arityN(Term arg1,..., Term argN) • fails if exceptions are thrown • Defining the theory - overriding String getTheory() method - default = empty theory = empty string • Defining the name - overriding String getName() method - default = class name
  • 20. Example package alice.test.tuprolog; import alice.tuprolog.*; public class StringLibrary extends Library { public boolean to_lower_case_2(Term arg0, Term arg1){ String dest = arg0.toString().toLowerCase(); return unify(arg1, new Struct(dest)); } } 2P Intro - 200311
  • 21. Example (2) package alice.test.tuprolog; import alice.tuprolog.*; import alice.tuprolog.Number; public class TestLibrary extends StringLibrary { public Term sum_2(Number arg0, Number arg1){ int sum = arg0.intValue()+arg1.intValue(); return new Int(sum); } public String getTheory(){ return “print_sum(A,B):- N is sum(A,B), n”+ “write(N),nl. n”; } 2P Intro - 200311
  • 22. Remarks • Libraries as bridge to legacy libreries & code - not only Java • exploiting JNI • Solution for specialised & performant computation - Math libraries - Graphics 3D/2D libraries (e.g. OpenGL) - Multimedia libraries • sound, video streaming, etc 2P Intro - 200311
  • 23. Standard Libraries • Package alice.tuprolog.lib • Basic Library - alice.tuprolog.lib.BasicLibrary - basic & frequent builtins • ISO Library - alice.tuprolog.lib.ISOLibrary - ISO standard builtins • IO Library - alice.tuprolog.lib.IOLibrary - Input/Output Builtins (File, Console, etc) • Java Library - alice.tuprolog.lib.JavaLibrary - Using Java from 2P
  • 24. The JavaLibrary • Goals - reusing all the Java world from Prolog - OOP-oriented access style • object creation • method invocation - full dynamism • classes/objects created/linked at run-time - Java Event Management (1.2.1 version) 2P Intro - 200311
  • 25. JavaLibrary Design Goal • Mapping 1-1 with Java operation - simple object creation - method invocation - field access • Keeping the two paradigms separated - Object references are denotated by simple terms - The terms refer to Java objects only in the context of JavaLibrary builtins predicates/operators • not embedding an OOP model inside the Prolog virtual machine 2P Intro - 200311
  • 26. Simple class used for the examples public class Counter { private int value; public String name; public Counter(){} public Counter(String n){ name=n; } public void setValue(int val){ value=val; } public int getValue() { return value; } public void inc() { value++; } public void setName(String s) { name = s;} static public String getVersion() { return quot;1.0quot;; } } 2P Intro - 200311
  • 27. Creating Java Objects • Syntax java_object(@ClassName,@ArgumentList,?ObjectRef) • Semantics - the predicate is true if ObjectRef denotates a new instance of a Java object of class ClassName created with arguments ArgumentList • Example ?- java_object(’Counter’,[],MyCounter). ?- java_object(’Counter’,[],aCounter). ?- java_object(’Counter’,[’pippo’],pippoCounter). • For arrays java_object(@ClassName[],@ArgumentList,?ObjectRef) - Example ?- java_object(’Counter[]’,[10],MyArray). 2P Intro - 200311
  • 28. Method Invocation • Syntax @TargetRef <- @MethodName(@Arguments) @TargetRef <- @MethodName(@Arguments) returns ?Result class(@ClassName) <- @MethodName(...) ... • Semantics - the predicate is true if the method MethodName can be invoked on the object referenced by TargetRef possibly obtaining a result unifying with Result. • Examples ?- MyCounter <- setValue(303). ?- pippoCounter <- getValue returns Value. ?- class(’Counter’) <- getVersion returns Version. 2P Intro - 200311
  • 29. Accessing Fields • Syntax @TargetRef . @Field <- set(@Content) @TargetRef . @Field <- get(?Content) • Semantics - the predicates are true if the content of the field Field of the object referenced by TargetRef can be set with the value Content or can be read and its value unifies the Content value. • Examples ?- MyCounter.name <- get(Name). ?- pippoCounter.name <- set(’pippo2’). 2P Intro - 200311
  • 30. Dynamic Compilation • Compiling dynamically a Java class given its source • Syntax java_class(@Source,@FullClassName,@ClassPathList,-ClassRef) • Semantics - the predicate is true if ClassRef is the reference to an object class whose name is FullClassName and it can be obtained by compiling the source Source with class pathes of the list ClassPathList. • Example 2P Intro - 200311
  • 31. JavaLibrary: Overall Example test:- java_object('Counter',['ANiceCounter'],myCounter), myCounter <- setValue(5), myCounter <- inc, myCounter <- getValue returns Value, write(Value), class('Counter') <- getVersion returns Version, class('java.lang.System').out <- get(StdOut), StdOut <- println(Version), myCounter.name <- get(MyName), StdOut <- println(MyName), myCounter.name <- set('NicerCounter'), java_object('Counter[]', [10], ArrayCounters), java_array_set(ArrayCounters, 3, myCounter). 2P Intro - 200311
  • 32. JavaLibrary: Examples (1) Opening a swing dialog for choosing a file: 2P Intro - 200311
  • 33. Java Library: Examples (2) • Using RMI Infrastructure ?- java_object(’java.rmi.RMISecurityManager’,[],Manager), class(’java.lang.System’) <- setSecurityManager(Manager), class(’java.rmi.Naming’) <- lookup(’pippoCounter’) returns MyCounter, MyCounter <- inc, MyCounter <- getValue returns Val, write(Val),nl. • In Java... ... RMISecurityManager rman = new RMISecurityManager(); System.setSecurityManager(rman); Counter core=(Counter)Naming.lookup(quot;pippoCounterquot;); counter.inc(); long val = counter.getValue(); System.out.println(val); 2P Intro - 200311
  • 34. JavaLibrary: Examples (3) “Find the minimum path between two cities. City distances are stored in a standard DB (table ‘distances’, city_from/city_to/length row)” find_path( From, To ):- init_dbase( ’jdbc:odbc:distances’, Connection,’’,’’), exec_query( Connection, ’SELECT city_from, city_to, distance FROM distances.txt’,ResultSet ), assert_result( ResultSet ), findall( pa(Length,L), paths(From,To,L,Length), PathList ), current_prolog_flag( max_integer, Max ), min_path( PathList, pa(Max,_), pa(MinLength, MinList) ), outputResult( From, To, MinList, MinLength ). 2P Intro - 200311
  • 35. JavaLibrary: Examples (3) % Access to Database init_dbase( DBase, Username, Password, Connection ) :- class(’java.lang.Class’) <- forName( ’sun.jdbc.odbc.JdbcOdbcDriver’ ), class(’java.sql.DriverManager’) <- getConnection( DBase, Username, Password) returns Connection, write( ’[ Database ’ ), write(DBase), write(’ connected ]’ ), nl. exec_query( Connection, Query, ResultSet ):- Connection <- createStatement returns Statement, Statement <- executeQuery( Query ) returns ResultSet, write( ’[ query ’ ), write(Query), write( ’ executed ]’ ), nl. assert_result( ResultSet ) :- ResultSet <- next returns Valid, Valid == true, !, ResultSet <- getString( ’city_from’ ) returns From, ResultSet <- getString( ’city_to’ ) returns To, ResultSet <- getInt( ’distance’ ) returns Dist, assert( distance(From, To, Dist) ), assert_result( ResultSet ). assert_result(_). 2P Intro - 200311
  • 36. JavaLibrary: Examples (3) paths( A, B, List, Length ):- path( A, B, List, Length, [] ). path( A, A, [], 0, _). path( A, B, [City|Cities], Length, VisitedCities):- distance( A, City, Length1 ), not( member(City, VisitedCities) ), path( City, B, Cities, Length2, [City|VisitedCities] ), Length is Length1 + Length2. min_path( [], X, X) :- !. min_path( [ pa(Length, List) | L ], pa(MinLen, MinList), Res):- Length < MinLen, !, min_path( L, pa(Length,List), Res ). min_path( [_|MorePaths], CurrentMinPath, Res) :- min_path( MorePaths, CurrentMinPath, Res). writeList( [] ) :- !. writeList( [X|L] ) :- write(’,’), write(X), !, writeList( L ). 2P Intro - 200311
  • 37. JavaLibrary: Examples (3) outputResult( From, To, [], _) :- !, write(’no path found from ’), write(From), write(’ to ’), write(To), nl. outputResult( From, To, MinList, MinLength) :- write(’min path from ’), write(From), write(’ to ’), write(To), write(’: ’), write(From), writeList(MinList), write(’ - length: ’), write(MinLength). 2P Intro - 200311
  • 38. Other JavaLibrary features • Casting Reference Types • Built-ins to access arrays • Predefined Object Bindings (Refer to 2P user manual for detailed information) 2P Intro - 200311
  • 39. Thesis on 2P • Concluded - 2Pme = 2P on Cellular phones (J2ME) - 2Pstorm = 2P controlling LEGO Mindstorm Robots • Ongoing - 2P on a web server • Available - Applications on top of 2Pme - Extending 2P toward Exceptions - Extending the JavaLibrary toward Java Events - Improving 2P performance - MAS on 2P 2P Intro - 200311
  • 40. 2P in Context • • 2P for Logic Programming - An example: Working with trees • 2P for AI • 2P for experiments in DAI/MAS 2P Intro - 200311
  • 41. An Example of Data Structure: Working with Binary Trees • -A rappresentation: tree(Element, Left, Right) - Empty tree: void • A basic theory - Defining a tree • binary_tree(T) - Testing for membership • tree_membership(X,T). - Visiting a tree • preorder(T,List) / inorder (T,List) / postorder(T,List) 2P Intro - 200311
  • 42. A Tree theory (1) % % Defining a binary tree % binary_tree(void). binary_tree(tree(Element,Left,Right)):- binary_tree(Left), binary_tree(Right). % % Testing membership % tree_member(X,tree(X,_,_)). tree_member(X,tree(_,Left,Right)):-tree_member(X,Left). tree_member(X,tree(_,Left,Right)):-tree_member(X,Right). 2P Intro - 200311
  • 43. A Tree theory (2) % % Visiting a tree % % pre-order preorder(void,[]). preorder(tree(X,L,R),List):- preorder(L,Ls), preorder(R,Rs), append([X|Ls],Rs,List). % in-order inorder(void,[]). inorder(tree(X,L,R),List):- inorder(L,Ls), inorder(R,Rs), append(Ls,[X|Rs],List). % post-order postorder(void,[]). postorder(tree(X,L,R),List):- postorder(L,Ls), postorder(R,Rs), append(Ls,Rs,L1), append(L1,[X],List). 2P Intro - 200311
  • 44. 2P for AI: classic themes • Problem-Solving Strategies - depth first, breadth-first, best-first (heuristics) • Game Playing - min-max strategy & alpha-beta algorithm • Meta-Programming - meta-intepreters - implementing foreign paradigms • OOP, Pattern-directed Programming, etc • Planning - Means-ends algorithm • Expert Systems & Knowledge Representation - Frames • Language Processing & Grammar Rules • Machine Learning (Goodf reference: “Prolog for AI” - Ivan Bratko, Addison Wesley) 2P Intro - 200311
  • 45. 2P for Rapid Prototyping • Interpreters • Compilers 2P Intro - 200311
  • 46. 2P for experiments in DAI & MAS • 2P for building agents - reasoning capabilities • TuCSoN for communication/coordination - alice.tucson.api.TucsonLibrary for using TuCSoN from 2P (ver 1.2.1, dist- 1.3.1) - basic TuCSoN primitives • TC @ Node ? Operation • TC ? Operation (local node) • Operation (local node, default tuple centre) 2P Intro - 200311
  • 47. Simple Agents init(Args):- <init>, • A simple agent loop main_loop. main_loop:- <percept>, <reason/plan>, <act>, main_loop. • Action/Perception through TuCSoN primitives (out,in,rd,inp,rdp,set_spec,get_spec) • Reasoning/planning by means of the agent theory 2P Intro - 200311
  • 48. A simple task-oriented pattern • Agents individually are able to solve a problem or achieving a task. The basic loop becomes main_loop:- <in/rd task/problem info>, <reason/work>, <out results>, main_loop. • Task/Problem info described with logic tuples • Task/Problem result described with logic tuples 2P Intro - 200311
  • 49. An example • simple task: dumb counting :- load_library('alice.tucson.api.TucsonLibrary'). produce(0):- test ? out(count(0)),!. produce(N):- test ? out(count(N)), N1 is N - 1, produce(N1). init(AgentName):- stdout<-print(AgentName), stdout<-println(quot; starts working.quot;), main_loop. main_loop:- test ? in(counting_task(N)), produce(N), main_loop. spawn the agent from build directory of the distribution with java alice.tuprolog.Agent producer.pl ‘init(pippo).’ 2P Intro - 200311
  • 50. Some ideas • Mobile logic agents - Using tuple centres to ‘move’ agent behaviour • continuation-style agent behaviour - Theory + NextGoal • request_to_move(Who, AgentTheory, NextGoal) • welcome Tuple Centre in hosting nodes as a glue - A simple protocol • welcome @ NodeDest ? out(request_to_move(Me, MyTheory, MyNextGoal)) • welcome @ NodeDest ? in(request_result(Me,ok|fail)) - agent spawner to collect move requests and to spawn agents • using agent builtin predicate of BasicLibrary • agent theory (as text) + next goal 2P Intro - 200311
  • 51. References • “The Art of Prolog”, Shapiro et al, Addison Wesley • “Prolog for AI”, Bratko, Addison Wesley • “An Introduction to Multi-agent systems”, Wooldridge, Wiley 2P Intro - 200311
  • 52. This is the end • aricci@deis.unibo.it for questions, ideas, themes, proposals, thesis • Download the seminar material from http://alicelab.ing2.unibo.it/downloads/2p-1.2.1-alfa 2P Intro - 200311