Initializing help system before first use

In-memory data exchange


Type: Embedding
Rating: 3 (intermediate)
Description:
  • ugiocb.java: Exchanging data between model and host application. Callbacks for exchanging data: sparse data, string indices (requires burglar13.mos)
  • ugiodense.java: Exchanging data between model and host application. Dense data (requires burglar8.mos)
  • ugioscalar.java: Exchanging data between model and host application. Scalars (requires burglar11.mos)
  • ugiosparse.java: Exchanging data between model and host application. Sparse data, string indices (requires burglar9.mos)
  • ugstreamdense.java: Exchanging data between model and host application using Java streams. Dense data (requires burglar8s.mos)
  • ugstreamsparse.java: Exchanging data between model and host application using Java streams. Sparse data, string indices (requires burglar9s.mos)
  • ugstreamdensescrmt.java: Exchanging data between a remote model (started from another model that acts as intermediate) and a Java host application using Java streams. Dense data (requires runburglar8sdc.mos and burglar8sdc.mos)
File(s): ugiocb.java, ugiodense.java, ugioscalar.java, ugiosparse.java, ugstreamdense.java, ugstreamsparse.java, ugstreamdensescrmt.java, burglar13.mos (submodel), burglar11.mos (submodel), burglar8.mos (submodel), burglar8s.mos (submodel), runburglar8sdc.mos (submodel), burglar8sdc.mos (submodel), burglar9.mos (submodel), burglar9s.mos (submodel)

ugiocb.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugiocb.java
   ````````````````
   Exchanging data between model and host application.
   - Callbacks for exchanging data (sparse data, string indices) -
   
   (c) 2009 Fair Isaac Corporation
       author: S. Heipcke, Nov. 2009
********************************************************/

import com.dashoptimization.*;

public class ugiocb
{                                   // Input data
 static final double[] vdata={15,100,90,60,40,15,10, 1};   // VALUE
 static final double[] wdata={ 2, 20,20,30,40,30,60,10};   // WEIGHT
 static final String[] ind={"camera", "necklace", "vase", "picture", 
     "tv", "video", "chest", "brick"};                     // Index names
 static final int datasize=8;

                        // Class to receive solution values
 public static class MySol
 {
  public String ind;                // index name
  public double val;                // solution value
 }
 static MySol[] solution;
 static int solsize;

                /*************************************************/
                /* A class to initialize model data via callback */
                /*************************************************/
 public static class modelInit implements XPRMInitializationFrom, XPRMInitializationTo
 {
  public boolean initializeFrom(XPRMInitializeContext ictx, String label, XPRMTyped type)
  {
   try
   {
    if(label.equals("DATA"))
    {
     ictx.sendControl(ictx.CONTROL_OPENLST);
     for(int i=0;i<datasize;i++)
     {
      ictx.sendControl(ictx.CONTROL_OPENNDX);
       ictx.send(ind[i]);
      ictx.sendControl(ictx.CONTROL_CLOSENDX);
      ictx.sendControl(ictx.CONTROL_OPENLST);
       ictx.send(vdata[i]);
       ictx.send(wdata[i]);
      ictx.sendControl(ictx.CONTROL_CLOSELST);
     }
     ictx.sendControl(ictx.CONTROL_CLOSELST);
     return true;
    }
    else
    {
     System.err.println("Label `"+label+"' not found.");
     return false;
    }
   }
   catch(java.io.IOException e)
   {
    System.err.println("`"+label+"' could not be initialized - "+e);
    return false;
   }
  }

  /**** Retrieving data from Mosel ****/
  public boolean initializeTo(String label, XPRMValue value)
  {
   XPRMArray solarr;
   XPRMSet[] sets;
   int[] indices;
   int ct;

   if(label.equals("SOL"))
   {
    solarr=(XPRMArray)value;
    solsize=solarr.getSize();
    solution = new MySol[solsize];
    for(int i=0;i<solsize;i++) solution[i] = new MySol();

    sets = solarr.getIndexSets();          // Get the indexing sets
    ct=0;
    indices = solarr.getFirstTEIndex();    // Get the first entry of the array
    do
    {
     solution[ct].ind=sets[0].getAsString(indices[0]);
     solution[ct].val=solarr.getAsReal(indices);
     ct++;
    } while(solarr.nextTEIndex(indices));  // Get the next index  
   }
   else System.out.println("Unknown output data item: " + label + "=" + value);
   return true;
  }
 }

