Retrieving ERROR messages from SWI-Prolog using Java

When executing prolog programs from java (either using the terminal or JPL) it is important to be able to find out if the prolog program has problems. Such programs may be uploaded by users, as in the case of Gorgias Cloud.

To get the output you need to execute your prolog file from the java runtime. Use the snippet below to get a demo:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestCMD {

  public static void main(String[] args) {
    try {
      String userProjectPath = "Path to the folder of your file, e.g. E:\\";
      String userFilename = "Your file name, e.g. test.pl";
      Process p = Runtime.getRuntime()
          .exec("\"Path to swipl.exe, e.g. C:\\Program Files\\swipl\\bin\\swipl.exe\" -o /dev/null -c " + userProjectPath + userFilename);
      p.waitFor();
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    } catch (InterruptedException e2) {
      e2.printStackTrace();
    }
  }
}

yum: duplicate packages problem

This problem is based on a yum update or yum install failed operation, due to a network error or failure. It happened to me while updating a Centos 7 system. During the update the network was disconnected and the update operation failed. Then after executing:

yum update

I had an error indicating that several packages had duplicates, e.g.:

...
rpm-4.11.3-25.el7.x86_64 is a duplicate with rpm-4.11.3-21.el7.x86_64
...

To cope with this problem you need to remove the new version -that was not correctly installed- from the rpm database, using the command:

rpm -e --justdb --nodeps rpm-4.11.3-25.el7.x86_64

You need to do this for all packages (above run for package rpm-4.11.3-25.el7.x86_64) marked as duplicates in the yum check command. Then, just do a normal update:

yum update

and the system will download the newest versions of all packages.

To resolve this issue I was helped by this thread @ centos forums

Complex Graphical Models using Eclipse GMF technology

Today I am going to discuss about two features of Eclipse GMF that are not well covered by the documentation and that are difficult to locate in forums. For this article I used the Eclipse Modeling Tools Mars 2 Package. After installing the package you must go to Help -> Install Modeling Components and select and install the Graphical Modeling Framework Tooling.

The first feature is to have text areas that can span multiple lines of text.

The second feature is to be able to print my model (as I may want to have it is xps or pdf format). By default GMF allows only for printing your models in png (picture) format.

I will take you step by step to these features definition using a simple example. Assume you have a newspaper and you want to publish articles. The page of the newspaper has one or more articles. Articles have a title, a teaser and text.

1. Create the project and the metamodel

You first need to create a new Modeling project. File-> New-> Project..->Ecore Modeling Project (see the next figure).

ModelingProject

Now define the model as a collection of pages, and the pages are collections of articles.  To do that right click on the newspaper.ecore file and click on “Initialize ecore_diagram diagram file”. Use the aggregation (or composition if you use the aird file) relationship from the toolbox and click and drag from the Newspaper EClass to the Page EClass and for Page to Article. Define the relationships and properties shown in the following diagram.

ecore_model

It is interesting to take a look at the properties of the aggregation. Right click on the line of the articles relationship and select the properties view (see figure below). To indicate that the articles can be from one to many you assign to the property “Lower Bound” the value 1 and to the “Upper Bound” the value -1.

open_properties

Now assume that you want the teaser and text properties of the Article to be able to have multiple lines of text (the first deature we discuss in this article). In order to do that you need first to open the genmodel file. Then you will select the teaser attribute and you set its “Property Multi-line” to the value true. By default it is false, so make sure to do that.

multi-line

Finally select the top level node in the genmodel diagram and check its properties. Set the Compliance Level to 6.0 (if you do not do this then when building the gmfgen file you will get an error):

genmodel-complianceLevel

Now you are ready to initialize the code for editing the model’s elements. Right click on the Newspaper element of the genmodel and select “Generate All”. This will create the ecore Model Code in this project and generate the Edit Code project that you need.

generate_all

2. Generating the Graphical Model

