Initializing help system before first use

Retrieving data from a Mosel model


Type: Programming
Rating: 3 (intermediate)
Description: mmexset.cs: Using sets in Mosel (requires burglari.bim)
  • retrieve a set by its model name
  • get the set size
  • get first and last set element
  • get the name or index of a set element
mmexas.cs: Using arrays with index sets (requires trans.bim)
  • get indexing sets of an array
  • get array type
  • enumerate array entries in usual and transposed order
  • enumerate true array entries
mmexlst.cs: Using lists in Mosel (requires euler.mos and euler.dat)
  • retrieve a list by its model name
  • get the list size
  • enumerate the list elements
  • get value of list element
mmexrec.cs: Using records in Mosel (requires burglar_rec.mos and burglar_rec.dat)
  • retrieve an array of records (user type) by its model name
  • retrieve the record field information (field name, type, and number)
  • enumerate the array of records
  • for each array entry (record) get the value of all its fields
mmexprob.cs: Accessing problems and solution information with Mosel (requires blend2.bim)
  • export problem to a file (MPS or LP format)
  • get problem status
  • get objective function value
  • get primal/dual solution values, and constraint activity
Note that these examples require the provided mos files to be pre-compiled.
File(s): mmexset.cs, mmexas.cs, mmexlst.cs, mmexrec.cs, mmexprob.cs
Data file(s): burglari.mos, trans.mos, euler.mos, euler.dat, burglar_rec.mos, burglar_rec.dat, blend2.mos


mmexset.cs
/********************************************************/
/*  Mosel Library Examples                              */
/*  ======================                              */
/*                                                      */
/*  file mmexset.cs                                     */
/*  ```````````````                                     */
/*  Example for the use of the Mosel libraries          */
/*  (accessing sets in Mosel)                           */
/*                                                      */
/*  (c) 2008 Fair Isaac Corporation                     */
/*      author: J. Farmer & S. Heipcke                  */
/********************************************************/

using System;
using Mosel;

namespace mmexset {
  public class mmexsetClass {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      XPRM mosel;
      XPRMModel mod;
      XPRMSet set;
      int first, last;

      // Initialise Mosel
      mosel = XPRM.Init();
      /// Load a BIM file
      mod = mosel.LoadModel("Models/burglari.bim");
      // Ru the model
      mod.Run();

      // Get the model object named 'ITEMS'
      // (it must be a set)
      set = (XPRMSet) mod.FindIdentifier("ITEMS");

      if (!set.IsEmpty) {
        // Items in a set are indexed by numbers
        // So get the number of the first and last indexes
        first = set.FirstIndex;
        last = set.LastIndex;
        Console.WriteLine("Elements of set ITEMS:");
        for (int i=first;i<=last;i++)
          Console.Write(" {0}, ", set.GetAsString(i));
        Console.WriteLine();
      }
      // We've written this explicitely to demonstrate set access, but the set
      // actually knows how to output itself.  Uncomment the following line to
      // see how it does this.
      // Console.WriteLine(set);

      if (set.GetIndex("CD player")<0)
        Console.WriteLine("'CD player' is not contained in 'ITEMS',");
    }
  }
}

mmexas.cs
/********************************************************/
/*  Mosel Library Examples                              */
/*  ======================                              */
/*                                                      */
/*  file mmexas.cs                                      */
/*  ``````````````                                      */
/*  Example for the use of the Mosel libraries          */
/*  (using arrays with index sets: different ways       */
/*   of enumerating arrays)                             */
/*                                                      */
/*  (c) 2008 Fair Isaac Corporation                     */
/*      author: J.Farmer & S. Heipcke                   */
/********************************************************/


using System;
using Mosel;

namespace mmexas {
  public class mmexasClass {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      XPRM mosel;
      XPRMModel mod;
      XPRMArray varr;
      XPRMSet[] sets;
      XPRMValue[] vindex;
      int dim;

      // Initialise Mosel
      mosel = XPRM.Init();
      // Load a BIM file
      mod = mosel.LoadModel("Models/trans.bim");
      // Run the model;
      mod.Run();


      // Get the model object named 'x'
      // It must be an array
      varr = (XPRMArray) mod.FindIdentifier("x");
      // Get the number of dimensions of the array
      dim = varr.Dim;
      // Get the indexing sets
      sets = varr.IndexSets;

      // We could use varr.ToString() to print out a summary of the
      // array contents, but instead we'll demonstrate how to iterate
      // over the array contents directly

      Console.WriteLine("\n1. Logic entries:");
      // Get the first entry of varr
      foreach(int[] indices in varr.Indices) {
        Console.Write("x(");
        // Get the values for this index
        vindex = varr.DereferenceIndex(indices);
        // Now, output them.  Note that we could call the utility method
        // varr.IndexToString(indices) instead of this and the previous
        // line
        for (int i=0;i<dim-1;i++)
          Console.Write(vindex[i] + ",");
        Console.Write(vindex[dim-1] + "), ");
      };

      // Now enumerate over the true entries - in a dense array this would
      // be no different from the previous method, so skip it in this case.
      if (varr.IsDynamic) {
        Console.WriteLine("\n\n2. True entries:");
        foreach(int[] indices in varr.TEIndices) {
          Console.Write("x(");
          vindex = varr.DereferenceIndex(indices);
          for (int i=0;i<dim-1;i++)
            Console.Write(vindex[i] + ",");
          Console.Write(vindex[dim-1] + "), ");
        };
      }
      Console.WriteLine();

      mod.Reset();
    }
  }
 }