                /* Interface objects are static: no need to bind */
 public static modelInit cbinit=new modelInit();

 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;  

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("burglar13.mos");     // Compile & load the model
  mod = mosel.loadModel("burglar13.bim");

                        // File names are passed through execution parameters
  mod.execParams = "DATAFILE='java:ugiocb.cbinit'," + 
                   "SOLFILE='java:ugiocb.cbinit'";

  mod.run();                          // Run the model

  if(mod.getProblemStatus()!=mod.PB_OPTIMAL) 
   System.exit(1);                    // Stop if no solution found

                        // Display solution values obtained from the model
  System.out.println("Objective value: " + mod.getObjectiveValue());
  for(int i=0;i<solsize;i++)
   System.out.println(" take(" + solution[i].ind + "): " + solution[i].val);

  mod.reset();                        // Reset the model
 }
}


ugiodense.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugiodense.java
   ````````````````````
   Exchanging data between model and host application.
   - Dense data -
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, 2006
********************************************************/

import com.dashoptimization.*;

public class ugiodense
{                                     // Input data
 static final double[] vdata={15,100,90,60,40,15,10, 1};   // VALUE
 static final double[] wdata={ 2, 20,20,30,40,30,60,10};   // WEIGHT

                                      // Array to receive solution values
 static double[] solution = new double[8];  

 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("burglar8.mos");      // Compile & load the model
  mod = mosel.loadModel("burglar8.bim");

                        // Associate the Java objects with names in Mosel
  mosel.bind("vdat", vdata);
  mosel.bind("wdat", wdata);
  mosel.bind("sol", solution);
                        // File names are passed through execution parameters
  mod.execParams =
   "VDATA='noindex,vdat',WDATA='noindex,wdat',SOL='noindex,sol'";

  mod.run();                          // Run the model

  if(mod.getProblemStatus()!=mod.PB_OPTIMAL) 
   System.exit(1);                    // Stop if no solution found

                        // Display solution values obtained from the model
  System.out.println("Objective value: " + mod.getObjectiveValue());
  for(int i=0;i<8;i++)
   System.out.println(" take(" + (i+1) + "): " + solution[i]);

  mod.reset();                        // Reset the model
 }
}


ugioscalar.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugioscalar.java
   ````````````````````
   Exchanging data between model and host application.
   - Scalars -
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, Mar. 2008
********************************************************/

import com.dashoptimization.*;

public class ugioscalar
{
 public static class MyData            // Scalars for data in/output
 {
  public int wmax;
  public int numitem;
  public double objval;
 }
 
 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;
  MyData data=new MyData();

  data.wmax=100;

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("burglar11.mos");     // Compile & load the model
  mod = mosel.loadModel("burglar11.bim");

                        // Associate the Java object with a name in Mosel
  mosel.bind("data", data);
                        // File names are passed through execution parameters
  mod.execParams =
   "WMAX='data(wmax)',NUM='data(numitem)',SOLVAL='data(objval)'";

  mod.run();                          // Run the model

  if(mod.getProblemStatus()!=mod.PB_OPTIMAL) 
   System.exit(1);                    // Stop if no solution found

                        // Display solution values obtained from the model
  System.out.println("Objective value: " + data.objval);
  System.out.println("Total number of items: " + data.numitem);

  mod.reset();                        // Reset the model
 }
}


ugiosparse.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugiosparse.java
   ````````````````````
   Exchanging data between model and host application.
   - Sparse data (string indices) -
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, 2006
********************************************************/

import com.dashoptimization.*;

public class ugiosparse
{
                        // Class to store initial values for array 'data'
 public static class MyData
 {
  public String ind;                // index name
  public double val,wght;           // value and weight data entries
  MyData(String i, double v, double w)
  { ind=i; val=v; wght=w; }
 }
                        // Class to receive solution values
 public static class MySol
 {
  public String ind;                // index name
  public double val;                // solution value
 }

 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;
  MyData data[]={new MyData("camera",15,2), new MyData("necklace",100,20), 
                 new MyData("vase",90,20), new MyData("picture",60,30), 
		 new MyData("tv",40,40), new MyData("video",15,30), 
                 new MyData("chest",10,60), new MyData("brick",1,10)};
  MySol[] solution=new MySol[8];
  