Now you are ready to start working with GMF. Open the GMF Dashboard. Select Window->Show View->Other and type GMF and immediately you will see the GMF Dashboard appear. Select it and you will see it in your eclipse window.

GMFDashboard

The first task is to select the ecore (Domain Model) and genmodel (Domain Gen Model) files:

GMFDashboard1

Next you derive the gmfgraph model by clicking Derive from the Domain Model towards the Graphical Def Model. I named it newspaper1.gmfgraph (see first figure below, in your machine you can give it the name newspaper.gmfgraph, I cannot because I already have one graph file). Then I selected the newspaper element in the Next step of the dialog (see second figure below), and in the final step of the dialog (see third figure) I selected that I want graphical representations for the Page (with the number attribute) and Article (with all its attributes, i.e., name, teaser and text).

GMF-Gen-Graph-dialog-2

GMF-Gen-Graph-dialog-1

GMF-Gen-Graph-dialog-3

Now if everything is OK you can see the following newspaper1.gmfgraph file on eclipse:

GMF-Graph-initial

All elements are in the Canvas. The Canvas has a Figure Gallery (we will see it in detail later), the Node elements that refer to the objects that will be displayed and the Diagram Label elements that refer to the text boxes that will display attributes (bottom part of the figure). Now, in the Figure Gallery we have two main Figure Descriptors, one for the Page (PageFigure) and one for the Article (ArticleFigure). Each of these has a Rectangle with the default Flow Layout and as many Child Access elements as its text boxes (attributes). Note that this is not enough, there are also the relevant Labels defined in the Rectangle. The Diagram Label elements refer to the Child Access elements and the latter refer to the Label elements. In the Label element you can add children like Insets (to space the text from the limits of the rectangle) and  a Basic Font to define text size and style – regular, bold or italics:

GMF-Graph-add-properties-to-label

Now we need to define a new Rectangle in Page where we will be inserting Article objects. Right click on the Rectangle PageFigure and select New Child -> Rectangle:

GMF-Graph-add-rectangle

Name the Rectangle element PageCompartmentFigure. See its properties:

GMF-Graph-name-rectangle

Now you need to add a Border Layout Data child to the PageCompartmentFigure and add to the Rectangle PageFigure a Child Access element with properties:

GMF-Graph-Child-Access-Compartment

Now go to Canvas -> New Child -> Compartment, name it PageCompartment with the following properties:

GMF-Graph-Compartment-properties

Save it and for now you are finished with the gmfgraph file. The next step is to go to the GMF Dashboard and Derive the gmftool model. First you select its name, then you select the newspaper element and finally, the two objects that you are going to be using to draw the model, i.e. the Page and the Article. See these three steps of the wizard:

GMF-Gen-Tool-dialog-1

GMF-Gen-Tool-dialog-2

GMF-Gen-Tool-dialog-3

Now you are ready to Combine all these models (using again the GMF Dashboard) to get the gmfmap model. Follow again the steps of the wizard. Take care to remove Article from the Links compartment in the fifth step. It must look as in the fifth figure below:

GMF-Gen-Map-dialog-1

GMF-Gen-Map-dialog-2

GMF-Gen-Map-dialog-3

GMF-Gen-Map-dialog-4

GMF-Gen-Map-dialog-5

Then you have to take care of the Nodes Page and Article because they need a final touch. Select Article and then click the button Change. Add the first EReference articles to the Children Feature:

GMF-Gen-Map-dialog-5-Article

GMF-Gen-Map-dialog-5-Page

Now you have to edit the newspaper.gmfmap file. It is shown below. See that it contains the ecore, gmfgraph and gmftool models. We are going to focus on the gmfmap part. The Mapping has two elements of type Top Node Reference (one for articles and one for nodes) and a Canvas Mapping. Verify that the

Each Top Node Reference has a Node Mapping. The Node Mapping of Article has a Feature Label Mapping whose properties are displayed in the figure below:

