Tutorial

The goal of this tutorial is to provide a compact overview of the basic functionality of the GAMS C# API. It allows the user to start immediately working with the API by providing a set of small examples based on the well-known transportation problem. These examples introduce several API features step by step.

Getting Started

This section illustrates the basic steps of creating and configuring a C# project in Visual Studio Code for use with the GAMS C# API.

Install the C# extension in Visual Studio Code

To develop .NET applications in Visual Studio Code, first install the official C# tooling from Microsoft. Visual Studio Code is a lightweight editor by default, with many extensions one can install for personal preferences.

  1. Open Visual Studio Code.
  2. Open the Extensions sidebar by clicking the Extensions icon on the Activity Bar on the left side of the window, or press Ctrl+Shift+X (Cmd+Shift+X on macOS).
  3. In the search box, type C# Dev Kit or C#.
  4. Select C# Dev Kit (published by Microsoft) and click Install.
Installing the C# Dev Kit extension in Visual Studio Code

Create a new project

After opening Visual Studio Code, create a new .NET project. To do this, open the Explorer sidebar by clicking the File icon or pressing Ctrl+Shift+E. Then, click the "Create .NET Project" button and choose a Project Template (e.g. Console App). Finally, set a project name, such as GAMSApplication.

Creating a new .NET Project
Choosing the right template

Add a reference to the GAMS.net10.dll assembly

The simplest way to reference the GAMS assembly is by adding the following ItemGroup section into the Project section of GAMSApplication.csproj:

<ItemGroup>
<Reference Include="GAMS.net10">
<HintPath>C:\GAMS\55\api\dotnet\GAMS.net10.dll</HintPath>
</Reference>
</ItemGroup>
Adding a GAMS assembly reference to the .csproj file

Replace C:\GAMS\55\api\dotnet\GAMS.net10.dll with the actual path to GAMS.net10.dll inside the GAMS system directory.

Solving the first model

This section illustrates how a model from the GAMS model library can be imported and solved.

Open a new project and reference the GAMS.net10.dll in the project as explained above. Open Program.cs which should be part of the project and replace the content by:

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using GAMS;
namespace TransportSeq
{
class Transport0
{
static void Main(string[] args)
{
ws.GamsLib("trnsport");
// create a GAMSJob from file and run it with default settings
GAMSJob t0 = ws.AddJobFromFile("trnsport.gms");
t0.Run();
Console.WriteLine("Ran with Default:");
foreach (GAMSVariableRecord rec in t0.OutDB.GetVariable("x"))
Console.WriteLine("x(" + rec.Key(0) + "," + rec.Key(1) + "): level=" + rec.Level + " marginal=" + rec.Marginal);
Console.WriteLine("z=" + t0.OutDB.GetVariable("z").LastRecord().Level);
}
}
}
GAMSVariable GetVariable(string variableIdentifier)
GAMSDatabase OutDB
void Run(GAMSOptions gamsOptions=null, GAMSCheckpoint checkpoint=null, TextWriter output=null, Boolean createOutDB=true)
new GAMSVariableRecord LastRecord()
void GamsLib(string model)
GAMSJob AddJobFromFile(string fileName, GAMSCheckpoint checkpoint=null, string jobName=null)

To run the program, open the integrated terminal (Terminal -> New Terminal), navigate to the folder containing the .csproj file (e.g., cd GAMSApplication), and run:

dotnet run

Alternatively, run and debug the program directly from within Visual Studio Code:

  1. Open the Program.cs tab of the project.
  2. Open the Run and Debug panel on the left-hand side.
  3. Click Run and Debug. If prompted to select a debugger, choose C#, and then select C#: Launch Startup Project <YourProjectName> (e.g., C#: Launch Startup Project GAMSApplication) from the list of detected launch configurations.
Selecting the launch configuration in Visual Studio Code

The program is then built and executed, and its console output (including anything written to Console.Out) is shown in the integrated Debug Console:

Ran with Default:
x(seattle,new-york): level=50 marginal=0
x(seattle,chicago): level=300 marginal=0
x(seattle,topeka): level=0 marginal=0.036000000000000004
x(san-diego,new-york): level=275 marginal=0
x(san-diego,chicago): level=0 marginal=0.009000000000000008
x(san-diego,topeka): level=275 marginal=0
z=153.675

Important Classes of the API

This section provides a quick overview of some fundamental classes of the GAMS Namespace. Their usage is demonstrated by an extensive set of examples.

How to use the API

In the GAMS system directory there are some examples provided that illustrate the usage of the C# API. <GAMS system directory>\api\dotnet\examples\control\csharp contains a file TransportSeq.slnx that can be opened in Microsoft Visual Studio. The contained projects deal with the well-known transportation problem. In further course of this tutorial these examples are discussed step by step and new elements of the API are introduced in detail.

The aforementioned files provide a complete overview of the examples. Down below the examples are explained with the help of selected code snippets.

Choose the GAMS system

Example: Transport1

By default the GAMS system is determined automatically. In case of multiple GAMS systems, the desired system can be specified via an additional argument when the workspace is created. When running the examples, an additional command line argument can be provided to define the GAMS system directory that should be used. By executing Transport1.exe with C:/GAMS/55, GAMS 55 is used to run Transport1 even if the default GAMS system might be a different one. This is managed by the following code:

...
GAMSWorkspace ws;
if (Environment.GetCommandLineArgs().Length > 1)
ws = new GAMSWorkspace(systemDirectory: Environment.GetCommandLineArgs()[1]);
else
ws = new GAMSWorkspace();
...