  for(int i=0;i<8;i++) solution[i] = new MySol();

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("burglar9.mos");      // Compile & load the model
  mod = mosel.loadModel("burglar9.bim");

                        // Associate the Java objects with names in Mosel
  mosel.bind("dt", data);
  mosel.bind("sol", solution);
                        // File names are passed through execution parameters
  mod.execParams = "DATA='dt(ind,val,wght)',SOL='sol(ind,val)'";

  mod.run();                          // Run the model

  if(mod.getProblemStatus()!=mod.PB_OPTIMAL) 
   System.exit(1);                    // Stop if no solution found

                        // Display solution values obtained from the model
  System.out.println("Objective value: " + mod.getObjectiveValue());
  for(int i=0;i<8;i++)
   System.out.println(" take(" + solution[i].ind + "): " + solution[i].val);

  mod.reset();                        // Reset the model
 }
}


ugstreamdense.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugstreamdense.java
   ```````````````````````
   Exchanging data between model and host application
   using Java streams.
   - Dense data -
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, July 2008
********************************************************/

import java.io.*;
import java.nio.*;
import com.dashoptimization.*;

public class ugstreamdense
{                                     // Input data
 static final double[] vdata={15,100,90,60,40,15,10, 1};   // VALUE
 static final double[] wdata={ 2, 20,20,30,40,30,60,10};   // WEIGHT

                                      // Array to receive solution values
 static final int SOLSIZE=8;
 static double[] solution = new double[SOLSIZE];  

 // A stream to send the 'MyData' array in a form suitable for the 'raw:' driver
 public static class MyInitStream extends InputStream
 {
  int ndx;
  double mydata[];

  MyInitStream(double data[])
  {
   ndx=0;
   mydata=data;
  }

  public int read(byte[] b)
  {
   ByteBuffer buf;
   byte [] bs;

   if(ndx<mydata.length)
   {
                        // Handle the buffer as a ByteBuffer
    buf=ByteBuffer.wrap(b);
                        // Set the byte ordering for binary data
    buf.order(ByteOrder.nativeOrder());                  
    buf.rewind();       // Start from the beginning
                        // Put the data values (8 bytes each)
    buf.putDouble(mydata[ndx]);
                        // Increase counter for next call
    ndx++;
    return buf.position();
   }
   else
    return 0;
  }

  // Other methods are not used by Mosel
  public int read(byte[] b,int off,int len) { return 0; }
  public int read() { return 0; }
  public void close() {}
 }

 // A stream to retrieve the 'MySol' array in a form suitable for the 'raw:' driver
 public static class MyOutStream extends OutputStream
 {
  int ndx;
  double mysol[];

  MyOutStream(double data[])
  {
   ndx=0;
   mysol=data;
  }

  public void write(byte[] b)
  {
   ByteBuffer buf;
   byte[] bs = new byte[16];

                        // Handle the buffer as a ByteBuffer
   buf=ByteBuffer.wrap(b);
                        // Set the byte ordering for binary data
   buf.order(ByteOrder.nativeOrder());            
   buf.rewind();        // Start from the beginning

   try
   {
    while(buf.hasRemaining())
    {                   // Get the value (8 bytes)
     mysol[ndx] = buf.getDouble();
     ndx++;             // Increase counter for next call    
    }
   }
   catch(Exception e)
   {
    System.err.println(e.getMessage());
    System.exit(1);   
   } 
  }

  // Other methods are not used by Mosel
  public void write(byte[] b,int off,int len) {}
  public void write(int i) {}
  public void close() {}
 }

 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;
  MyInitStream myvdatastream=new MyInitStream(vdata);
  MyInitStream mywdatastream=new MyInitStream(wdata);
  MyOutStream mysolstream=new MyOutStream(solution);

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("burglar8s.mos");     // Compile & load the model
  mod = mosel.loadModel("burglar8s.bim");

                        // Associate the Java objects with names in Mosel
  mosel.bind("vdat", myvdatastream);
  mosel.bind("wdat", mywdatastream);
  mosel.bind("sol", mysolstream);
                        // File names are passed through execution parameters
  mod.execParams =
   "VDATA='vdat',WDATA='wdat',SOL='sol'";

  mod.run();                          // Run the model

  if(mod.getProblemStatus()!=mod.PB_OPTIMAL) 
   System.exit(1);                    // Stop if no solution found

                        // Display solution values obtained from the model
  System.out.println("Objective value: " + mod.getObjectiveValue());
  for(int i=0;i<SOLSIZE;i++)
   System.out.println(" take(" + (i+1) + "): " + solution[i]);

  mod.reset();                        // Reset the model
 }
}


ugstreamsparse.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugstreamsparse.java
   ````````````````````````
   Exchanging data between model and host application
   using Java streams.
   - Sparse data (string indices) -
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, July 2008
********************************************************/

import java.io.*;
import java.nio.*;
import com.dashoptimization.*;

public class ugstreamsparse
{
                        // Class to store initial values for array 'data'
 public static class MyData
 {
  public String ind;                // index name
  public double val,wght;           // value and weight data entries
  MyData(String i, double v, double w)
  { ind=i; val=v; wght=w; }
 }
                        // Class to receive solution values
 public static class MySol
 {
  public String ind;                // index name
  public double val;                // solution value
 }

 // A stream to send the 'MyData' array in a form suitable for the 'raw:' driver
 public static class MyInitStream extends InputStream
 {
  int ndx;
  MyData mydata[];

  MyInitStream(MyData data[])
  {
   ndx=0;
   mydata=data;
  }

  public int read(byte[] b)
  {
   ByteBuffer buf;
   byte [] bs;

   if(ndx<mydata.length)
   {
                        // Handle the buffer as a ByteBuffer
    buf=ByteBuffer.wrap(b);
                        // Set the byte ordering for binary data
    buf.order(ByteOrder.nativeOrder());                  
    buf.rewind();       // Start from the beginning
                        // Convert the string into a byte array
    bs=mydata[ndx].ind.getBytes();                 
    buf.put(bs);        // Copy the array into the ByteBuffer
              // Strings are of fixed size (Mosel default 16 characters): 
              // we padd with 0
    for(int i=bs.length;i<16;i++)
     buf.put((byte)0);
                        // Put the data values (8 bytes each)
    buf.putDouble(mydata[ndx].val);
    buf.putDouble(mydata[ndx].wght);
                        // Increase counter for next call
    ndx++;
    return buf.position();
   }
   else
    return 0;
  }

  // Other methods are not used by Mosel
  public int read(byte[] b,int off,int len) { return 0; }
  public int read() { return 0; }
  public void close() {}
 }

 // A stream to retrieve the 'MySol' array in a form suitable for the 'raw:' driver
 public static class MyOutStream extends OutputStream
 {
  int ndx;
  MySol mysol[];

  MyOutStream(MySol data[])
  {
   ndx=0;
   mysol=data;
  }

  public void write(byte[] b)
  {
   ByteBuffer buf;
   byte[] bs = new byte[16];

                        // Handle the buffer as a ByteBuffer
   buf=ByteBuffer.wrap(b);
                        // Set the byte ordering for binary data
   buf.order(ByteOrder.nativeOrder());            
   buf.rewind();        // Start from the beginning

   try
   {
    while(buf.hasRemaining())
    {            
     buf.get(bs);       // Copy the array into the ByteBuffer
                        // Convert the string into a byte array
     mysol[ndx].ind = new String(bs);
                        // Get the value (8 bytes)
     mysol[ndx].val = buf.getDouble();
     ndx++;             // Increase counter for next call    
    }
   }
   catch(Exception e)
   {
    System.err.println(e.getMessage());
    System.exit(1);   
   } 
  }

  // Other methods are not used by Mosel
  public void write(byte[] b,int off,int len) {}
  public void write(int i) {}
  public void close() {}
 }

 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;
  MyData data[]={new MyData("camera",15,2), new MyData("necklace",100,20), 
                 new MyData("vase",90,20), new MyData("picture",60,30), 
                 new MyData("tv",40,40), new MyData("video",15,30), 
                 new MyData("chest",10,60), new MyData("brick",1,10)};
  MyInitStream mydatastream=new MyInitStream(data);
  MySol[] solution=new MySol[8];
  MyOutStream mysolstream=new MyOutStream(solution);
  
  for(int i=0;i<8;i++) solution[i] = new MySol();

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("burglar9s.mos");     // Compile & load the model
  mod = mosel.loadModel("burglar9s.bim");

                        // Associate the Java objects with names in Mosel
  mosel.bind("dt", mydatastream);
  mosel.bind("sol", mysolstream);
                        // File names are passed through execution parameters
  mod.execParams = "DATA='dt',SOL='sol'";

  mod.run();                          // Run the model

  if(mod.getProblemStatus()!=mod.PB_OPTIMAL) 
   System.exit(1);                    // Stop if no solution found

                        // Display solution values obtained from the model
  System.out.println("Objective value: " + mod.getObjectiveValue());
  for(int i=0;i<8;i++)
   System.out.println(" take(" + solution[i].ind + "): " + solution[i].val);

  mod.reset();                        // Reset the model
 }
}


ugstreamdensescrmt.java
/*******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugstreamdensescrmt.java
   ````````````````````````````
   Exchanging data between model and host application
   using Java streams.
   - Dense data array and scalar data -
   
   (c) 2022 Fair Isaac Corporation
       author: S. Heipcke, Jan 2022
********************************************************/

import java.io.*;
import java.nio.*;
import com.dashoptimization.*;

public class ugstreamdensescrmt
{                                     // Input data
 static final double[] vdata={15,100,90,60,40,15,10, 1};   // VALUE
 static final double[] wdata={ 2, 20,20,30,40,30,60,10};   // WEIGHT

 public static class MyData            // Scalars for data in/output
 {
  public int wmax;
  public double objval;
 }
                                      // Array to receive solution values
 static final int SOLSIZE=8;
 static double[] solution = new double[SOLSIZE];  

 // A stream to send the 'MyData' array in a form suitable for the 'raw:' driver
 public static class MyInitStream extends InputStream
 {
  int ndx;
  double mydata[];

  MyInitStream(double data[])
  {
   ndx=0;
   mydata=data;
  }

  public int read(byte[] b)
  {
   ByteBuffer buf;
   byte [] bs;

   if(ndx<mydata.length)
   {
                        // Handle the buffer as a ByteBuffer
    buf=ByteBuffer.wrap(b);
                        // Set the byte ordering for binary data
    buf.order(ByteOrder.nativeOrder());                  
    buf.rewind();       // Start from the beginning
                        // Put the data values (8 bytes each)
    buf.putDouble(mydata[ndx]);
                        // Increase counter for next call
    ndx++;
    return buf.position();
   }
   else
    return 0;
  }

  // Other methods are not used by Mosel
  public int read(byte[] b,int off,int len) { return 0; }
  public int read() { return 0; }
  public void close() {}
 }

 // A stream to retrieve the 'MySol' array in a form suitable for the 'raw:' driver
 public static class MyOutStream extends OutputStream
 {
  int ndx;
  double mysol[];

  MyOutStream(double data[])
  {
   ndx=0;
   mysol=data;
  }

  public void write(byte[] b)
  {
   ByteBuffer buf;
   byte[] bs = new byte[16];

                        // Handle the buffer as a ByteBuffer
   buf=ByteBuffer.wrap(b);
                        // Set the byte ordering for binary data
   buf.order(ByteOrder.nativeOrder());            
   buf.rewind();        // Start from the beginning

   try
   {
    while(buf.hasRemaining())
    {                   // Get the value (8 bytes)
     mysol[ndx] = buf.getDouble();
     ndx++;             // Increase counter for next call    
    }
   }
   catch(Exception e)
   {
    System.err.println(e.getMessage());
    System.exit(1);   
   } 
  }

  // Other methods are not used by Mosel
  public void write(byte[] b,int off,int len) {}
  public void write(int i) {}
  public void close() {}
 }

 public static void main(String[] args) throws Exception
 {
  XPRM mosel;
  XPRMModel mod;
  MyInitStream myvdatastream=new MyInitStream(vdata);
  MyInitStream mywdatastream=new MyInitStream(wdata);
  MyOutStream mysolstream=new MyOutStream(solution);
  MyData data=new MyData();

  data.wmax=102;

  mosel = new XPRM();                 // Initialize Mosel

  mosel.compile("runburglar8sdc.mos");   // Compile & load the model
  mod = mosel.loadModel("runburglar8sdc.bim");

                        // Associate the Java objects with names in Mosel
  mosel.bind("vdat", myvdatastream);
  mosel.bind("wdat", mywdatastream);
  mosel.bind("sol", mysolstream);
  mosel.bind("data", data);
                        // File names are passed through execution parameters
  mod.execParams =
   "VDATA='java:vdat',WDATA='java:wdat',SOL='java:sol',WMAX='data(wmax)',OBJVAL='data(objval)'";

  mod.run();                          // Run the model

  if(mod.getExecStatus()!=mod.RT_OK || mod.getExitCode()!=0) {
   System.out.println("(Sub)model execution error");
   System.exit(1);                    // Stop if an error has occurred
  }
                        // Display solution values obtained from the model
  System.out.println("Objective value: " + data.objval);
  for(int i=0;i<SOLSIZE;i++)
   System.out.println(" take(" + (i+1) + "): " + solution[i]);

  mod.reset();                        // Reset the model
 }
}


burglar13.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar13.mos
   ``````````````````
   Same as burglar2.mos, with input from/output to
   calling application.

   *** Not intended to be run standalone - run from ugiocb.*  ***
   
   (c) 2009 Fair Isaac Corporation
       author: S. Heipcke, Nov. 2009
*******************************************************!)

model Burglar13
 uses "mmxprs"
 
 parameters
  DATAFILE = ''                    ! Location of input data
  SOLFILE = ''                     ! Location for solution data output
  WTMAX = 102                      ! Maximum weight allowed
 end-parameters

 declarations
  ITEMS: set of string             ! Index set for items  
  VALUE: array(ITEMS) of real      ! Value of items
  WEIGHT: array(ITEMS) of real     ! Weight of items
  soltake: array(ITEMS) of real    ! Solution values
 end-declarations

 initializations from DATAFILE
  [VALUE,WEIGHT] as "DATA"
 end-initializations

 declarations
  take: array(ITEMS) of mpvar      ! 1 if we take item i; 0 otherwise
 end-declarations

! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 maximize(MaxVal)                  ! Solve the MIP-problem

! Output solution to calling application
 forall(i in ITEMS) soltake(i):= getsol(take(i))

 initializations to SOLFILE
  soltake as "SOL"
 end-initializations

end-model

burglar11.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar11.mos
   ``````````````````
   Same as burglari.mos, with some scalars 
   input from/output to calling application.

   *** Not intended to be run standalone - run from ugioscalar.*  ***
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, Mar. 2008, rev. Apr. 2013
*******************************************************!)

model Burglar11
 uses "mmxprs"
 
 parameters
  NUM = ''                         ! Location for no. of items output
  SOLVAL = ''                      ! Location for objective value output
  WMAX = ''                        ! Maximum weight allowed
  IODRV = 'jraw:'
 end-parameters

 declarations
  WTMAX: integer                   ! Maximum weight allowed
  ITEMS = {"camera", "necklace", "vase", "picture", "tv", "video", 
           "chest", "brick"}     ! Index set for items
  VALUE: array(ITEMS) of real      ! Value of items
  WEIGHT: array(ITEMS) of real     ! Weight of items
  soltake: array(ITEMS) of real    ! Solution values
 end-declarations

 VALUE :: (["camera", "necklace", "vase", "picture", "tv", "video", 
            "chest", "brick"])[15,100,90,60,40,15,10,1]
 WEIGHT:: (["camera", "necklace", "vase", "picture", "tv", "video", 
            "chest", "brick"])[2,20,20,30,40,30,60,10]

 initializations from IODRV
  WTMAX as WMAX
 end-initializations

 declarations
  take: array(ITEMS) of mpvar      ! 1 if we take item i; 0 otherwise
 end-declarations

! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 maximize(MaxVal)                  ! Solve the MIP-problem

! Print out the solution
 writeln("Solution:")
 forall(i in ITEMS)  writeln(" take(", i, "): ", getsol(take(i)))

! Output solution to calling application
 initializations to IODRV
  evaluation of getobjval as SOLVAL
  evaluation of round(sum(i in ITEMS) getsol(take(i))) as NUM
 end-initializations

end-model

burglar8.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar8.mos
   `````````````````
   Model as in burglar.mos, with data input/ouput
   from/to calling application.

   *** Not intended to be run standalone - run from ugiodense.java ***
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, Mar. 2006
*******************************************************!)