GMF-Map-FeatureLabelMapping

Now you have to add the Feature Label Mapping that are missing with similar properties. Note that the one for Page (number) is not of type EString but of type EInt. I have its properties shown below:

GMF-Map-FeatureLabelMappings

The final part in mapping is to add the compartment of the page.Right click to Node Mapping <Page/Page> -> New Child -> Child Reference and then again right  click to Node Mapping <Page/Page> -> New Child -> Compartment Mapping. You do not have to type anything in their properties, just select the right items. See both their properties in the figures below:

GMF-Map-ChildReference-Properties

GMF-Map-CompartmentMapping-Properties

Now save it, if all has gone well you are ready to press transform from the gmfmap model to the gmfgen model in GMF Dashboard. You finished the process:

GMF-Dashboard-100

Insert Printing Capability

Double click the newspaper.gmfgen file to open it. Now you click its Gen Editor Generator top element. Its properties Diagram File Extention and Domain File Extention show the extentions of the files related to newspaper. The models will have the extention .mewspaper and the graphical models .newspaper_diagram. See also all the files in the models folder of our projet on the left:

GMF-GMFGen-model

Now select the Gen Plugin Newspaper Plugin element and set its property Printing Enabled to true:

GMF-GMFGen-print

Now your models will have the printing capability! Now save and right click on the newspaper.gmfgen file and select to generate the diagram code:

GMF-Gen-generate_code

Add Text Multi-line capability

Normally the Newspaper.diagram project has been created successfully and you can see it in the following figure. It is ready to work with it. However, we want the teaser and the text elements of the articles to be able to span multiple lines of text. To achieve that you need to edit a number (six actually) java files in package newspaper.diagram.edit.parts. The first two files that you need to edit are the ArticleEditPart.java and Article2EditPart.java. You need to find their createContents() method. Initially it is like in the figure:

GMF-diagram_code_edit_initial

You need to locate the lines where the fFigureArticleTeaserFigure.setText(“<…>”) method is called and add the code:

fFigureArticleTeaserFigure.setTextWrap(true);

Do the same for the fFigureArticleTextFigure. Do not forget to set the method to not be automatically generated from now on (generated NOT). You must do that because if for any reason  – e.g. you want to change the fonts of the labels – you re-generate the diagram code you will lose your changes. See the final outcome in the following figure:

GMF-diagram_code_edit_refined

You have to repeat the above process for file Article2EditPart.java.

Now you get the ArticleTeaserEditPart.java, ArticleTeaser2EditPart.java, ArticleTextEditPart.javaArticleText2EditPart.java, and make another change. Take for example the first of them, i.e., ArticleTeaserEditPart.java, and locate its getManager() method:

GMF-diagram_code_text_edit_initial

Now you have to locate the line with code:

setManager(new TextDirectEditManager(this, null, NewspaperEditPartFactory.getTextCellEditorLocator(this)));

and replace null with WrapTextCellEditor.class. This classhas not been imported yet, so hover your mouse over it and select to import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager:

GMF-diagram_code_text_edit_edit_line

Then remember to add generated NOT and save it:

GMF-diagram_code_text_edit_final

Do not worry about the deprecated warning, it is just a warning 🙂

Now you have to do the same for the other three files. After that you are ready to test your model! To do that right click on your Newspaper.diagram project and select Run as -> Eclipse Application.

Create my first newspaper

Create a new project and name it MyNewspaper. Then right click on the project and select New -> Example -> Newspaper Diagram

Let it have the default name and add pages and then articles. To add an element click on it at the palette on the right hand side of the following figure. Then if it is a Page click anywhere in the canvas to insert a page. If it is an Article click inside a page to insert it there. Then add your text:

GMF-diagram_newspaper

Now do you want to print your model? Just right click on the canvas and select File -> Print:

GMF-diagram_print

Enjoy!

