Initializing help system before first use

Basic embedding tasks


Type: Embedding
Rating: 2 (easy-medium)
Description:
  • ugcomptmp.cs: Compiling a model into a BIM file saved in Mosel's temporary directory (requires burglar2.mos, burglar.dat)
  • ugrun.cs: Compiling a model into a BIM file, then load and run it (requires burglar2.bim, burglar.dat)
  • ugdefstream.cs: Redirecting the model output (requires burglar2.mos, burglar.dat)
  • ugarray.cs: Accessing modeling objects: sparse arrays (requires transport.mos, transprt.dat)
  • ugcb.cs: Retrieve model output via a callback into a custom TextWriter (requires burglar2.mos, burglar.dat)
  • ugcb2.cs: Retrieve model output via a callback into a string (requires burglar2.mos, burglar.dat)
  • ugparam.cs: Passing parameters to a Mosel model (requires prime.mos)
  • ugsol.java: Accessing modeling objects and solution information (requires burglar3.mos, burglar.dat)
File(s): ugcomptmp.cs, ugrun.cs, ugdefstream.cs, ugarray.cs, ugcb.cs, ugcb2.cs, ugsol.cs, ugparam.cs, burglar2.mos, transport.mos, prime.mos, burglar3.mos
Data file(s): burglar.dat, transprt.dat


ugcomptmp.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugcomptmp.cs
   `````````````````
   Compiling a model into a BIM file saved in Mosel's
   temporary directory, then load and run it.
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Apr. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugcomptmp.cs {

  public class ugcomptmp {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Compile the Mosel model, save the BIM file in Mosel's temp. dir.
      mosel.Compile("", "burglar2.mos", "tmp:burglar2.bim");

      // Load the BIM file
      XPRMModel model = mosel.LoadModel("tmp:burglar2.bim");

      // Run the model
      model.Run();
    }
  }

}

ugrun.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugrun.cs
   `````````````
   Compile+load, then run a model.
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Apr. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugrun.cs {

  public class ugrun {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Compile and load a model 
      XPRMModel model = mosel.CompileAndLoad("burglar2.mos");

      // Run the model
      model.Run();

      Console.WriteLine("`burglar2' returned: " + model.Result);
    }
  }

}

ugdefstream.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugdefstream.cs
   ```````````````````
   Redirecting model output.
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Apr. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugdefstream.cs {

  public class ugdefstream {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Compile and load the Mosel model 
      XPRMModel model = mosel.CompileAndLoad("burglar2.mos");

 // Redirect the model output. Uncomment one of the following lines:
      // Disable model output
 //     model.SetDefaultStream(XPRMStreamType.F_OUTPUT, "null:");
      // Double model output (file+stdout)
      model.SetDefaultStream(XPRMStreamType.F_OUTPUT, "tee:burglog.txt&");

      // Run the model
      model.Run();

      Console.WriteLine("'burglar2' returned: {0}", model.Result);
    }
  }

}

ugarray.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugarray.cs
   ```````````````
   Accessing modeling objects (sparse arrays).
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Apr. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugarray.cs {

  public class ugarray {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      XPRMArray varr;
      XPRMSet[] sets;
      XPRMValue[] vindex;
      int dim;

      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Compile and load a model 
      XPRMModel model = mosel.CompileAndLoad("transport.mos");

      // Run the model
      model.Run();

      // Get model object 'flow', it must be an array
      varr=(XPRMArray)model.FindIdentifier("flow");
      dim = varr.Dim;           // Get the number of dimensions of the array
      sets = varr.IndexSets;    // Get the indexing sets

      // Enumerate over the true entries
      foreach(int[] indices in varr.TEIndices)
      {
        // Get the values for this index
        vindex = varr.DereferenceIndex(indices);
        Console.Write("flow(");
        for(int i=0;i<dim-1;i++)
          Console.Write(vindex[i] + ",");
        Console.Write(vindex[dim-1] + "), ");

        // Alternative printing method:
        // Console.Write("flow" + varr.IndexToString(indices) + ", ");
      }  
      Console.WriteLine();

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

ugcb.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugcb.cs
   ````````````
   Retrieve model output via callback-style functionality.
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, J.Farmer, Mar. 2013 
********************************************************/


using System;
using System.IO;
using System.Text;
using Mosel;


namespace ugcb.cs {

  public class ugcb {
    
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Associate .NET object with a name in Mosel
      mosel.Bind("mycb", new MyOut());

      // Redirect error stream to stdout
      mosel.SetDefaultStream(XPRMStreamType.F_ERROR, Console.Out);

      // Compile and load the Mosel model
      XPRMModel model = mosel.CompileAndLoad("burglar2.mos");
      
      // Redirect the model's output to a custom TextWriter
      MyOut modelOut = new MyOut();
      model.SetDefaultStream(XPRMStreamType.F_OUTPUT_LINEBUF, modelOut);

      // Alternative:
      // Redirect the model's output to our printing function 'cbmsg'
      model.SetDefaultStream(XPRMStreamType.F_OUTPUT_LINEBUF, "dotnet:mycb");

      // Run the model
      model.Run();

    }
  }

  public class MyOut: TextWriter
  {
   private bool atStartOfLine = true;
   public override void Write(char b)
   {
     if (atStartOfLine) {
      Console.Write("Mosel: ");
      atStartOfLine=false;
     }
     if (b=='\n') {
      Console.WriteLine();
      atStartOfLine=true;
     }
     else if (b=='\r') {
      // ignore 
     }
     else {
      Console.Write(b);
     }
   }
   public override Encoding Encoding {
    get {
     return Encoding.UTF8;
    }
   }
  }
}

ugcb2.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugcb.cs
   ````````````
   Retrieve model output via callback-style functionality.
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Mar. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugcb.cs {

  public class ugcb {
    
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Redirect error stream to stdout
      mosel.SetDefaultStream(XPRMStreamType.F_ERROR, Console.Out);

      // Compile and load the Mosel model
      XPRMModel model = mosel.CompileAndLoad("burglar2.mos");
      
      // Collect the model's output into a string
      StringWriter modelOut = new StringWriter();
      model.SetDefaultStream(XPRMStreamType.F_OUTPUT_LINEBUF, modelOut);
    
      // Run the model
      model.Run();

      // Print the output 
      string modelOutText = modelOut.ToString();
      Console.WriteLine("Model output: {0}", modelOutText);
    }
  }

}