mmexlst.cs
/********************************************************/
/*  Mosel Library Examples                              */
/*  ======================                              */
/*                                                      */
/*  file mmexlst.cs                                     */
/*  ```````````````                                     */
/*  Accessing modeling objects                          */
/* (enumerating the elements of a list)                 */
/*                                                      */
/*  (c) 2008 Fair Isaac Corporation                     */
/*      author: J. Farmer                               */
/********************************************************/


using System;
using Mosel;


namespace mmexlst {

  /// <summary>
  /// Records example
  /// </summary>
  class mmexlstClass {

    [STAThread]
    static void Main(string[] args) {
      
      /* Initialize Mosel */
      XPRM mosel = XPRM.Init();
      
      /* Compile & load the model */
      mosel.Compile("Models/euler.mos");
      XPRMModel mod = mosel.LoadModel("Models/euler.bim");
      
      /* Run the model */
      mod.Run();
      
      /* Get the model object named 'TOUR' */
      XPRMList lst = (XPRMList) mod.FindIdentifier("TOUR");
      
      /* Print out all the list elements */
      Console.Write("Tour: ");
      int count=0;
      foreach (XPRMValue val in lst) {
        Console.Write(val.AsInteger());
        if ((++count)<lst.Count)
          Console.Write(" -> ");
      }
      Console.WriteLine();

      
    }


  }

}

mmexrec.cs
/********************************************************/
/*  Mosel Library Examples                              */
/*  ======================                              */
/*                                                      */
/*  file mmexrec.cs                                     */
/*  ```````````````                                     */
/*  Accessing modeling objects                          */
/* (enumerating an array of records and                 */
/*  printing the value of each record field).           */
/*                                                      */
/*  (c) 2008 Fair Isaac Corporation                     */
/*      author: J. Farmer                               */
/********************************************************/


using System;
using Mosel;


namespace mmexrec {

  /// <summary>
  /// Records example
  /// </summary>
  class mmexrecClass {

    [STAThread]
    static void Main(string[] args) {
      
      /* Initialize Mosel */
      XPRM mosel = XPRM.Init();
      
      /* Compile & load the model */
      mosel.Compile("Models/burglar_rec.mos");
      XPRMModel mod = mosel.LoadModel("Models/burglar_rec.bim");
      
      /* Run the model */
      mod.Run();
      
      /* Get the model object named 'I' */
      XPRMArray arr = (XPRMArray) mod.Identifiers["I"];

      /* Iterate over the fields */
      XPRMRecordFields fields = ((XPRMUserType)mod.ExpandType(arr.TypeCode)).Fields;
      
      Console.WriteLine("Record has {0} fields:", fields.Count);
      foreach (XPRMRecordField f in fields)
        Console.WriteLine(f.Name);
      
      /* Enumerate the array (we know it has a single dimension) */
      XPRMSet[] indSets = arr.IndexSets;
      
      /* Get the first index tuple */
      int[] indices = arr.FirstIndex;
      do {
        /* Display the array index */
        Console.Write("I({0}): \t", indSets[0].Get(indices[0]));
        /* Retrieve the array entry (=record) */
        XPRMRecord rec = arr.Get(indices).AsRecord();
        /* Output contents of 1st record field */
        Console.Write("{0}={1} ", fields[0].Name, rec.GetValueAsReal(fields[0]));
        /* Output contents of 2nd record field */
        Console.Write("{0}={1} ", fields[1].Name, rec.GetValueAsReal(fields[1]));
        Console.WriteLine();
      } while (arr.NextIndex(indices)); /* And move onto the next index tuple */
      
      
      /* Reset the model */
      mod.Reset();
      
    }


  }

}

mmexprob.cs
/********************************************************/
/*  Mosel Library Examples                              */
/*  ======================                              */
/*                                                      */
/*  file mmexprob.cs                                    */
/*  ````````````````                                    */
/*  Example for the use of the Mosel libraries          */
/*  (accessing problems and solution information)       */
/*                                                      */
/*  (c) 2008 Fair Isaac Corporation                     */
/*      author: J.Farmer & S. Heipcke                   */
/********************************************************/

using System;
using Mosel;

namespace mmexprob {
  public class mmexprobClass {
    /// <summary>
    /// Main entry point for the application
    /// </summary>
    [STAThread]
    static void Main(string[] args) {
      XPRM mosel;
      XPRMModel mod;
      XPRMArray varr, darr;
      XPRMLinCtr lgrade;

      // Initialize Mosel
      mosel = XPRM.Init();
      // Load a BIM file
      mod = mosel.LoadModel("Models/blend2.bim");
      // Run the model (it includes optimization)
      mod.Run();

      // Export the problem to a file in LP format (maximization)
      mod.ExportProblem("p", "blend");

      // Test whether optimal is found
      if (mod.ProblemStatus==XPRMProblemStatus.PB_OPTIMAL)
        Console.WriteLine("Solution is optimal.");

      // Print out the objective function value
      Console.WriteLine("Objective value: {0}", mod.ObjectiveValue);

      // Get the model objects 'x' and 'COST' (both arrays)
      varr = (XPRMArray) mod.FindIdentifier("x");
      darr = (XPRMArray) mod.FindIdentifier("COST");

      // For each entry in array varr, display solution value and
      // corresponding cost
      foreach(int[] indices in varr.Indices) {
        Console.WriteLine(
          "x{0}={1} (COST: {2})",
          varr.IndexToString(indices),
          varr.Get(indices).AsMPVar().Solution,
          darr.GetAsReal(indices)
        );
      }

      // Get the model object 'LoGrade'
      // It must be a reference to a linear constraint
      lgrade = ((XPRMReference) mod.FindIdentifier("LoGrade")).Value.AsLinCtr();
      Console.WriteLine(
        "LoGrade: activity={0}, dual={1}",
        lgrade.Activity,
        lgrade.Dual
      );

      mod.Reset();
    }
  }
}