Export data to GDX

Example: TransportGDX

Although the .NET Control API offers much more than exchanging data between .NET and GDX, a common use case is the export and import of GDX files. The central class for this purpose is GAMSDatabase. For the following example, it is assumed that the data to be exported is available in .NET data structures.

...
List<string> plants = new List<string>()
{
"Seattle", "San-Diego"
};
List<string> markets = new List<string>()
{
"New-York", "Chicago", "Topeka"
};
Dictionary<string, double> capacity = new Dictionary<string, double>()
{
{ "Seattle", 350.0 }, { "San-Diego", 600.0 }
};
Dictionary<string, double> demand = new Dictionary<string, double>()
{
{ "New-York", 325.0 }, { "Chicago", 300.0 }, { "Topeka", 275.0 }
};
Dictionary<Tuple<string, string>, double> distance = new Dictionary<Tuple<string, string>, double>()
{
{ new Tuple<string,string> ("Seattle", "New-York"), 2.5 },
{ new Tuple<string,string> ("Seattle", "Chicago"), 1.7 },
{ new Tuple<string,string> ("Seattle", "Topeka"), 1.8 },
{ new Tuple<string,string> ("San-Diego", "New-York"), 2.5 },
{ new Tuple<string,string> ("San-Diego", "Chicago"), 1.8 },
{ new Tuple<string,string> ("San-Diego", "Topeka"), 1.4 }
};
...

Different GAMS symbols are represented using different .NET data structures. The data for the GAMS sets is represented using lists of strings (e.g. plants and markets). On the other hand, GAMS parameters are represented by dictionaries (e.g. capacity and demand). Note that the representation of the two dimensional parameter distance uses tuples for storing the keys. The choice of data structures can also be different, but the used structures in this example fit well for representing GAMS data with .NET data structures.

A new GAMSDatabase instance can be created using GAMSWorkspace.AddDatabase.

...
// prepare a GAMSDatabase with data from the C# data structures
GAMSDatabase db = ws.AddDatabase();
...
GAMSDatabase AddDatabase(string databaseName=null, string inModelName=null)

Next, GAMS sets are added by using the method GAMSDatabase.AddSet, which takes the name and the dimension as arguments. The third argument is an optional explanatory text. A foreach-loop iterates through plants and adds new records to the recently created GAMSSet instance i using GAMSSet.AddRecord.

...
// add 1-dimensional set 'i' with explanatory text 'canning plants' to the GAMSDatabase
GAMSSet i = db.AddSet("i", 1, "canning plants");
foreach (string p in plants)
i.AddRecord(p);
...

GAMSParameter instances can be added by using the method GAMSDatabase.AddParameter. It has the same signature as GAMSDatabase.AddSet. Anyhow, in this example an overload of the method is used, which takes a list of GAMSSet instances instead of the dimension for creating a parameter with domain information.

...
// add parameter 'a' with domain 'i'
GAMSParameter a = db.AddParameter("a", "capacity of plant i in cases", i);
foreach (string p in plants)
a.AddRecord(p).Value = capacity[p];
...

As soon as all data is prepared in the GAMSDatabase, the method GAMSDatabase.Export can be used to create a GDX file.

...
// export the GAMSDatabase to a GDX file with name 'data.gdx' located in the 'workingDirectory' of the GAMSWorkspace
db.Export("data.gdx");
...

Import data from GDX

Example: TransportGDX

Data can be imported from a GDX file using GAMSWorkspace.AddDatabaseFromGDX. The method takes a path to a GDX file and creates a GAMSDatabase instance.

...
// add a new GAMSDatabase and initialize it from the GDX file just created
GAMSDatabase db2 = ws.AddDatabaseFromGDX("data.gdx");
...
GAMSDatabase AddDatabaseFromGDX(string gdxFileName, string databaseName=null, string inModelName=null)

Reading the data from the GAMSSet i into a list can be done as follows:

...
// read data from symbols into .NET data structures
List<string> plants2 = new List<string>();
foreach (GAMSSetRecord item in db2.GetSet("i"))
plants2.Add(item.Key(0));
...

A new list plants2 is created. i is retrieved by calling GAMSDatabase.GetSet on db2. The returned GAMSSet object can be iterated using a foreach-loop to access the records of the set. Each record is of type GAMSSetRecord and can be asked for its keys.

One can do the same for GAMSParameters. Instead of creating a list, one can have the data in the form of a dictionary. GAMSParameterRecords can not only be asked for their keys, but also for their value. The following code snippet shows how to read the one dimensional parameter a into a Dictionary<string, double>.

...
Dictionary<string, double> capacity2 = new Dictionary<string, double>();
foreach (GAMSParameterRecord item in db2.GetParameter("a"))
capacity2.Add(item.Key(0), item.Value);
...

For multi dimensional symbols, one can use tuples instead of strings as dictionary keys.

...
Dictionary<Tuple<string, string>, double> distance2 = new Dictionary<Tuple<string, string>, double>();
foreach (GAMSParameterRecord item in db2.GetParameter("d"))
distance2.Add(new Tuple<string, string>(item.Key(0), item.Key(1)), item.Value);
...

Run a GAMSJob from file

Example: Transport1

Here the model trnsport is loaded from the GAMS Model Library. In doing so it is made available in the current working directory and can be loaded by the GAMSWorkspace.AddJobFromFile method afterwards. Apparently this method also works with any other gms file one might have created as long as it is located in the current working directory. Then the GAMSJob t1 is defined from that file and run by the GAMSJob.Run method.

