Quick Start

This section will show a simple example to illustrate various functionalities of the AMPL C# interface. The full example prints the version of the AMPL interpreter used, loads a model from file and the corresponding data file, solves it, gets some of the AMPL entities in C# and uses them to get the results and to assign data programmatically. This section assumes that you are already familiar with the C# language. Full class reference is given in C# API Reference.

Complete listing

This is the complete listing of the example. Please note that, for clarity of presentation, all the code in the examples below does not include exceptions handling.

using ampl;
using ampl.Entities;
using System;

public static int Main(string[] args)
{
        String modelDirectory = ((args != null) && (args.Length > 0)) ? args[0] : "./models";

        /*
        // If the AMPL installation directory is not in the system search path:
        ampl.Environment env = new ampl.Environment(
                "full path to the AMPL installation directory");
        // Create an AMPL instance
        using (AMPL a = new AMPL(env)) {}
        */

        // Create an AMPL instance
        using (AMPL a = new AMPL())
        {
                // Interpret the two files
                a.Read(System.IO.Path.Combine(modelDirectory, "diet.mod"));
                a.ReadData(System.IO.Path.Combine(modelDirectory, "diet.dat"));

                // Solve
                a.Solve();

                // Get objective entity by AMPL name
                Objective totalcost = a.GetObjective("Total_Cost");
                // Print it
                Console.WriteLine("ObjectiveInstance is: {0}", totalcost.Value);
                // Reassign data - specific instances
                Parameter cost = a.GetParameter("cost");
                cost.SetValues(ampl.Tuple.FromArray("BEEF", "HAM"), new double[] { 5.01, 4.55 });
                Console.WriteLine("Increased costs of beef and ham.");

                // ReSolve and display objective
                a.Solve();
                Console.WriteLine("Objective value: {0}", totalcost.Value);

                // Reassign data - all instances
                cost.SetValues(new double[] { 3, 5, 5, 6, 1, 2, 5.01, 4.55 });
                Console.WriteLine("Updated all costs");
                // ReSolve and display objective
                a.Solve();
                Console.WriteLine("New objective value: {0}", totalcost.Value);

                // Get the values of the variable Buy in a dataframe object
                Variable Buy = a.GetVariable("Buy");
                // Access a specific instance (method 1)
                Console.WriteLine(Buy.Get("FISH").ToString());
                // Access a specific instance (method 2)
                Console.WriteLine(Buy[new ampl.Tuple("FISH")].ToString());
                DataFrame df = Buy.GetValues();
                // Print them
                Console.WriteLine(df);

                // Get the values of an expression into a DataFrame object
                DataFrame df2 = a.GetData("{j in FOOD} 100*Buy[j]/Buy[j].ub");
                // Print them
                Console.WriteLine(df2);
        }
}

Namespaces and AMPL environment creation

All the classes of the C# AMPL API are defined in the assembly csharpapi.dll therefore adding a reference to it is a mandatory and sufficient step to start developing. Please note that all classes part of the AMPL API are declared in the ampl and ampl.Entities namespaces.

using ampl;

Then copy the following statements to have a hello world application which gets the value of the option version as defined in the underlying AMPL executable and prints the result on the console.

AMPL ampl = new AMPL();
Console.WriteLine(ampl.GetOption("version"));

The first line creates a new AMPL object with all default settings, the second, which is the preferred way to access AMPL options, gets the value of the option version from AMPL as a string and prints the result on the active console.

Load a model from file

The following lines use the method ampl.AMPL.Read() to load a model and data stored in external (AMPL) files. If the files are not found, an exception is thrown.

a.Read(System.IO.Path.Combine(modelDirectory, "diet.mod"));
a.ReadData(System.IO.Path.Combine(modelDirectory, "diet.dat"));

Once these commands are executed, the AMPL interpreter will have interpreted the content of the two files. No further communication is made between the AMPL interpreter and the C# object, as every entity is created lazily (as needed).

Solve a problem

To solve the currently loaded problem instance, it is sufficient to issue the command:

ampl.Solve();

Get an AMPL entity in the programming environment (get objective value)