Υπολογισμός ακρότατων συνάρτησης δύο μεταβλητών

Όταν θέλω να υπολογίσω τα ακρότατα μιας συνάρτησης δύο μεταβλητών χρειάζεται να κάνω κάποιους υπολογισμούς. Παρακάτω, μια έτοιμη συνάρτηση για το Matlab και το Octave για τον υπολογισμό των ακρότατων και την 3D γραφική παράσταση που τα παρουσιάζει. Ο κώδικας για να δουλέψει χρειάζεται το συμβολικό πακέτο (symbolic package), το οποίο δεν περιλαμβάνεται στις τυπικές εκδόσεις των matlab (symbolic math toolbox) και octave (octsympy).

Εάν θέλετε να μάθετε και τη θεωρία πίσω από τους υπολογισμούς σας παραπέμπω στις σημειώσεις του Καθ. Γεώργιου Ανδρουλάκη.

Λοιπόν έχουμε και λέμε, ο κώδικας είναι ο:

function akrotata(syn,pedia_timwn)
%Ypologizei akrotata synartisis syn me 2 metablhtes x, y. 
%H sinartisi f dinetai ws alfarithmitiko kai proairetika mporeite na dwsete ta pedia timwn gia ta x, y me th morfi [x_min,x_max, y_min, y_max] (metabliti pedia_timwn). 
%An den balete timh sta pedia_timwn tote sto grafima 0a deite tin syn otan ta x,y anikoyn sto [-pi,pi].
syms x y f;
f=sym(syn);
fx=diff(f,x,1);
fy=diff(f,y,1);
[a,b]=solve(fx==0,fy==0);
if nargin < 2
    pedia_timwn = [-pi,pi,-pi,pi];
end
ezsurf(f,pedia_timwn);
if size(a) > 0
    fxx=diff(f,x,2);
    fyy=diff(f,y,2);
    fxy=diff(diff(f,x),y);
    for i=1:size(a)
        vfxx=double(subs(subs(fxx,x,a(i)), y, b(i)));
        vfyy=double(subs(subs(fyy,x,a(i)), y, b(i)));
        vfxy=double(subs(subs(fxy,x,a(i)), y, b(i)));
        vfxy2=vfxy^2;
        vfxx_times_vfyy = vfxx*vfyy;
        if vfxx < 0 && vfyy < 0 && vfxx_times_vfyy > vfxy2
            sprintf('\nYparxei topiko megisto sto shmeio (%f, %f, %f)',double(a(i)), double(b(i)), double(subs(subs(f,x,a(i)), y, b(i))))
        elseif vfxx > 0 && vfyy > 0 && vfxx_times_vfyy > vfxy2
            sprintf('\nYparxei topiko elaxisto sto shmeio (%f, %f, %f)',double(a(i)), double(b(i)), double(subs(subs(f,x,a(i)), y, b(i))))
        elseif vfxx_times_vfyy < vfxy2
            sprintf('\nSagmatiko  shmeio (%f, %f, %f)',double(a(i)), double(b(i)), double(subs(subs(f,x,a(i)), y, b(i))))
        end
    end
else
    disp('Den yparxoun akrotata')
end

Πληκτρολογήστε ή επικολλήστε τον κώδικα σε ένα αρχείο akrotata.m , επιλέξτε τον φάκελο στον οποίο το έχετε αποθηκεύσει και για να το δοκιμάσετε εκτελέστε στο παράθυρο εντολών την παρακάτω εντολή:

>> akrotata('(x^2+4*y^2)*exp(1-x^2-y^2)',[-2,2,-2,2])

Η γραφική παράσταση φαίνεται στο παρακάτω σχήμα:

figure_akrotata

Ενώ η έξοδος της συνάρτησης φαίνεται στην εικόνα:

screenshot_octave_akrotata

 

Debugging a Java application querying Prolog using Eclipse