The following lines create the solution output and illustrate the usage of the GAMSJob.OutDB property to get access to the GAMSDatabase created by the Run method. To retrieve the content of variable x, the GAMSVariableRecord class and the GAMSDatabase.GetVariable method are used.

...
ws.GamsLib("trnsport");
// create a GAMSJob from file and run it with default settings
GAMSJob t1 = ws.AddJobFromFile("trnsport.gms");
t1.Run();
Console.WriteLine("Ran with Default:");
foreach (GAMSVariableRecord rec in t1.OutDB.GetVariable("x"))
Console.WriteLine("x(" + rec.Key(0) + "," + rec.Key(1) + "): level=" + rec.Level + " marginal=" + rec.Marginal);
...

Specify the solver

Example: Transport1

The solver can be specified via the GAMSOptions class and the GAMSWorkspace.AddOptions method. The GAMSOptions.AllModelTypes property sets xpress as default solver for all model types which the solver can handle.

...
// run the job again with another solver
using (GAMSOptions opt = ws.AddOptions())
{
opt.AllModelTypes = "xpress";
t1.Run(opt);
}
...
GAMSOptions AddOptions(GAMSOptions optFrom=null)

Run a job with a solver option file and capture its log output

Example: Transport1

At first the StreamWriter is used to create the file xpress.opt, which will be used as solver option file and is stored in the current working directory. Then algorithm=barrier is written to this file to select the barrier algorithm and the solver option file is closed. Xpress is chosen as solver just like in the preceding example and the GAMSOptions.OptFile property is set to 1 to tell the solver to look for a solver option file. In addition, the argument output is specified in order to write the log of the GAMSJob into the file transport1_xpress.log.

...
using (StreamWriter optFile = new StreamWriter(Path.Combine(ws.WorkingDirectory, "xpress.opt")))
using (TextWriter logFile = new StreamWriter(Path.Combine(ws.WorkingDirectory, "transport1_xpress.log")))
using (GAMSOptions opt = ws.AddOptions())
{
optFile.WriteLine("algorithm=barrier");
optFile.Close();
opt.AllModelTypes = "xpress";
opt.OptFile = 1;
t1.Run(opt, output: logFile);
}
...

Instead of writing the log output to a file, it can be written into any TextWriter. In order to write the log directly to Console.Out, one can use the following code:

...
t1.Run(opt, output: Console.Out);
...

Use include files

Example: Transport2

In this example, as in many that follow, the data text and the model text are separated into two different strings. Note that these strings GetDataText and GetModelText are using GAMS syntax.

At first an include file tdata.gms that contains the data but not the model text is written:

...
using (StreamWriter writer = new StreamWriter(ws.WorkingDirectory + Path.DirectorySeparatorChar + "tdata.gms"))
{
writer.Write(GetDataText());
}
...

Afterwards a GAMSJob using the GAMSWorkspace.AddJobFromString method is created. The GAMSOptions.Defines field is used like the 'double dash' GAMS parameters, i.e., it corresponds to --incname=tdata on the command line.

...
using (GAMSOptions opt = ws.AddOptions())
{
GAMSJob t2 = ws.AddJobFromString(GetModelText());
opt.Defines.Add("incname", "tdata");
t2.Run(opt);
...
}
...
GAMSJob AddJobFromString(string gamsSource, GAMSCheckpoint checkpoint=null, string jobName=null)

Note that the string GetModelText contains the following lines to read in the data.

...
$if not set incname $abort 'no include file name for data file provided'
$include %incname%
...

Read data from string and export to GDX

Example: Transport3

As in previous examples, the data is read from the string GetDataText. Note that this contains no solve statement but only data definition in GAMS syntax. By running the corresponding GAMSJob, a GAMSDatabase is created that is available via the GAMSJob.OutDb property. One can use the GAMSDatabase.Export method to write the content of this database to a GDX file tdata.gdx.

...
GAMSJob t3 = ws.AddJobFromString(GetDataText());
t3.Run();
t3.OutDB.Export(ws.WorkingDirectory + Path.DirectorySeparatorChar + "tdata.gdx");
...

Run a job using data from GDX

Example: Transport3

This works quite similar to the usage of an include file explained in Transport2 - Use include files.

...
t3 = ws.AddJobFromString(GetModelText());
using (GAMSOptions opt = ws.AddOptions())
{
opt.Defines.Add("gdxincname", "tdata");
opt.AllModelTypes = "xpress";
t3.Run(opt);
...
}
...
Dictionary< string, string > Defines

Note that there are some changes in GetModelText due to the usage of a GDX file instead of an include file.

...
$if not set gdxincname $abort 'no include file name for data file provided'
$gdxin %gdxincname%
$load i j a b d f
$gdxin
...

Run a job using implicit database communication

Example: Transport3

This example does basically the same as the two preceding examples together. Two GAMSJobs t3a and t3b are created, where the first one contains only the data and the second one contains only the model without data. After running t3a the corresponding OutDB can be read in directly just like a GDX file. Note that the database needs to be passed to the GAMSJob.Run method as additional argument.

...
using (GAMSOptions opt = ws.AddOptions())
{
GAMSJob t3a = ws.AddJobFromString(GetDataText());
GAMSJob t3b = ws.AddJobFromString(GetModelText());
t3a.Run();
opt.Defines.Add("gdxincname", t3a.OutDB.Name);
opt.AllModelTypes = "xpress";
t3b.Run(opt, t3a.OutDB);
...
}
...

