Tuesday, February 28, 2017

example15_get_input.zubr

An optimizer created by zubr communicates with the outer world via two methods:
  • getInput
  • execute
What is an optimizer? From our point of view the optimizer runs in a loop:

    while (loopIsRunning):
        getInput(...)
        ....
        execute(...)


In this example we tell zubr that the method getInput will be provided by us. The other one, "execute" will be a default one. We will provide an implementation of getInput which will enable the user to set one input variable at one of two values it may have.

// This is an example zubr specification.

package optimizer;

%option class MyOptimizer    // here we modify the target class name, it is optional
%option getinput own    // with this option we tell zubr we will provide our own implementation of the method getInput

// We can import Java packages here.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Dimension;


In the middle section we provide the Perkun code declaring one input variable, alpha, which may have one of the two values - FALSE or TRUE.

// here we put the Perkun code (values and variables)

values
{
    value FALSE, TRUE;
}

variables
{
    input variable alpha:{FALSE, TRUE};   
}


The method getInput looks as follows:
// this is the implementation of the method we promised to provide:
protected void getInput(Map<Variable, Value> m) {

    Object[] possibilities = {"FALSE", "TRUE"};
   
    String n = (String)JOptionPane.showInputDialog(frame, "Alpha=?", "Continue?", JOptionPane.PLAIN_MESSAGE,
         null, possibilities, "FALSE");
      if (n == null) {
        loopIsRunning = false; // here we tell the optimizer we want to break the loop
      }
      else
      if (n == "FALSE") {
         m.put(mapNameToVariable.get("alpha"), Value.FALSE);
      }
      else
      if (n == "TRUE") {
         m.put(mapNameToVariable.get("alpha"), Value.TRUE);
     
}

It is filling the map Map<Variable,Value> named "m" with values for all input variables, depending on the decision made by the user. We are free to use the map Map<String,Variable> named "mapNameToVariable" to access the variable "alpha". The Value is an enum created by zubr.

In more complex cases we will possibly have more input variables, then we will provide a different dialog.

When we run this example with zubr we will obtain a Java code:

zubr example15_get_input.zubr > MyOptimizer.java

After compiling and running it a dialog will be shown to set the variable "alpha" either with FALSE or TRUE. After you enter the alpha value twice (and press OK) an error will occur. Moreover - this error will not be reported, and we would like to have a Swing dialog shown when it happens. How to achieve this? We must provide an important error handling method, which will be discussed in the next example. The default version of this method does nothing, and the error should be handled otherwise.

No comments:

Post a Comment