ugsol.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 


   file ugsol.cs
   `````````````
   Accessing modeling objects and solution information.
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Apr. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugsol.cs {

  public class ugsol {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static int Main(string[] args) {
      XPRMArray varr, darr;
      XPRMSet set;
      XPRMMPVar x;
      double val;

      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Compile and load a model 
      XPRMModel model = mosel.CompileAndLoad("burglar3.mos");

      // Run the model
      model.Run();

      if(model.ProblemStatus!=XPRMProblemStatus.PB_OPTIMAL) 
        return 1;                    // Stop if no solution found

      Console.WriteLine("Objective value: " + model.ObjectiveValue);
                                     // Print the objective function value

      // Get model object 'take', it must be an array
      varr=(XPRMArray)model.FindIdentifier("take");  
      // Get model object 'VALUE', it must be an array
      darr=(XPRMArray)model.FindIdentifier("VALUE");
      // Get model object 'ITEMS', it must be a set
      set=(XPRMSet)model.FindIdentifier("ITEMS");

      // Enumerate all entries of 'varr' (dense array)
      foreach(int[] indices in varr.Indices)
      {
	x = varr.Get(indices).AsMPVar();   // Get a variable from varr
        val = darr.GetAsReal(indices);     // Get the corresponding value
//        Console.WriteLine("take(" + set.GetAsString(indices[0]) + "): " +
        Console.WriteLine("take" + varr.IndexToString(indices) + ": " +
	                x.Solution + "\t (item value: " + val + ")");
      }

      model.Reset();                         // Reset the model
      return 0;
    }
  }
}

ugparam.cs
/********************************************************
   Mosel User Guide Example Problems
   ================================= 

   file ugparam.cs
   ```````````````
   Passing parameters to a Mosel program
   Accessing modeling objects (sets).
   
   (c) 2013 Fair Isaac Corporation
       author: S.Heipcke, Apr. 2013 
********************************************************/


using System;
using System.IO;
using Mosel;


namespace ugparam.cs {

  public class ugparam {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      XPRMSet set;
      int LIM=500, first, last;

      // Initialize Mosel
      XPRM mosel = XPRM.Init();

      // Compile and load a model 
      XPRMModel model = mosel.CompileAndLoad("prime.mos");

      // Run the model
      model.ExecParams = "LIMIT=" + LIM;
      model.Run();
      Console.WriteLine("`prime' returned: " + model.Result);

      // Get model object 'SPrime', it must be a set
      set=(XPRMSet)model.FindIdentifier("SPrime");                              