Define data using C# data structures

Example: Transport4

The List<T> class, the Dictionary<TKey, TValue> class, and the Tuple<T1, T2> class are used to define C# data structures that correspond to the sets, parameters, and tables used for the data definition in GAMS.

...
List<string> plants = new List<string>()
{
"Seattle", "San-Diego"
};
List<string> markets = new List<string>()
{
"New-York", "Chicago", "Topeka"
};
Dictionary<string, double> capacity = new Dictionary<string, double>()
{
{ "Seattle", 350.0 }, { "San-Diego", 600.0 }
};
Dictionary<string, double> demand = new Dictionary<string, double>()
{
{ "New-York", 325.0 }, { "Chicago", 300.0 }, { "Topeka", 275.0 }
};
Dictionary<Tuple<string,string>, double> distance = new Dictionary<Tuple<string,string>, double>()
{
{ new Tuple<string,string> ("Seattle", "New-York"), 2.5 },
{ new Tuple<string,string> ("Seattle", "Chicago"), 1.7 },
{ new Tuple<string,string> ("Seattle", "Topeka"), 1.8 },
{ new Tuple<string,string> ("San-Diego", "New-York"), 2.5 },
{ new Tuple<string,string> ("San-Diego", "Chicago"), 1.8 },
{ new Tuple<string,string> ("San-Diego", "Topeka"), 1.4 }
};
...

Prepare a GAMSDatabase from C# data structures

Example: Transport4

At first an empty GAMSDatabase db is created using the GAMSWorkspace.AddDatabase method. Afterwards, the database is prepared. To add a set to the database, the GAMSSet class and the GAMSDatabase.AddSet method is used with arguments describing the identifier, dimension, and explanatory text. To add the records to the database, one can iterate over the elements of the C# data structure and add them by using the GAMSSet.AddRecord method.

For parameters the procedure is pretty much the same. Note that an overload of GAMSDatabase.AddParameter taking the domain sets (e.g. i, j) instead of an explicit dimension is used here, which also attaches domain information to the parameter.

The GAMSJob can be run like explained in the preceding example about implicit database communication.

...
GAMSDatabase db = ws.AddDatabase();
GAMSSet i = db.AddSet("i", 1, "canning plants");
foreach (string p in plants)
i.AddRecord(p);
...
GAMSParameter a = db.AddParameter("a", "capacity of plant i in cases", i);
foreach (string p in plants)
a.AddRecord(p).Value = capacity[p];
...
GAMSParameter d = db.AddParameter("d", "distance in thousands of miles", i, j);
foreach(Tuple<string,string> t in distance.Keys)
d.AddRecord(t.Item1,t.Item2).Value = distance[t];
GAMSParameter f = db.AddParameter("f", "freight in dollars per case per thousand miles");
f.AddRecord().Value = 90;
// run a job using data from the created GAMSDatabase
GAMSJob t4 = ws.AddJobFromString(GetModelText());
using (GAMSOptions opt = ws.AddOptions())
{
opt.Defines.Add("gdxincname", db.Name);
opt.AllModelTypes = "xpress";
t4.Run(opt, db);
...
}
...
new GAMSParameterRecord AddRecord(params string[] keys)
new GAMSSetRecord AddRecord(params string[] keys)

Initialize a GAMSCheckpoint by running a GAMSJob

Example: Transport5

The following two lines of code conduct several operations. While the first line simply creates a GAMS Checkpoint, the second one uses the GAMSWorkspace.AddJobFromString method to create a GAMSJob containing the model text and data but no solve statement. In contrast to the preceding examples it runs the job immediately using the GAMSJob.Run method. Furthermore, it passes an additional checkpoint argument to the Run method. That means the GAMSCheckpoint cp captures the state of the GAMSJob.

...
GAMSCheckpoint cp = ws.AddCheckpoint();
...
ws.AddJobFromString(GetModelText()).Run(cp);
...
GAMSCheckpoint AddCheckpoint(string checkpointName=null)

This creates the same checkpoint as for example the following code snippet:

GAMSJob t5a = ws.AddJobFromString(GetModelText());
t5a.Run(cp);

Initialize a GAMSJob from a GAMSCheckpoint

Example: Transport5

Note that the string returned from function GetModelText() contains the entire model and data definition plus an additional demand multiplier and scalars for model and solve status but no solve statement:

...
Scalar bmult demand multiplier /1/;
...
demand(j) .. sum(i, x(i,j)) =g= bmult*b(j) ;
...
Scalar ms 'model status', ss 'solve status';
...

A list with eight different values for this demand multiplier is created:

double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };

For each entry of that list, a GAMSJob t5 is created using the GAMSWorkspace.AddJobFromString method. Besides the string which resets the demand multiplier bmult, specifies the solve statement, and assigns values to the scalars ms and ss, the checkpoint cp is passed as additional argument. This results in a GAMSJob combined from the checkpoint plus the content provided by the string.

The GAMSJob is run, echoing some interesting data from the OutDB using the GAMSDatabase.GetParameter and GAMSDatabase.GetVariable methods, the GAMSParameter.FindRecord and GAMSVariable.FindRecord methods plus the GAMSParameterRecord.Value property and the GAMSVariableRecord.Level property.