model Burglar8
 uses "mmxprs"

 parameters
  VDATA = ''; WDATA = ''         ! Location of input data
  SOL = ''                       ! Location for solution data output
  WTMAX = 102                    ! Maximum weight allowed
 end-parameters
  
 declarations
  ITEMS = 1..8                   ! Index range for items
  
  VALUE: array(ITEMS) of real    ! Value of items
  WEIGHT: array(ITEMS) of real   ! Weight of items
  
  take: array(ITEMS) of mpvar    ! 1 if we take item i; 0 otherwise
  soltake: array(ITEMS) of real  ! Solution values
 end-declarations

 initializations from 'jraw:'
  VALUE as VDATA  WEIGHT as WDATA
 end-initializations

! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 maximize(MaxVal)                 ! Solve the MIP-problem

! Output solution to calling application
 forall(i in ITEMS) soltake(i):= getsol(take(i))

 initializations to 'jraw:'
  soltake as SOL
 end-initializations

end-model

burglar8s.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar8s.mos
   ``````````````````
   Model as in burglar.mos, with data input/ouput
   from/to calling application through Java streams.

   *** Not intended to be run standalone - run from ugstreamdense.java ***
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, July 2008
*******************************************************!)

model Burglar8
 uses "mmxprs"

 parameters
  VDATA = ''; WDATA = ''         ! Location of input data
  SOL = ''                       ! Location for solution data output
  WTMAX = 102                    ! Maximum weight allowed
 end-parameters
  
 declarations
  ITEMS = 1..8                   ! Index range for items
  
  VALUE: array(ITEMS) of real    ! Value of items
  WEIGHT: array(ITEMS) of real   ! Weight of items
  
  take: array(ITEMS) of mpvar    ! 1 if we take item i; 0 otherwise
  soltake: array(ITEMS) of real  ! Solution values
 end-declarations

 initializations from 'raw:noalign,noindex'
  VALUE as "java:"+VDATA  WEIGHT as "java:"+WDATA
 end-initializations

! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 maximize(MaxVal)                 ! Solve the MIP-problem

! Output solution to calling application
 forall(i in ITEMS) soltake(i):= getsol(take(i))

 initializations to 'raw:noalign,noindex'
  soltake as "java:"+SOL
 end-initializations

end-model

runburglar8sdc.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file runburglar8sdc.mos 
   ```````````````````````
   Distributed computing: 
   Running a model on a remote Mosel instance.
   - Data exchange with Java host program 
   - via the java: and jraw: I/O drivers  

   (c) 2022 Fair Isaac Corporation
       author: S. Heipcke, Jan. 2022
*******************************************************!)

model "Run model burglar8sdc remotely"
 uses "mmjobs", "mmsystem"

 parameters
  VDATA = ''; WDATA = ''         ! Location of input data
  SOL = ''                       ! Location for solution data output
  OBJVAL = ''                    ! Location for objective value output
  WMAX = ''                      ! Location of maximum weight allowed
 end-parameters

 declarations
  moselInst: Mosel
  modBurg: Model
  event: Event
  wmax: integer
  objval: real
 end-declarations
                               ! Compile submodel locally
 if compile("burglar8sdc.mos")<>0 then exit(1); end-if

                               ! Start a remote Mosel instance: 
                               ! "" means the node running this model
 if connect(moselInst, "")<>0 then exit(2); end-if

                               ! Load bim file into remote instance
 load(moselInst, modBurg, "rmt:burglar8sdc.bim")

                               ! Disable submodel output
! setdefstream(modBurg,"","null:","null:")

! Retrieve a scalar value from Java memory via 'jraw'
 initializations from "jraw:"
  wmax as WMAX
 end-initializations

                               ! Start execution and
 run(modBurg, "VDATA='rmt:"+VDATA+"',WDATA='rmt:"+WDATA+"',SOL='rmt:"+SOL+"',"+
  "WTMAX="+wmax+",OBJVAL='bin:rmt:shmem:objval'")
 wait                          ! ... wait for an event
 if getclass(getnextevent) <> EVENT_END then
  writeln("Problem with submodel run")
  exit(1)
 else
  writeln("Submodel run terminated.")

 ! Retrieve a scalar value from the submodel and copy it to Java memory
  initializations from "bin:shmem:objval"
   objval
  end-initializations

  initializations to "jraw:"
   objval as OBJVAL
  end-initializations
 end-if 

 unload(modBurg)              ! Unload the submodel
end-model 

burglar8sdc.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar8sdc.mos
   ````````````````````
   Model as in burglar.mos, with data input/ouput
   from/to calling application through Java streams.

   *** Not intended to be run standalone - run from ugstreamdensescrmt.java ***
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, July 2008
*******************************************************!)

model Burglar8
 uses "mmxprs"

 parameters
  VDATA = ''; WDATA = ''         ! Location of input data
  SOL = ''                       ! Location for solution data output
  OBJVAL = ''                    ! Location for objective value output
  WTMAX = 10                     ! Maximum weight allowed
 end-parameters
  
 declarations
  ITEMS = 1..8                   ! Index range for items
  
  VALUE: array(ITEMS) of real    ! Value of items
  WEIGHT: array(ITEMS) of real   ! Weight of items
  
  take: array(ITEMS) of mpvar    ! 1 if we take item i; 0 otherwise
  soltake: array(ITEMS) of real  ! Solution values
 end-declarations

 initializations from 'raw:noalign,noindex'
  VALUE as VDATA  WEIGHT as WDATA
 end-initializations


! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 setparam("XPRS_VERBOSE",true)
 maximize(MaxVal)                 ! Solve the MIP-problem

! Output solution to calling application
 forall(i in ITEMS) soltake(i):= getsol(take(i))

 initializations to 'raw:noalign,noindex'
  soltake as SOL
 end-initializations

 initializations to OBJVAL
  evaluation of getobjval as 'objval'
 end-initializations

end-model

burglar9.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar9.mos
   `````````````````
   Same as burglar2.mos, with input from/output to
   calling application.

   *** Not intended to be run standalone - run from ugiosparse.java ***
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, Mar. 2006
*******************************************************!)