You normally start a new eclispe java project, let’s name it TestPrologInterface (see Figure 1 below).

To use JPL you need to import the jar file in your project. You right-click on the project’s name and click on Properties (or from the Eclipse menu bar you select Project->Properties). Then on the Libraries tab you click on the Add External JARs… button and select the jpl.jar (see Figure 2 below).

Then, you can add a new class and paste in the code from my previous blog entry (see Figure 3 below).

Subsequently, you will need to setup a run configuration for executing/debugging your project. To do that you select on the Eclipse menu bar the Run->Run Configurations… option, then you right-click on Java application and select New. Then you add the names of the project and main class (see Figure 4 below).

The next thing to do is define the right environment variables. To do that you need a command prompt where you will execute the command:

  "c:\Program Files\swipl\bin\swipl.exe" --dump-runtime-variables=cmd

See the resulting environment variables in Figure 5 below.

Now you are ready to configure the variables on eclipse. In the run configuration go to the Environment tab and then add the variables one by one (click Add and insert the information from the previous screen, from each line the left hand side as name and the right hand side as value). You can see the results in Figure 6 below.

Finally, you run the configuration by clicking on Run (bottom right). The result is shown at the bottom of Figure 7, where you see the eclipse screenshot including the source code.

If you want to export the project to a runnable jar file you right click on the project name and select Export. In the dialog that opens you select Java->Runnable jar file. In the next dialog you define the name of the exported jar and don’t forget to check the Package required libraries into generated JAR if you want the jpl.jar file to be included (see a screenshot in Figure 8).

Now you are ready to distribute your application. Distribute it with the batch file that I used in my previous blog entry.

Figure 1: Create a new project dialog
new_project

Figure 2: Add the JPL JAR file to library
add_external_jars

Figure 3: New class dialog
new_class

Figure 4: Create a new run configuration dialog
new_run_conf

Figure 5: Using the command line to find the SWI-Prolog environment variables
find_variables

Figure 6: The environment tab in the new run configuration dialog
new_run_conf_env

Figure 7: The java class and the execution output
code_and_run_results

Figure 8: The runnable JAR export dialog
runnable_jar

Querying Prolog from Java

This blog entry is for those who want to use Prolog queries from their Java program. I use swi-prolog, a free implementation of the Prolog language.

The SWI-prolog installation includes the java jpl7 package (in the lib installation folder):
http://jpl7.org/JavaApiOverview.jsp

To use it from java you need to setup some system variables before executing your app. Moreover, the java and swi-prolog installations must both be 32 bit or 64bit. For example you can edit a run.bat batch file with the following commands (assuming that swi-prolog is installed in c:/program files/swipl and your app is in the executable <your jar name>.jar file):

  set SWI_PROLOG_PATH=c:\program files\swipl
  set path=%path%;%SWI_PROLOG_PATH%\bin\;%SWI_PROLOG_PATH%\lib\
  swipl.exe --dump-runtime-variables=cmd > plvars.bat
  call plvars.bat
  java -jar <your jar name>.jar

This approach assumes that the jpl.jar library file is included in your jar file, otherwise you must add the jpl.jar to the classpath variable. In the next blog entry I explain how to do that using eclipse.

See an example that adds in the fact father(john,nikos) to the prolog database and then runs the query father(X,nikos):

  
import java.util.Map;
import org.jpl7.*;

public class TestPrologInterface {

  public static void main(String[] args) {
    String s = "assert(father(john,nikos)).";
    Query q = new Query(s);
    // run the query
    if (q.hasNext()) {
      // now I can ask for the father of nikos
      s = "father(X,nikos).";
      q = new Query(s);
      // run the query, repeat while there are more results
      while (q.hasNext()){
        //get a mapping of variables to instantiations:
	Map<String, Term> map = q.next();
	//get the instance of variable X
	String varX = map.get("X").toString();
	//print variable instance
	System.out.println(varX);
      }
    }
  }
}