...
foreach (double b in bmultlist)
{
string b_formatted = b.ToString(CultureInfo.InvariantCulture);
GAMSJob t5 = ws.AddJobFromString("bmult=" + b_formatted + "; solve transport min z use lp; ms=transport.modelstat; ss=transport.solvestat;", cp);
t5.Run();
Console.WriteLine("Scenario bmult=" + b_formatted + ":");
Console.WriteLine(" Modelstatus: " + t5.OutDB.GetParameter("ms").FindRecord().Value);
Console.WriteLine(" Solvestatus: " + t5.OutDB.GetParameter("ss").FindRecord().Value);
Console.WriteLine(" Obj: " + t5.OutDB.GetVariable("z").FindRecord().Level);
}
...
GAMSParameter GetParameter(string parameterIdentifier)
new GAMSParameterRecord FindRecord(params string[] keys)
new GAMSVariableRecord FindRecord(params string[] keys)
Note
The value b is formatted using CultureInfo.InvariantCulture before embedding it in the GAMS statement text. Formatting a double with the current culture can produce a comma instead of a period as the decimal separator (e.g., on systems where the regional format uses ,), which would break the resulting GAMS statement.
Some demand multipliers cause infeasibility. Nevertheless, GAMS keeps the incumbent objective function value. Therefore the model status and the solve status provide important information to correctly interpret the solution.

Run multiple GAMSJobs in parallel using a GAMSCheckpoint

Example: Transport6

This example illustrates how to run the jobs known from Transport5 in parallel. The GAMSCheckpoint cp is initialized and a demand multiplier is introduced as before:

...
GAMSCheckpoint cp = ws.AddCheckpoint();
ws.AddJobFromString(GetModelText()).Run(cp);
double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };
...

Furthermore, a new object ioMutex is introduced that will be used to avoid mixed up output from the parallel jobs. For each element b from the list of demand multipliers, a delegate of the function RunScenario is called. Note that these calls are executed in parallel!

...
// run multiple parallel jobs using the created GAMSCheckpoint
Object ioMutex = new Object();
System.Threading.Tasks.Parallel.ForEach(bmultlist, delegate(double b) { RunScenario(ws, cp, ioMutex, b); });
...

In function RunScenario a GAMSJob is created and run just like in the preceding example of Transport5. The output section is also the same except for the fact that it is marked as critical section by the lock keyword. That means the delegates of RunScenario are running in parallel but the output block of different delegates cannot be executed in parallel since it is 'locked' by the same object ioMutex for all delegates.

...
static void RunScenario(GAMSWorkspace ws, GAMSCheckpoint cp, object ioMutex, double b)
{
string b_formatted = b.ToString(CultureInfo.InvariantCulture);
GAMSJob t6 = ws.AddJobFromString("bmult=" + b_formatted + "; solve transport min z use lp; ms=transport.modelstat; ss=transport.solvestat;", cp);
t6.Run();
// we need to make the output a critical section to avoid messed up report information
lock (ioMutex)
{
Console.WriteLine("Scenario bmult=" + b_formatted + ":");
Console.WriteLine(" Modelstatus: " + t6.OutDB.GetParameter("ms").FindRecord().Value);
Console.WriteLine(" Solvestatus: " + t6.OutDB.GetParameter("ss").FindRecord().Value);
Console.WriteLine(" Obj: " + t6.OutDB.GetVariable("z").FindRecord().Level);
}
}
...

While the output in Transport5 is strictly ordered subject to the order of the elements of bmultlist, in Transport6 the output blocks might change their order but the blocks describing one scenario are still appearing together due to the lock keyword.

For a further impression of the impact of the lock keyword, comment out the lock in Transport6 as follows, run again, and compare the output.

...
//lock (ioMutex)
//{
Console.WriteLine("Scenario bmult=" + b_formatted + ":");
Console.WriteLine(" Modelstatus: " + t6.OutDB.GetParameter("ms").FindRecord().Value);
Console.WriteLine(" Solvestatus: " + t6.OutDB.GetParameter("ss").FindRecord().Value);
Console.WriteLine(" Obj: " + t6.OutDB.GetVariable("z").FindRecord().Level);
//}
...

Create a GAMSModelInstance from a GAMSCheckpoint

Example: Transport7

In Transport7 the usage of GAMS::GAMSModelInstance is demonstrated.

At first checkpoint cp is created as in the preceding examples. Then the GAMSModelInstance mi is created using the GAMSCheckpoint.AddModelInstance method. Note that the GAMSJob again contains no solve statement and the demand multiplier is already included with default value 1.

...
GAMSCheckpoint cp = ws.AddCheckpoint();
GAMSJob t7 = ws.AddJobFromString(GetModelText());
t7.Run(cp);
...
GAMSModelInstance AddModelInstance(string modelInstanceName=null)

Modify a parameter of a GAMSModelInstance using GAMSModifier

Example: Transport7

A GAMSModelInstance uses a SyncDB to maintain the data. Using the GAMSDatabase.AddParameter method, bmult is defined as GAMSParameter and cplex is specified as solver. Afterwards, the GAMSModelInstance is instantiated with arguments opt and GAMSModifier bmult. The GAMSModifier means that bmult is modifiable while all other parameters, variables and equations of ModelInstance mi stay unchanged. The GAMSParameter.AddRecord method is used to assign a value to bmult that can be varied afterwards using the GAMSParameter.FirstRecord method to reproduce the well-known example with different demand multipliers.