model Burglar9
 uses "mmxprs"
 
 parameters
  DATA = ''                        ! Location of input data
  SOL = ''                         ! Location for solution data output
  WTMAX = 102                      ! Maximum weight allowed
 end-parameters

 declarations
  ITEMS: set of string             ! Index set for items  
  VALUE: array(ITEMS) of real      ! Value of items
  WEIGHT: array(ITEMS) of real     ! Weight of items
  soltake: array(ITEMS) of real    ! Solution values
 end-declarations

 initializations from 'jraw:'
  [VALUE,WEIGHT] as DATA
 end-initializations

 declarations
  take: array(ITEMS) of mpvar      ! 1 if we take item i; 0 otherwise
 end-declarations

! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 maximize(MaxVal)                  ! Solve the MIP-problem

! Output solution to calling application
 forall(i in ITEMS) soltake(i):= getsol(take(i))

 initializations to 'jraw:'
  soltake as SOL
 end-initializations

end-model

burglar9s.mos
(!******************************************************
   Mosel User Guide Example Problems
   ================================= 

   file burglar9s.mos
   ``````````````````
   Same as burglar2.mos, with input from/output to
   calling application through Java streams.

   *** Not intended to be run standalone - run from ugstreamsparse.java ***
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, July 2008
*******************************************************!)