      // Enumerate the set elements
      if (!set.IsEmpty)
      {
        first = set.FirstIndex;         // Get the number of the first index
        last = set.LastIndex;           // Get the number of the last index
	Console.WriteLine("Prime numbers from 2 to " + LIM);
        for (int i=first;i<=last;i++)   // Print all set elements
          Console.Write(" {0},", set.GetAsInteger(i));
        Console.WriteLine();
      }
    }
  }
}

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

   file burglar2.mos
   `````````````````
   Use of index sets.
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, 2001, rev. 2006
*******************************************************!)

model Burglar2
 uses "mmxprs"
 
 declarations
  WTMAX = 102                    ! 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
  
  take: array(ITEMS) of mpvar    ! 1 if we take item i; 0 otherwise
 end-declarations

 initializations from 'burglar.dat'
  VALUE  WEIGHT
 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

! Print out the solution
 writeln("Solution:\n Objective: ", getobjval)
 forall(i in ITEMS)  writeln(" take(", i, "): ", getsol(take(i)))
end-model

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

   file transport.mos
   ``````````````````
   Using dynamic arrays.
   
   (c) 2008 Fair Isaac Corporation
       author: S.Heipcke, 2001, rev. June 2018
*******************************************************!)

model Transport
 uses "mmxprs"

 public declarations
  REGION: set of string                 ! Set of customer regions
  PLANT: set of string                  ! Set of plants

  DEMAND: array(REGION) of real         ! Demand at regions
  PLANTCAP: array(PLANT) of real        ! Production capacity at plants
  PLANTCOST: array(PLANT) of real       ! Unit production cost at plants
  TRANSCAP: dynamic array(PLANT,REGION) of real
                                        ! Capacity on each route plant->region
  DISTANCE: dynamic array(PLANT,REGION) of real
                                        ! Distance of each route plant->region
  FUELCOST: real                        ! Fuel cost per unit distance

  flow: dynamic array(PLANT,REGION) of mpvar    ! Flow on each route
 end-declarations
 
 initializations from 'transprt.dat'
  DEMAND
  [PLANTCAP,PLANTCOST] as 'PLANTDATA'
  [DISTANCE,TRANSCAP] as 'ROUTES'
  FUELCOST
 end-initializations
 
! Create the flow variables that exist
 forall(p in PLANT, r in REGION | exists(TRANSCAP(p,r)) ) create(flow(p,r))
 
! Objective: minimize total cost
 MinCost:= sum(p in PLANT, r in REGION | exists(flow(p,r))) 
            (FUELCOST * DISTANCE(p,r) + PLANTCOST(p)) * flow(p,r)
 
! Limits on plant capacity
 forall(p in PLANT) sum(r in REGION) flow(p,r) <= PLANTCAP(p)

! Satisfy all demands
 forall(r in REGION) sum(p in PLANT) flow(p,r) = DEMAND(r)
 
! Bounds on flows
 forall(p in PLANT, r in REGION | exists(flow(p,r))) 
  flow(p,r) <= TRANSCAP(p,r)
 
 minimize(MinCost)                       ! Solve the problem
 
end-model

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

   file prime.mos 
   ``````````````
   Working with sets.
 
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, 2001, rev. June 2018
*******************************************************!)

model Prime 

 parameters
  LIMIT=100                     ! Search for prime numbers in 2..LIMIT
 end-parameters

 public declarations
  SNumbers: set of integer      ! Set of numbers to be checked
  SPrime: set of integer        ! Set of prime numbers
 end-declarations

 SNumbers:={2..LIMIT} 
 
 writeln("Prime numbers between 2 and ", LIMIT, ":")

 n:=2
 repeat
   while (not(n in SNumbers)) n+=1
   SPrime += {n}                ! n is a prime number
   i:=n
   while (i<=LIMIT) do          ! Remove n and all its multiples
     SNumbers-= {i}
     i+=n
   end-do
 until SNumbers={}    
 
 writeln(SPrime)
 writeln(" (", getsize(SPrime), " prime numbers.)")
 
end-model

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

   file burglar3.mos
   `````````````````
   Same as burglar2.mos but no output printing.
   
   (c) 2008 Fair Isaac Corporation
       author: S. Heipcke, 2001, rev. June 2018
*******************************************************!)

model Burglar3
 uses "mmxprs"
 
 public declarations
  WTMAX = 102                    ! 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
  
  take: array(ITEMS) of mpvar    ! 1 if we take item i; 0 otherwise
 end-declarations

 initializations from 'burglar.dat'
  VALUE  WEIGHT
 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

end-model

© 2001-2020 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.