...
GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
opt.AllModelTypes = "cplex";
mi.Instantiate("transport use lp min z", opt, new GAMSModifier(bmult));
bmult.AddRecord().Value = 1.0;
double[] bmultlist = new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 };
foreach (double b in bmultlist)
{
bmult.FirstRecord().Value = b;
mi.Solve();
Console.WriteLine("Scenario bmult=" + b + ":");
Console.WriteLine(" Modelstatus: " + mi.ModelStatus);
Console.WriteLine(" Solvestatus: " + mi.SolveStatus);
Console.WriteLine(" Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
}
...
GAMSParameter AddParameter(string identifier, int dimension, string explanatoryText="")
void Solve(SymbolUpdateType updateType=SymbolUpdateType.BaseCase, TextWriter output=null, GAMSModelInstanceOpt miOpt=null)
void Instantiate(string modelDefinition, params GAMSModifier[] modifiers)

Modify a variable of a GAMSModelInstance using GAMSModifier

Example: Transport7

A GAMSModelInstance is created just like in the next to last example. GAMSVariable x is created with upper bound as GAMSParameter xup. At the following instantiate method, GAMSModifier has three arguments. The first one says that x is modifiable, the second determines which part of the variable (lower bound, upper bound or level) can be modified, and the third specifies the GAMSParameter that holds the new value.

In the following loops, the upper bound of one link of the network is set to zero, which means that no transportation between the corresponding plant and market is possible, and the modified transportation problem is solved.

...
mi = cp.AddModelInstance();
GAMSVariable x = mi.SyncDB.AddVariable("x", 2, VarType.Positive, "");
GAMSParameter xup = mi.SyncDB.AddParameter("xup", 2, "upper bound on x");
mi.Instantiate("transport use lp min z", modifiers: new GAMSModifier(x,UpdateAction.Upper,xup));
foreach (GAMSSetRecord i in t7.OutDB.GetSet("i"))
foreach (GAMSSetRecord j in t7.OutDB.GetSet("j"))
{
xup.Clear();
xup.AddRecord(i.Key(0),j.Key(0)).Value = 0;
mi.Solve();
Console.WriteLine("Scenario link blocked: " + i.Key(0) + " - " + j.Key(0));
Console.WriteLine(" Modelstatus: " + mi.ModelStatus);
Console.WriteLine(" Solvestatus: " + mi.SolveStatus);
Console.WriteLine(" Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
}
...
GAMSSet GetSet(string setIdentifier)
GAMSVariable AddVariable(string identifier, int dimension, VarType varType, string explanatoryText="")
UpdateAction

Use a queue to solve multiple GAMSModelInstances in parallel

Example: Transport8

A GAMSCheckpoint cp is initialized from a GAMSJob. Then a queue that represents the different values of the demand multiplier is defined. A queue follows the first-in-first-out-principle. The objects queueMutex and ioMutex are used later to avoid messed up output. Then two delegates of the function ScenSolve that get the same queue as argument are called in parallel.

...
GAMSCheckpoint cp = ws.AddCheckpoint();
ws.AddJobFromString(GetModelText()).Run(cp);
Queue<double> bmultQueue = new Queue<double>(new double[] { 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 });
Object queueMutex = new Object();
Object ioMutex = new Object();
Parallel.For(0, 2, delegate(int i) { ScenSolve(ws, cp, bmultQueue, queueMutex, ioMutex); });
...

In function ScenSolve, a GAMSModelInstance is created and instantiated as in the preceding examples and bmult is made modifiable. GAMSCheckpoint.AddModelInstance is called inside the same queueMutex lock used for dequeuing, since it is not safe to call concurrently from multiple threads. The two delegates of the function extract the elements of the queue using bmultQueue.Dequeue. Note that one of the thread-safe solvers is used. Once the queue is empty the loop terminates.

private static void ScenSolve(GAMSWorkspace ws, GAMSCheckpoint cp, Queue<double> bmultQueue, Object queueMutex, Object ioMutex)
{
lock (queueMutex)
{
mi = cp.AddModelInstance();
}
GAMSParameter bmult = mi.SyncDB.AddParameter("bmult", "demand multiplier");
GAMSOptions opt = ws.AddOptions();
opt.AllModelTypes = "cplex";
mi.Instantiate("transport use lp min z", opt, new GAMSModifier(bmult));
bmult.AddRecord().Value = 1.0;
while (true)
{
double b;
// dynamically get a bmult value from the queue instead of passing it to the different threads at creation time
lock (queueMutex)
{
if(0 == bmultQueue.Count)
return;
b = bmultQueue.Dequeue();
}
bmult.FirstRecord().Value = b;
mi.Solve();
// we need to make the output a critical section to avoid messed up report informations
lock (ioMutex)
{
Console.WriteLine("Scenario bmult=" + b + ":");
Console.WriteLine(" Modelstatus: " + mi.ModelStatus);
Console.WriteLine(" Solvestatus: " + mi.SolveStatus);
Console.WriteLine(" Obj: " + mi.SyncDB.GetVariable("z").FindRecord().Level);
}
}
}
new GAMSParameterRecord FirstRecord()

Fill a GAMSDatabase by reading from MS Access

Example: Transport9

This example illustrates how to import data from Microsoft Access to a GAMSDatabase. Unlike .NET Framework, .NET 10 does not include System.Data.OleDb out of the box, so one first needs to add it to the project as a NuGet package (e.g., via Manage NuGet Packages in Visual Studio Code, or by adding <PackageReference Include="System.Data.OleDb" Version="9.0.0" /> to the .csproj file). A function ReadFromAccess that finally returns a GAMSDatabase is called as shown below.

...
GAMSDatabase db = ReadFromAccess(ws);
...

The data that is read can be found in <GAMS system directory>\apifiles\Data\transport.accdb. It might be helpful to open this file for a better understanding. The function begins with the creation of an empty GAMSDatabase. Afterwards, the MS Access database is connected by first specifying the provider and then defining the aforementioned file, located relative to GAMSWorkspace.SystemDirectory as data source. The OleDbConnection represents an open connection to a data source. The following lines initialize the connection and use a try and a catch block for potential exceptions, i.e., errors that occur during application execution. To finally read in GAMS sets and parameters, the functions ReadSet and ReadParameter are called. Several classes of the System.Data.OleDb namespace are documented here.

static GAMSDatabase ReadFromAccess(GAMSWorkspace ws)
{
// connect to database
string strAccessConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Path.Combine(ws.SystemDirectory, @"apifiles/Data/transport.accdb");
OleDbConnection connection = null;
try
{
connection = new OleDbConnection(strAccessConn);
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
Environment.Exit(1);
}
// read GAMS sets
ReadSet(connection, db, "SELECT Plant FROM Plant", "i", 1, "canning plants");
ReadSet(connection, db, "SELECT Market FROM Market", "j", 1, "markets");
// read GAMS parameters
ReadParameter(connection, db, "SELECT Plant,Capacity FROM Plant", "a", 1, "capacity of plant i in cases");
ReadParameter(connection, db, "SELECT Market,Demand FROM Market", "b", 1, "demand at market j in cases");
ReadParameter(connection, db, "SELECT Plant,Market,Distance FROM Distance", "d", 2, "distance in thousands of miles");
return db;
}

The function ReadSet incorporates a try and a catch block. In the try block, the reading from the MS Access file is prepared. Then a set symbol is added to the GAMSDatabase and filled with the data from the MS Access file. The function ReadParameter works quite similar.

static void ReadSet(OleDbConnection connect, GAMSDatabase db, string strAccessSelect, string setName, int setDim, string setExp = "")
{
try
{
OleDbCommand cmd = new OleDbCommand(strAccessSelect, connect);
connect.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.FieldCount != setDim)
{
Console.WriteLine("Number of fields in select statement does not match setDim");
Environment.Exit(1);
}
GAMSSet i = db.AddSet(setName, setDim, setExp);
string[] keys = new string[setDim];
while (reader.Read())
{
for (int idx = 0; idx < setDim; idx++)
keys[idx] = reader.GetString(idx);
i.AddRecord(keys);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
Environment.Exit(1);
}
finally
{
connect.Close();
}
}
GAMSSet AddSet(string identifier, int dimension, string explanatoryText="", SetType setType=SetType.multi)

Once all the data is read, one can create a GAMSJob from the GAMSDatabase and run it as usual.

Fill a GAMSDatabase by reading from MS Excel

Example: Transport10

This example illustrates how to read data from Excel, or to be more specific, from <GAMS system directory>\apifiles\Data\transport.xlsx. The model is given as string without data like in many examples before. At first, one has to add

using Excel = Microsoft.Office.Interop.Excel;

to the preamble to be able to use the Microsoft.Office.Interop.Excel namespace. Then the excelApp is defined as Excel application using the implicit variable type var, the aforementioned file is used as workbook wb, and the Excel range is defined. The range can represent a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3-D range.

...
var excelApp = new Excel.Application();
Excel.Workbook wb = excelApp.Workbooks.Open(Path.Combine(ws.SystemDirectory, @"apifiles/Data/transport.xlsx"));
Excel.Range range;
...

The following lines address the different worksheets and read in the contained data. Afterwards, an errorcheck ensures that the number of plants and markets is the same in all worksheets.

...
Excel.Worksheet capacity = (Excel.Worksheet)wb.Worksheets.get_Item("capacity");
range = capacity.UsedRange;
Array capacityData = (Array)range.Cells.Value;
int iCount = capacity.UsedRange.Columns.Count;
Excel.Worksheet demand = (Excel.Worksheet)wb.Worksheets.get_Item("demand");
range = demand.UsedRange;
Array demandData = (Array)range.Cells.Value;
int jCount = range.Columns.Count;
Excel.Worksheet distance = (Excel.Worksheet)wb.Worksheets.get_Item("distance");
range = distance.UsedRange;
Array distanceData = (Array)range.Cells.Value;
// number of markets/plants have to be the same in all spreadsheets
Debug.Assert((range.Columns.Count - 1) == jCount && (range.Rows.Count - 1) == iCount,
"Size of the spreadsheets doesn't match");
wb.Close();
...

If the steps above are not clear, adding the following output section right after wb.Close() might be helpful to understand where which data is stored.

...
for (int ii = 1; ii <= iCount; ii++)
{
Console.WriteLine("capacityData(1, " + ii + ") = " + capacityData.GetValue(1, ii));
Console.WriteLine("capacityData(2, " + ii + ") = " + capacityData.GetValue(2, ii));
}
for (int jj = 1; jj <= jCount; jj++)
{
Console.WriteLine("demandData(1, " + jj + ") = " + demandData.GetValue(1, jj));
Console.WriteLine("demandData(2, " + jj + ") = " + demandData.GetValue(2, jj));
}
for (int ii = 1; ii <= iCount; ii++)
{
for (int jj = 1; jj <= jCount; jj++)
Console.WriteLine("distanceData("+ (ii+1) + "," + (jj+1) +") = " + distanceData.GetValue(ii+1, jj+1));
}
...

Now the GAMSWorkspace and a GAMSDatabase can be created as usual and the database can be filled with the workbook data as follows:

...
GAMSDatabase db = ws.AddDatabase();
GAMSSet i = db.AddSet("i", 1, "Plants");
GAMSSet j = db.AddSet("j", 1, "Markets");
GAMSParameter capacityParam = db.AddParameter("a", "Capacity", i);
GAMSParameter demandParam = db.AddParameter("b", "Demand", j);
GAMSParameter distanceParam = db.AddParameter("d", "Distance", i, j);
for (int ic = 1; ic <= iCount; ic++)
{
i.AddRecord((string)capacityData.GetValue(1, ic));
capacityParam.AddRecord((string)capacityData.GetValue(1, ic)).Value = (double)capacityData.GetValue(2, ic);
}
for (int jc = 1; jc <= jCount; jc++)
{
j.AddRecord((string)demandData.GetValue(1, jc));
demandParam.AddRecord((string)demandData.GetValue(1, jc)).Value = (double)demandData.GetValue(2, jc);
for (int ic = 1; ic <= iCount; ic++)
{
distanceParam.AddRecord((string)distanceData.GetValue(ic + 1, 1), (string)distanceData.GetValue(1, jc + 1)).Value = (double)distanceData.GetValue(ic + 1, jc + 1);
}
}
...

Note that the C# variable names holding a GAMSSet/GAMSParameter do not need to match the GAMS identifier passed as the first argument, though in this example they do. Now the database can finally be set up and the GAMSJob be run as usual.

...
using (GAMSOptions opt = ws.AddOptions())
{
GAMSJob t10 = ws.AddJobFromString(GetModelText());
opt.Defines.Add("gdxincname", db.Name);
opt.AllModelTypes = "xpress";
t10.Run(opt, db);
foreach (GAMSVariableRecord rec in t10.OutDB.GetVariable("x"))
Console.WriteLine("x(" + rec.Key(0) + "," + rec.Key(1) + "): level=" + rec.Level + " marginal=" + rec.Marginal);
}
...

Create and use a save/restart file

Example: Transport11

Transport11 demonstrates how to create and use a save/restart file. Usually such a file should be supplied by an application provider, but this example creates one for demonstration purpose. Note that the restart is launched from a GAMSCheckpoint.

The main function starts with the creation of a folder called tmp that internally is denoted as wDir. Then the function CreateSaveRestart is called.

...
string wDir = Path.Combine(".", "tmp");
CreateSaveRestart(Path.Combine(wDir, "tbase"));
...

In function CreateSaveRestart the path of the file (wDir) is given as working directory argument. Then a GAMSJob is created from a string. Note that the string given via GetBaseModelText() contains the basic definitions of sets without giving them a content (that is what $onempty is used for). Afterwards, a GAMSOption is specified to only compile the job but do not execute it. Then a checkpoint cp is created that is initialized by the following run of the GAMSJob and stored in the file given as argument to the function. This becomes possible because the AddCheckpoint method accepts identifiers as well as file names as argument.

static void CreateSaveRestart(string cpFileName)
{
if (Environment.GetCommandLineArgs().Length > 1)
ws = new GAMSWorkspace(workingDirectory: Path.GetDirectoryName(cpFileName), systemDirectory: Environment.GetCommandLineArgs()[1]);
else
ws = new GAMSWorkspace(workingDirectory: Path.GetDirectoryName(cpFileName));
GAMSJob j1 = ws.AddJobFromString(GetBaseModelText());
GAMSOptions opt = ws.AddOptions();
opt.Action = GAMSOptions.EAction.CompileOnly;
GAMSCheckpoint cp = ws.AddCheckpoint(Path.GetFileName(cpFileName));
j1.Run(opt, cp);
opt.Dispose();
}

So what one should keep in mind, before returning to further explanations of the main function, is that now the file tbase in folder tmp, which is denoted as wDir, contains a checkpoint. Now in the main function, some data is defined using C# data structures as in Transport4, before the GAMSWorkspace is created with working directory wDir.

...
GAMSWorkspace ws;
if (Environment.GetCommandLineArgs().Length > 1)
ws = new GAMSWorkspace(workingDirectory: wDir, systemDirectory: Environment.GetCommandLineArgs()[1]);
else
ws = new GAMSWorkspace(workingDirectory: wDir);
...

Afterwards the GAMSDatabase is set up as in Transport4. Once this is done, a GAMSJob is run using this data plus the checkpoint stored in file tbase.

...
GAMSCheckpoint cpBase = ws.AddCheckpoint("tbase");
using (GAMSOptions opt = ws.AddOptions())
{
GAMSJob t4 = ws.AddJobFromString(GetModelText(), cpBase);
opt.Defines.Add("gdxincname", db.Name);
opt.AllModelTypes = "xpress";
t4.Run(opt, db);
foreach (GAMSVariableRecord rec in t4.OutDB.GetVariable("x"))
Console.WriteLine("x(" + rec.Key(0) + "," + rec.Key(1) + "): level=" + rec.Level + " marginal=" + rec.Marginal);
}
...

Note that the string from which the job t4 is created is different to the one used to prepare the checkpoint stored in tbase and is only responsible for reading in the data from the GAMSDatabase correctly. The entire model definition is delivered by the checkpoint cpBase, which is equal to the one saved in tbase.