amzi! logic server for java applications. references: amzi! is a registered
TRANSCRIPT
Amzi! Logic Server for Java Applications
References:http://www.amzi.comhttp://java.sun.com
Amzi! is a registered trademark and Logic Server is trademark of Amzi! Inc.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 3
Synopsis
Logic server is a software technology to access Prolog engine from host languages such as Java/C++/VB.
This lecture will demonstrate Logic Server classes for Java
applications. examine some of the classes/methods that give
the developer full control over the Prolog engine
Note: This is NOT a course to teach Java/Prolog programming.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 4
Target Audience
Lab Tutor for Artificial Intelligence (AI) courses
so that simple LogicServer module can be included in the syllabus of AI laboratory
Anyone who knows Java/Prolog programming but not sure how to link a back-end (Prolog) to a front-end (e.g. Java/VB/C++)
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 5
Outline
Overview: The Amzi! Logic Server (LS) Technology Main Functions of the Logic ServerAPI functions that correspond to the class methods of the API Java Class Encapsulates the Amzi! Logic ServerEntry Points String Passing Interface Converting Terms to Strings Backtracking through Multiple Answers Putting it all together: The pseudo codeConsulting Prolog Source Code Writing Extended PredicatesLSAPI Error Handling Software: Java2 SDK + any IDE + JRE & Prolog Engine + Amzi! LSConfiguration Tips & Programs Demo
Amzi! Logic Server(= Prolog Engine)
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 7
The needs
Java doesn’t speak prolog & Prolog speaks only prolog. So, LS technology is required to bridge the two to
build intelligent applications
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 8
From right to left in the diagram, amzi.dll is the Amzi! Logic Server.
amzijni.dll / libamzijni.so is the interface library that implements the Java versions of Logic Server API functions.
Those, in turn are wrapped in the Java classes, LogicServer and LSException.
Overview: The Amzi! LS for Java
The Java Class is implemented using the Java Native Interface (JNI).
Source: www.amzi.com
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 9
Why JNI?
In the case of Amzi!, the JNI is used to build a bridge to the Logic Server API, which is the external interface on the Amzi! Prolog engine.
The bridge is necessary because many of the Logic Server API functions have to be changed slightly to conform to Java parameter passing and return conventions This is to accommodate the lack of pointer support in
Java
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 10
Just Prolog ‘Listener’..will look like this
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 11
hello(Caller, Greeting) :- strcat($Greetings $, Caller, S1), strcat(S1, $, from Amzi! Prolog.$, Greeting).
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 12
.. Let’s pass it to Java
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 13
package hello; import amzi.ls.*; class Hello { public static void main(String args[]) throws LSException { long term; String result; LogicServer ls = new LogicServer(); ls.Init(""); ls.Load("hello.xpl"); term = ls.ExecStr("hello($..I\'m a Java Programmer$, Response)"); if (term == 0) System.out.println("Hello Failed"); else { result = ls.GetStrArg(term, 2); System.out.println(result); } ls.Close(); } }
Greetings from Prolog, displayed in Java Env.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 14
Main functions of the Logic Server
Two primary interfaces to the LSAPIThe Class interface is the LogicServer and LSException classes and their methods.
All the names start with 'ls'.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 15
Java Class encapsulates the Amzi! Logic Server
For use by Java applications and applets. A Java Class Package that encapsulates
a Logic Server Engine Methods that correspond to the Logic
Server API Functions Use of Java's exception handling for API
errors
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 16
API functions that correspond to the class methods of the API
Logic Server Return Codes Prolog Terms String Passing Interface Scope of Logic Server Terms Implementing a Simple Prolog Listener Calling Terms Mapping Prolog Arguments to Host
Variables Making Simple Terms Handling Varying Prolog Types Manipulating Structures Manipulating Lists Asserting and Retracting Dynamic
Clauses Consulting Prolog Source Running Multiple Engines Writing Extended Predicates etc.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 17
Entry Points The simplest host program to call Prolog clauses is
one that initializes the Prolog engine, loads a Prolog logic-base, calls its main/0 predicate and then closes the Prolog engine.
To do this, the following functions are required: Init(logic_base_name)
Initializes the Logic Server engine, allocating resources as needed.
Load(logic_base_name) Loads the compiled Prolog .xpl file for logic_base_name.
A .xpl file must always be loaded before executing any Prolog code. This is because a .xpl file includes a copy of alib.plm which implements a portion of the Prolog system software.
Main() returns TF Calls the main/0 predicate of the loaded program.
Close() Releases the memory and files used by the Logic Server
engine.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 18
Example You can write a simple host
language shell that runs the a Prolog program, ipts.xpl
Note: xpl = load module is needed
try { amzi.ls.LogicServer ls = new amzi.ls.LogicServer(); ls.Init(""); ls.Load("ipta.xpl"); term = ls.CallStr("local_u(X, Y)"); input = JOptionPane.showInputDialog("Enter Option (1 = MsgDialog, 2 = TextArea)"); ans = Integer.parseInt(input); if (ans==1) { outArea.setText("Name\tCity\n"); outArea.append("---------------\n"); if (term == 0) { outArea.append("Tiada Jawapan!!"); ls.Close(); return; } do { outArea.append(ls.GetStrArg(term, 1) + "\t"); outArea.append(ls.GetStrArg(term, 2) + "\n"); } while (ls.Redo()); JOptionPane.showMessageDialog(null, outArea, "Results retrieved from prolog facts", JOptionPane.INFORMATION_MESSAGE); ls.Close();
% ipta.pro local_u(um, kl). local_u(ukm, bangi). local_u(upm, serdang). local_u(usm, penang). local_u(utm, skudai). local_u(uniten, kajang).
Java Interface
The Knowledge Base
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 19
Look, facts are being pulled out from the .xpl module
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 20
More Examples
You can write a simple host language shell that runs the a Prolog program, hello.xpl & pets.xpl respectively.
ls.Init(); ls.Load(“hello.xpl"); ls.Main(); ls.Close();
ls.Init(); ls.Load(“pets.xpl"); ls.Main(); ls.Close();
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 21
String Passing Interface
Calling Prolog with a String Query CallStr(query_string) returns term
Convert query_string into a Prolog term pointed to by term_ptr, and call that Prolog term.
ExecStr(query_string) returns term Like CallStr, except it is optimized for queries
that will not be backtracked through.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 22
Example of CallStr() Use
For example, using a classic family tree Prolog application, you might want to issue the query 'sister(julie, X)' to find the sisters of julie.
If you entered this query at a Prolog listener
?- sister(julie). Prolog would first convert that input to a
term, and call it. This is exactly what CallStr() does.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 23
Converting Terms to Strings TermToStr(term, string, maxlength)
returns string Convert the term to a string no longer than
max-length characters. TermToStrQ(term, string, maxlength)
returns string Convert the term to a string, using quotes for
atoms and strings as necessary, so they can be used as input to Prolog again, if necessary.
StrTermLen(term) returns length Returns the size of the string needed to hold
the string representation of the term.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 24
Backtracking through Multiple Answers Once you have retrieved one answer from a
query, you can induce Prolog backtracking and get the next answer. You can do this until there are no more answers using Redo().
Redo() returns TF Using the term pointed to by the previous CallStr,
backtrack and redo the query. If the query succeeds, the term is now unified based
on this success and Redo() returns true, otherwise it returns false.
In Prolog, to ask for more is to press/type ‘;’ at the prompt
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 25
Putting it all together
The following examples make use of this Prolog program.
% a prolog source code, family.pro
mother(mary,julie). mother(mary,sandy).mother(mary,ricky). mother(mary,jenny).
sibling(X,Y) :- mother(P,X), mother(P,Y).
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 26
The pseudo code This finds all of the sisters of julie and prints
the full terms for each successful answer. declare TERM t declare STRING s of length 80 ls.Init() ls.Load(“family.pro") tf = ls.CallStr(&t, "sibling(julie, X)")
while (tf == true) L s.TermToStr(t, s, 80)
print(s) tf = ls.Redo()
end while ls.Close()
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 27
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 28
The facts (.pro)
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 29
Mapping Prolog Arguments to Host Variables (I)
One way to map Prolog arguments to host language variables is to convert the resultant term into a string, and parse the
string. Remember that a Prolog query term is usually a
structure, with a functor and a number of arguments. For example, the query 'sibling(julie, X)' is a
Prolog term/structure with the functor 'sibling' and two arguments.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 30
Mapping Prolog Arguments to Host Variables (II)
Given this, a function that can retrieve a specific argument from a term/structure and map it into a variable is a very useful one.
GetFloatArg(term, i_arg) returns double Gets the ith argument of term t and returns it as a host language double
variable. GetIntArg(term, i_arg) returns int
Gets the ith argument of term t and returns it as a host language double int. GetStrtArg(term, i_arg) returns string
Gets the ith argument of term t and returns it as a host language string. lsGetArg(term, i_arg, v_type, var) returns RC
Gets the ith argument of term t and converts it to host language type v_type and puts the result in variable var.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 31
Making Simple Terms In addition to the string-based functions, the API
provides specific functions to make simple terms. These are:
MakeAtom(string) returns term Returns a Prolog atom term created from the host language string.
MakeStr(term_ptr, string) returns term Returns a Prolog string term created from the host language string.
MakeInt(term_ptr, int) returns term Returns a Prolog integer term created from the host language integer.
MakeFloat(term_ptr, float) returns term Returns a Prolog double precision float term created from the host
language double precision float.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 32
testing(1, 200000, 3.4, abc, $Universiti Tenaga Nasional$).
A prolog fact
Multiple termsare made and called from VB
The codes? … next slide
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 33
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 34
Consulting Prolog Source Code You can also consult or re-consult source files of Prolog
code. It can be done by simply issuing a Prolog goal to consult or
re-consult a file, just as you would from Prolog listener. You can also load separate modules of compiled Prolog
code if desired. For example:
ls.ExecStr(&term, "consult(ipts)") ls.ExecStr(&term, "reconsult(ipts)") ls.ExecStr(&term "load(ipts)")
Note: If you wish to use them, you must have first loaded any XPL file. This is
because .xpl files are linked with alib.plm, which contains some of Amzi! Prolog's built-in predicate (such as consult, reconsult and load).
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 35
Writing Extended Predicates To call a host language from Prolog,
you must create extended predicates. These behave just like any other built-
in Prolog predicates, except you have written them.
Note: Only host languages that support p_______ or virtual machine extensions, such as C/C++, Delphi or Java, can be used for implementing extended predicates.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 36
Adding extended predicate
Define a host language function that will implement the predicate.
Inform the Logic Server during initialization of the name and arity of the Prolog predicate the address of the host language function
that implements it.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 37
Initializing the Extended Predicates Once you have defined a number of functions, you need to
let the Logic Server know about them. This is done after the call to Init in one of three different
ways. AddPred(functor, arity, function_ptr)
Maps the Prolog predicate of functor/arity to the host language function. Must be called once for each extended predicate.
InitPreds(pred_table_ptr) Uses a host language table that maps Prolog predicates
to functions. Called once to initialize all of the predicates in the table.
InitLSX(ptr) Causes the Logic Server to check the .cfg file for a lsxload
parameter. It then automatically loads any .LSXs (DLLs containing extended predicates) listed in the .cfg file.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 38
Implementing Extended Predicates Java, like C/C++, Delphi and VB 5.0 (and later), can be
used to implement custom extended predicates to the Prolog language.
These custom extensions give the Prolog code the ability to directly access anything Java can access.
The Java methods that implement extended predicates, must be declared as returning type boolean, and as public.
If your extended predicate is in a package, then the package name must be included in the class name, delimited by forward slashes, to AddPred as follows: ls.AddPred("extpred", 1, "javapkg/jprolog", "extpred", this);
Note: Extended predicate definitions must always be added after calling InitLS and before calling LoadXPL.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 39
‘prompt’ is a Prolog Extended Predicate (i.e. a Java Method)
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 40
The method is implemented here
Register it to Amzi!
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 41
output
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 42
LSAPI Error Handling
When used from Java or another object-oriented language, all errors from LSAPI functions are thrown using the LSException class.
Class Error Handling When an exception occurs in the engine, and the engine
was accessed from the LogicServer class, then an instance of LSException is thrown.
When catching Logic Server exceptions, it is better to catch a reference to the exception object.
For example: try { // Logic Server stuff } catch(LSException &e) { // recovery stuff }
Java Meets Prolog
Program extensions that needed (.java, .class, .pro, .plm, .xpl, &.jpx)
Software dependent
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 44
Java and Prolog
Java is designed to be an object oriented language for deploying secure, multithreaded network applications (both clients and servers).
Prolog is ideal for building intelligent components, expert systems and logic-bases.
In combination, Java and Prolog are a good pair for delivering useful intelligent applications.
Back-end handles reasoning/searching/etc., while the front-end does some numerical processing and
prepares the GUI components.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 45
Software Download &
Configuration Tips
1. Refer www.amzi.com for “How to install the Logic Server as a Java class”.
2. You can download Sun's Development Kit (e.g. SDK) from http://developers.sun.com/
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 46
Configuration
To use the Java Class, you must make the following files accessible to the calling environment:
Amzi! Dynamic/Shared Library The Amzi! Logic Server, amzi.dll or libamzi.so, and the
Amzi! Java interface, amzijni.dll, must be in your PATH.
Amzi! Java Classes The amzi/ls directory structure, containing the amzi.ls.*
package must be accessible via your CLASSPATH. You can do this by adding amzi/lsapis/java20 to your CLASSPATH
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 47
Tips
Classpath (etc.) settings and inclusions of Amzi! LS classes & all DLLs for VB/C++/Java are different.
Front-end modules developed using Java is greatly depended on the (GUI) Tools you use. E.g. the way JBuilder sees it is different from the
way Eclipse/Visual Safe/NetBean/Command line can recognize it.
Alicia Tang, Dept. of Computer Science, COIT, UNITEN 48
Test this:Amzi! Hello sample for Java
(before you begin to use other LS commands)
To make sure the Amzi! Java interface is ready to use, run the Amzi! Hello sample for Java.
To build the Hello program from Java, first open a 'DOS' window and change to the sample directory containing Hello.java.
To compile it, type: javac Hello.java
This will produce Hello.class which is simply run by typing:
java Hello