AMPL API provides C# representations of the AMPL entities. Usually, not all the entities are of interest for the programmer. The generic procedure is:

  1. Identify the entities that need interaction (either data read or modification)

  2. For each of these entities, create an object of the appropriate class in C#

  3. Get the entity through the AMPL API using one of the following functions: ampl.AMPL.GetVariable(), ampl.AMPL.GetConstraint(), ampl.AMPL.GetObjective(), ampl.AMPL.GetParameter() and ampl.AMPL.GetSet().

Objective totalcost = ampl.GetObjective("Total_Cost");
Console.WriteLine("Objective value is: {0}", totalcost.Get().Value);

It can be noted that we access an Objective to interrogate AMPL API about the objective function. It is a collections of objectives. To access the single instance, the function Get() should be used in case of the objective, which gets the only instance of the objective. Since objectives are often single instance, the Value property has been implemented in the class ampl.Entities.Objective. So, equivalently to the call above, the following call would return the same value, as it gives direct access to the objective function value totalcost.Value.

The output of the snippet above is:

Objective is: 118.05940323955669

The same is true for all other entities.

Modify model data (assign values to parameters)

The input data of an optimisation model is stored in its parameters; these can be scalar or vectorial entities. Two ways are provided to change the value of vectorial parameter: change specific values or change all values at once. The example shows an example of both ways, reassigning the values of the parameter costs firstly specifically, then altogether. Each time, it then solves the model and get the objective function. The function used to change the values is overloaded, and is in both cases ampl.Entities.Parameter.SetValues().

Parameter cost = a.GetParameter("cost");
cost.SetValues(ampl.Tuple.FromArray("BEEF", "HAM"),
    new double[] { 5.01, 4.55 });
Console.WriteLine("Increased costs of beef and ham.");
ampl.Solve();
Console.WriteLine("New objective value: {}", totalcost.Value);

The code above assigns the values 5.01 and 4.55 to the parameter cost for the objects beef and ham respectively. If the order of the indexing of an entity is known (i.e. for multiple reassignment), it is not necessary to specify both the index and the value. A collection of values is assigned to each of the parameter values, in the order they are represented in AMPL.

cost.SetValues(new double[] { 3, 5, 5, 6, 1, 2, 5.01, 4.55 });
Console.WriteLine("Updated all costs");
a.Solve();
Console.WriteLine("New objective value: {0}", totalcost.Value);

The statements above produce the following output:

Objective is: 118.05940323955669
Increased costs of beef and ham.
New objective value: 144.41572037510653
Updated all costs
New objective value: 164.54375000000002

Get numeric values from variables

To access all the numeric values contained in a Variable or any other entity, use a ampl.DataFrame object. Doing so, the data is detached from the entity, and there is a considerable performance gain. To do so, we first get the Variable object from AMPL, then we get its data with the function ampl.Entity.getValues().

// Get the values of the variable Buy in a dataframe object
Variable Buy = a.GetVariable("Buy");
// Access a specific instance (method 1)
Console.WriteLine(Buy.Get("FISH").ToString());
// Access a specific instance (method 2)
Console.WriteLine(Buy[new ampl.Tuple("FISH")].ToString());
DataFrame df = Buy.GetValues();
// Print them
Console.WriteLine(df);

Get arbitrary values via ampl expressions

Often we are interested in very specific values coming out of the optimization session. To make use of the power of AMPL expressions and avoiding cluttering up the environment by creating entities, fetching data through arbitrary AMPL expressions is possible. For this model, we are interested in knowing how close each decision variable is to its upper bound, in percentage. We can obtain this data into a dataframe using the function ampl.AMPL.GetData() with the code :

// Get the values of an expression into a DataFrame object
DataFrame df2 = a.GetData("{j in FOOD} 100*Buy[j]/Buy[j].ub");
// Print them
Console.WriteLine(df2);

Close the AMPL object to free the resources

It is good practice to make sure that the AMPL object is closed and all its resources released when it is not needed any more; the ampl.AMPL class supoorts the IDisposable interface therefore a using statement guarantees closure of all associated resources. To close the AMPL process at any point in time, refer to the method ampl.AMPL.Close().

using (AMPL ampl = new AMPL())
{
        Console.WriteLine(ampl.GetOption("version"));
} // automatically closed

AMPL ampl2 = new AMPL();
ampl2.Close(); // Closed manually