model Burglar9s
 uses "mmxprs"
 
 parameters
  DATA = ''                        ! Name of input data stream
  SOL = ''                         ! Name of solution data output stream
  WTMAX = 102                      ! Maximum weight allowed
 end-parameters

 declarations
  ITEMS: set of string             ! Index set for items  
  VALUE: array(ITEMS) of real      ! Value of items
  WEIGHT: array(ITEMS) of real     ! Weight of items
  soltake: array(ITEMS) of real    ! Solution values
 end-declarations

 initializations from 'raw:noalign'
  [VALUE,WEIGHT] as "java:"+DATA
 end-initializations

 declarations
  take: array(ITEMS) of mpvar      ! 1 if we take item i; 0 otherwise
 end-declarations

! Objective: maximize total value
 MaxVal:= sum(i in ITEMS) VALUE(i)*take(i) 

! Weight restriction
 sum(i in ITEMS) WEIGHT(i)*take(i) <= WTMAX

! All variables are 0/1
 forall(i in ITEMS) take(i) is_binary  

 maximize(MaxVal)                  ! Solve the MIP-problem

! Output solution to calling application
 forall(i in ITEMS) soltake(i):= getsol(take(i))

 initializations to 'raw:noalign'
  soltake as "java:"+SOL
 end-initializations

end-model

© 2001-2022 Fair Isaac Corporation. All rights reserved. This documentation is the property of Fair Isaac Corporation (“FICO”). Receipt or possession of this documentation does not convey rights to disclose, reproduce, make derivative works, use, or allow others to use it except solely for internal evaluation purposes to determine whether to purchase a license to the software described in this documentation, or as otherwise set forth in a written software license agreement between you and FICO (or a FICO affiliate). Use of this documentation and the software described in it must conform strictly to the foregoing permitted uses, and no other use is permitted.