GAMS [ Home | Downloads | Documentation | Solvers | APIs | Tools | Model Libraries | Resources | Sales | Support | Contact Us | Search ]

GAMS Python API - Tutorial and Examples
Tutorial

Table of Contents

The goal of this tutorial is to provide a compact overview of the basic functionality of the GAMS Python 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

The object oriented GAMS Python API is built on top of the different low level component API's and provides convenient access to GAMS from within Python. Examples using the API are located in apifiles/Python while the API itself is found in apifiles/Python/api for Python 2.7, in apifiles/Python/api_26 for Python 2.6 (Windows and Linux only), and in apifiles/Python/api_34 for Python 3.4 (Windows and Linux only). The bitness of the Python version has to be the same as the bitness of the GAMS system. Assuming that the current directory is <Path/To/GAMS>/apifiles/Python the API can be used as follows:

  • Installing the API and the required low level API's to Python site-packages:
    cd api && python setup.py install && cd ..
    
  • Using the API without installing:
    export PYTHONPATH=api  (on Windows: set PYTHONPATH=api)
    
  • Running the transport1.py example:
    python transport1.py 

Specifying a GAMS System Directory

There are several ways to specify which system directory should be used. On all platforms, the system directory can be specified in the GamsWorkspace constructor. If no system directory is specified by the user, The API tries to find one automatically:

  • Windows: Try to find a system directory in the Windows registry.
  • Linux: Try to find a system directory in the PATH first. If none was found, search LD_LIBRARY_PATH.
  • OS X: Try to find a system directory in the PATH first. If none was found, search DYLD_LIBRARY_PATH.

The environment variables can be set as follows:

Linux:

export LD_LIBRARY_PATH=<Path/To/GAMS>:$LD_LIBRARY_PATH

OS X:

export DYLD_LIBRARY_PATH=<Path/To/GAMS>:$DYLD_LIBRARY_PATH

Linux/OS X:

export PATH=<Path/To/GAMS>:$PATH

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 in the How to use the API section.

How to use the API

The GAMS distribution provides several examples that illustrate the usage of the Python API. [GAMSDIR]/apifiles/Python contains multiple examples dealing with the well-known transportation problem. In further course of this tutorial we discuss these examples step by step and introduce new elements of the API in detail.

We recommend to open the aforementioned files to gain a complete overview of the examples. Down below we explain the examples with the help of selected code snippets.

How to import packages/modules from the GAMS Python API (Transport1)

If you followed the instructions from the Getting started section and installed the GAMS Python API there should be a directory [PYTHONDIR]\Lib\site-packages\gams that contains the required packages and modules. We simply import all of them using

from gams import *

Conventional Python packages/modules can by imported like that:

import os
import sys

How to choose the GAMS system (Transport1)

By default the GAMS system is determined automatically. In case of having multiple GAMS systems on your machine, the desired system can be specified via an additional argument when the workspace is created. If we type python transport1.py C:\GAMS\win64\24.0 we use the 64-bit version of GAMS 24.0 to run transport1.py even if our default GAMS system might be a different one. This is managed by the following code:

...
if len(sys.argv) > 1:
ws = GamsWorkspace(system_directory = sys.argv[1])
else:
ws = GamsWorkspace()
...

Remember that the bitness of the GAMS system has to match the bitness of your Python version.

How to run a GamsJob from file (Transport1)

At first we create our workspace using ws = GamsWorkspace(). Afterwards we load the trnsport model from the GAMS model library which puts the corresponding gms file in our working directory. Apparently you can create a GamsJob with any other gms file you might have created on your own as long as it is located in the current working directory. Then the GamsJob t1 can be defined using the add_job_from_file method and afterwards we run the job.

...
ws.gamslib("trnsport")
t1 = ws.add_job_from_file("trnsport.gms")
t1.run()
...

How to retrieve a solution from an output database (Transport1)

The following lines create the solution output and illustrate the usage of the GamsJob.out_db property to get access to the GamsDatabase created by the run method. To retrieve the content of variable x we use squared brackets that internally call the get_symbol method.

...
for rec in t1.out_db["x"]:
print "x(" + rec.keys[0] + "," + rec.keys[1] + "): level=" + str(rec.level) + " marginal=" + str(rec.marginal)
...

Note that instead of using the squared brackets we could also use

...
for rec in t1.out_db.get_symbol("x"):
...

How to specify the solver using GamsOptions (Transport1)

The solver can be specified via the GamsOptions class and the GamsWorkspace.add_options method. The GamsOptions.all_model_types property sets xpress as default solver for all model types that can be handled by the solver. Then we run our GamsJob t1 with the new GamsOption.

...
opt = ws.add_options()
opt.all_model_types = "xpress"
t1.run(opt)
...

How to run a job with a solver option file (Transport1)

At first we create the file xpress.opt with content algorithm=barrier which will be used as solver option file and is stored in the current working directory. Afterwards we use a GamsOption just like in the preceding example and set GamsOption.optfile property to 1 to tell the solver to look for a solver option file.

...
file = open(os.path.join(ws.working_directory, "xpress.opt"), "w")
file.write("algorithm=barrier")
file.close()
opt.optfile = 1
t1.run(opt)
...

How to use include files (Transport2)

In this example, as in many succeeding, the data text and the model text are separated into two different strings. Note that these strings accessed via functions get_data_text and get_model_text are using GAMS syntax. At first we write an include file tdata.gms that contains the data but not the model text and save it in our current working directory.

...
file = open(os.path.join(ws.working_directory, "tdata.gms"), "w")
file.write(get_data_text())
file.close()
...

Afterwards we create a GamsJob using the GamsWorkspace.add_job_from_string method. GamsOptions.defines is used like the 'double dash' GAMS parameters, i.e. it corresponds to --incname=tdata on the command line where incname is used as name for the include file in get_model_text as shown below.

...
t2 = ws.add_job_from_string(get_model_text())
opt = ws.add_options()
opt.defines["incname"] = "tdata"
t2.run(opt)
...

The string get_model_text contains the following lines to read in the data.

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

How to read data from string and export to GDX (Transport3)

We read the data from the string accessed via function get_data_text. Note that this contains no model but only data definition in GAMS syntax. By running the corresponding GamsJob a GamsDatabase is created that is available via the GamsJob.out_db property. We can use the GamsDatabase.export method to write the content of this database to a gdx file tdata.gdx in the current working directory.

...
t3 = ws.add_job_from_string(get_data_text())
t3.run()
t3.out_db.export(os.path.join(ws.working_directory, "tdata.gdx"))
...

How to run a job using data from GDX (Transport3)

This works quite similar to the usage of an include file explained in How to use include files (Transport2).

...
t3 = ws.add_job_from_string(get_model_text())
opt = ws.add_options()
opt.defines["gdxincname"] = "tdata"
opt.all_model_types = "xpress"
t3.run(opt)
...

Note that there are some minor changes in get_model_text compared to preceding examples due to the usage of a gdx 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
...

How to run a job using implicit database communication (Transport3)

This example does basically the same as the two preceding examples together. We create two GamsJobs t3a and t3b where the first one contains only the data and the second one contains only the model without data. After running t3a the corresponding out_db 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.

...
t3a = ws.add_job_from_string(get_data_text())
t3b = ws.add_job_from_string(get_model_text())
t3a.run()
opt.defines["gdxincname"] = t3a.out_db.name
t3b.run(opt, databases=t3a.out_db)
...

How to define data using Python data structures (Transport4)

We use squared brackets (Python Lists) to define the sets and curly brackets (Python Dictionaries) for the parameter definition.

...
plants = [ "Seattle", "San-Diego" ]
markets = [ "New-York", "Chicago", "Topeka" ]
capacity = { "Seattle": 350.0, "San-Diego": 600.0 }
demand = { "New-York": 325.0, "Chicago": 300.0, "Topeka": 275.0 }
distance = { ("Seattle", "New-York") : 2.5,
("Seattle", "Chicago") : 1.7,
("Seattle", "Topeka") : 1.8,
("San-Diego", "New-York") : 2.5,
("San-Diego", "Chicago") : 1.8,
("San-Diego", "Topeka") : 1.4
}
...

How to prepare a GamsDatabase from Python data structures (Transport4)

At first we create an empty GamsDatabase db using the GamsWorkspace.add_database method. Afterwards we prepare the database. To add a set to the database we use the GamsSet class and the GamsDatabase.add_set method with arguments describing the identifier, dimension and explanatory text. To add the records to the database we iterate over the elements of our Python data structure and add them by using the GamsSet.add_record method.

For parameters the procedure is pretty much the same. Note that the table that specifies the distances in GAMS can be treated as parameter with dimension 2.

The GamsJob can be run like explained in the preceding example How to run a job using implicit database communication (Transport3).

...
db = ws.add_database()
i = db.add_set("i", 1, "canning plants")
for p in plants:
i.add_record(p)
j = GamsSet(db, "j", 1, "markets")
for m in markets:
j.add_record(m)
a = GamsParameter(db, "a", 1, "capacity of plant i in cases")
for p in plants:
a.add_record(p).value = capacity[p]
b = GamsParameter(db, "b", 1, "demand at market j in cases")
for m in markets:
b.add_record(m).value = demand[m]
d = GamsParameter(db, "d", 2, "distance in thousands of miles")
for k, v in distance.iteritems():
d.add_record(k).value = v
f = GamsParameter(db, "f", 0, "freight in dollars per case per thousand miles")
f.add_record().value = 90
t4 = GamsJob(ws, source=get_model_text())
opt = GamsOptions(ws)
opt.defines["gdxincname"] = db.name
opt.all_model_types = "xpress"
t4.run(opt, databases = db)
...

How to initialize a GamsCheckpoint by running a GamsJob (Transport5)

The following lines of code conduct several operations. While the first line simply creates a GamsCheckpoint, the second one uses the GamsWorkspace.add_job_from_string method to create a GamsJob containing the model text and data but no solve statement. Afterwards the run method gets the GamsCheckpoint as argument. That means the GamsCheckpoint cp captures the state of the GamsJob.

...
cp = ws.add_checkpoint()
t5 = ws.add_job_from_string(get_model_text())
t5.run(checkpoint=cp)
...

How to initialize a GamsJob from a GamsCheckpoint (Transport5)

Note that the string returned from function get_model_text 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';
...

In Transport5 we create a list with eight different values for this demand multiplier.

...
bmultlist = [ 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 ]
...

For each entry of that list we create a GamsJob t5 using the GamsWorkspace.add_job_from_string method. Besides another string which resets the demand multiplier bmult, specifies the solve statement and assigns values to the scalars ms and ss we pass the checkpoint cp as additional argument. This results in a GamsJob combined from the checkpoint plus the content provided by the string.

We run the GamsJob and print some interesting data from the out_db.

...
for b in bmultlist:
t5 = ws.add_job_from_string("bmult=" + str(b) + "; solve transport min z use lp; ms=transport.modelstat; ss=transport.solvestat;", cp)
t5.run()
print "Scenario bmult=" + str(b) + ":"
print " Modelstatus: " + str(t5.out_db["ms"].find_record().value)
print " Solvestatus: " + str(t5.out_db["ss"].find_record().value)
print " Obj: " + str(t5.out_db["z"].find_record().level)
...

NOTE: Some of the demand multipliers cause infeasibility. Nevertheless, GAMS keeps the incumbent objective function value. Therefore the model status and the solve status provide important information for a correct solution interpretation.

How to run multiple GamsJobs in parallel using a GamsCheckpoint (Transport6)

This example illustrates how to run the jobs known from Transport5 in parallel. We initialize the GamsCheckpoint cp and introduce a demand multiplier as we did before :

...
cp = ws.add_checkpoint()
t6 = ws.add_job_from_string(get_model_text())
t6.run(checkpoint=cp)
bmultlist = [ 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 ]
...

Furthermore, we introduce a lock object io_lock that will be used to avoid mixed up output from the parallel jobs. We create one scenario for each entry of bmultlist and cause a thread to begin execution.

...
io_lock = threading.Lock()
threads = {}
for b in bmultlist:
threads[b] = threading.Thread(target=run_scenario, args=(ws, cp, io_lock, b))
threads[b].start()
for b in bmultlist:
threads[b].join()
...

In function run_scenario a GamsJob t6 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 'locked' by the object io_lock which means that the output section cannot be executed simultaneously for multiple demand multipliers.

...
def run_scenario(workspace, checkpoint, io_lock, b):
t6 = workspace.add_job_from_string("bmult=" + str(b) + "; solve transport min z use lp; ms=transport.modelstat; ss=transport.solvestat;", checkpoint)
t6.run()
# we need to make the ouput a critical section to avoid messed up report informations
io_lock.acquire()
print "Scenario bmult=" + str(b) + ":"
print " Modelstatus: " + str(t6.out_db["ms"][()].value)
print " Solvestatus: " + str(t6.out_db["ss"][()].value)
print " Obj: " + str(t6.out_db["z"][()].level)
io_lock.release()
...

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 io_lock object.

How to create a GamsModelInstance from a GamsCheckpoint (Transport7)

In Transport7 the usage of GamsModelInstance is demonstrated.

At first checkpoint cp is created as in the preceding examples. Note that the GamsJob t7 again contains no solve statement and the demand multiplier is already included with default value 1. We create the GamsModelInstance mi using the GamsCheckpoint.add_modelinstance method.

...
cp = ws.add_checkpoint()
t7 = ws.add_job_from_string(get_model_text())
t7.run(checkpoint=cp)
mi = cp.add_modelinstance()
...

How to modify a parameter of a GamsModelInstance using GamsModifier (Transport7)

A GamsModelInstance uses a sync_db to maintain the data. We define bmult as GamsParameter using the GamsDatabase.add_parameter method and specify gurobi as solver. Afterwards the GamsModelInstance is instantiated with 3 arguments, the solve statement, GamsModifier bmult and GamsOptions opt. The GamsModifier means that bmult is modifiable while all other parameters, variables and equations of GamsModelInstance mi stay unchanged. We use the GamsParameter.add_record method to assign a value to bmult. That value can be varied afterwards using the GamsParameter.first_record method to reproduce our well-known example with different demand multipliers.

...
bmult = mi.sync_db.add_parameter("bmult", 0, "demand multiplier")
opt = ws.add_options()
opt.all_model_types = "gurobi"
mi.instantiate("transport use lp min z", GamsModifier(bmult), opt)
bmult.add_record().value = 1.0
bmultlist = [ 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3 ]
for b in bmultlist:
bmult.first_record().value = b
mi.solve()
print "Scenario bmult=" + str(b) + ":"
print " Modelstatus: " + str(mi.model_status)
print " Solvestatus: " + str(mi.solver_status)
print " Obj: " + str(mi.sync_db.get_variable("z").find_record().level)
...

How to modify a variable of a GamsModelInstance using GamsModifier (Transport7)

We create a GamsModelInstance using the GamsCheckpoint.add_modelinstance method. Afterwards we define x as GamsVariable and a GamsParameter xup that will be used as upper bound for x. At the following instantiate method GamsModifier has 3 arguments. The first one says that x is modifieable, 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 this case xup.

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

...
mi = cp.add_modelinstance()
x = mi.sync_db.add_variable("x", 2, VarType.Positive)
xup = mi.sync_db.add_parameter("xup", 2, "upper bound on x")
mi.instantiate("transport use lp min z", GamsModifier(x, UpdateAction.Upper, xup))
mi.solve()
for i in t7.out_db["i"]:
for j in t7.out_db["j"]:
xup.clear()
xup.add_record((i.keys[0],j.keys[0])).value = 0
mi.solve()
print "Scenario link blocked: " + i.keys[0] + " - " + j.keys[0]
print " Modelstatus: " + str(mi.model_status)
print " Solvestatus: " + str(mi.solver_status)
print " Obj: " + str(mi.sync_db["z"].find_record().level)
...

How to use a queue to solve multiple GamsModelInstances in parallel (Transport8)

We initialize a GamsCheckpoint cp from a GamsJob. Then we define a list that represents the different values of the demand multiplier. That list will be used like a queue where we extract the last element first. The objects list_lock and io_lock are used later to avoid multiple reading of one demand multiplier and messed up output. Then we call function scen_solve multiple times in parallel. The number of parallel calls is specified by nr_workers.

...
cp = ws.add_checkpoint()
t8 = ws.add_job_from_string(get_model_text())
t8.run(checkpoint=cp)
bmult_list = [ 1.3, 1.2, 1.1, 1.0, 0.9, 0.8, 0.7, 0.6 ]
list_lock = threading.Lock()
io_lock = threading.Lock()
# start 2 threads
nr_workers = 2
threads = {}
for i in range(nr_workers):
threads[i] = threading.Thread(target=scen_solve, args=(ws, cp, bmult_list, list_lock, io_lock))
threads[i].start()
for i in range(nr_workers):
threads[i].join()

In function scen_solve we create and instantiate a GamsModelInstance as in the preceding examples and make parameter bmult modifiable. Note that we choose cplexd as solver because it is thread safe (gurobi would also be possible).

We have two critical sections that are locked by the objects list_lock and io_lock. Note that the pop method removes and returns the last element from the list and deletes it. Once the list is empty the loop terminates.

...
def scen_solve(workspace, checkpoint, bmult_list, list_lock, io_lock):
mi = checkpoint.add_modelinstance()
bmult = mi.sync_db.add_parameter("bmult", 0, "demand multiplier")
opt = ws.add_options()
opt.all_model_types = "cplexd"
# instantiate the GamsModelInstance and pass a model definition and GamsModifier to declare bmult mutable
mi.instantiate("transport use lp min z", GamsModifier(bmult), opt)
bmult.add_record().value = 1.0
while True:
# dynamically get a bmult value from the queue instead of passing it to the different threads at creation time
list_lock.acquire()
if 0 == len(bmult_list):
list_lock.release()
return
b = bmult_list.pop()
list_lock.release()
bmult.first_record().value = b
mi.solve()
# we need to make the ouput a critical section to avoid messed up report informations
io_lock.acquire()
print "Scenario bmult=" + str(b) + ":"
print " Modelstatus: " + str(mi.model_status)
print " Solvestatus: " + str(mi.solver_status)
print " Obj: " + str(mi.sync_db.get_variable("z").find_record().level)
io_lock.release()
...

How to fill a GamsDatabase by reading from MS Access (Transport9)

This example illustrates how to import data from Microsoft Access to a GamsDatabase. There are a few prerequisites required to run Transport9 successfully.

  • We import pyodbc which can be downloaded from http://code.google.com/p/pyodbc/.
  • Note that an architecture mismatch might cause problems. The bitness of your MS Access, Python, pyodbc and GAMS should be identical.

We call a function read_data_from_access that finally returns a GamsDatabase as shown below.

...
...

The function read_from_access begins with the creation of an empty database. Afterwards we set up a connection to the MS Access database transport.accdb which can be found in [GAMSDIR]\apifiles\Data. To finally read in GAMS sets and parameters we call the functions read_set and read_parameter that are explained down below.

...
db = ws.add_database()
# connect to database
str_access_conn = 'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=..\\Data\\transport.accdb'
try:
connection = pyodbc.connect(str_access_conn)
except Exception as ex:
print "Error: Failed to create a database connection. \n {0}".format(ex)
sys.exit(1)
# read GAMS sets
read_set(connection, db, "SELECT Plant FROM plant", "i", 1, "canning plants")
read_set(connection, db, "SELECT Market FROM Market", "j", 1, "markets")
# read GAMS parameters
read_parameter(connection, db, "SELECT Plant,Capacity FROM Plant", "a", 1, "capacity of plant i in cases")
read_parameter(connection, db, "SELECT Market,Demand FROM Market", "b", 1, "demand at market j in cases")
read_parameter(connection, db, "SELECT Plant,Market,Distance FROM Distance", "d", 2, "distance in thousands of miles")
connection.close()
return db
...

The function read_set adds a set to the GamsDatabase that is filled with the data from the MS Access file afterwards. The function read_parameter works quite similar.

...
def read_set(connection, db, query_string, set_name, set_dim, set_exp=""):
try:
cursor = connection.cursor()
cursor.execute(query_string)
data = cursor.fetchall()
if len(data[0]) != set_dim:
print "Number of fields in select statement does not match setDim"
sys.exit(1)
i = db.add_set(set_name, set_dim, set_exp)
for row in data:
keys = []
for key in row:
keys.append(str(key))
i.add_record(keys)
except Exception as ex:
print "Error: Failed to retrieve the required data from the DataBase.\n{0}".format(ex)
sys.exit(1)
finally:
cursor.close()
...

Once we read in all the data we can create a GamsJob from the GamsDatabase and run it as usual.

How to fill a GamsDatabase by reading from MS Excel (Transport10)

This example illustrates how to read data from Excel, or to be more specific, from [GAMSDIR]\apifiles\Data\transport.xls.

At first you have to download an additional package from https://pypi.python.org/pypi/xlrd, e.g. to C:\Users\[USERNAME]\Downloads. Unzip the package and run the following code from command line:

cd C:\Users\[Username]\Downloads\xlrd-0.9.2 && python setup.py install && cd [GAMSDIR]\apifiles\Python

Now you should be able to find the directory xlrd in [PYTHONDIR]\Lib\site-packages and to run transport10.

In transport10 the model is given as string without data like in many examples before and the Excel file transport.xls is located at [GAMSDIR]\apifiles\Data. At first we define the workbook to read from and the different sheet names. To ensure to have the same number of markets and plants in all spreadsheets, we conduct a little test that checks for the number of rows and columns. Our workspace is only created if this test yields no errors.

...
wb = open_workbook("..\\Data\\transport.xls")
capacity = wb.sheet_by_name("capacity")
demand = wb.sheet_by_name("demand")
distance = wb.sheet_by_name("distance")
# number of markets/plants have to be the same in all spreadsheets
assert (distance.ncols-1 == demand.ncols) and (distance.nrows-1 == capacity.ncols), \
"Size of the spreadsheets doesn't match"
...

Now we can create a GamsDatabase and read in the data contained in the different worksheets. We iterate over the columns and read in the set names and the corresponding parameter values.

...
db = ws.add_database()
i = db.add_set("i", 1, "Plants")
j = db.add_set("j", 1, "Markets")
capacity_param = db.add_parameter("a", 1, "Capacity")
demand_param = db.add_parameter("b", 1, "Demand")
distance_param = db.add_parameter("d", 2, "Distance")
for cx in range(capacity.ncols):
i.add_record(str(capacity.cell_value(rowx=0, colx=cx)))
capacity_param.add_record(str(capacity.cell_value(rowx=0, colx=cx))).value = capacity.cell_value(rowx=1, colx=cx)
for cx in range(demand.ncols):
j.add_record(str(demand.cell_value(rowx=0, colx=cx)))
demand_param.add_record(str(demand.cell_value(rowx=0, colx=cx))).value = demand.cell_value(rowx=1, colx=cx)
for cx in range(1, distance.ncols):
for rx in range(1, distance.nrows):
keys = ( str(distance.cell_value(rowx=rx, colx=0)), str(distance.cell_value(rowx=0, colx=cx)) )
distance_param.add_record(keys).value = distance.cell_value(rowx=rx, colx=cx)
...

Note that we can name sets and parameters just like in the database but we don't have to. Now we can run our GamsJob as usual.

...
t10 = ws.add_job_from_string(get_model_text())
opt = ws.add_options()
opt.defines["gdxincname"] = db.name
opt.all_model_types = "xpress"
t10.run(opt, databases=db)
for rec in t10.out_db["x"]:
print "x(" + rec.keys[0] + "," + rec.keys[1] + "): level=" + str(rec.level) + " marginal=" + str(rec.marginal)
...

How to create and use a save/restart file (Transport11)

In Transport11 we demonstrate how to create and use a save/restart file. Usually such a file should be supplied by an application provider but in this example we create one for demonstration purpose. Note that the restart is launched from a GamsCheckpoint.

We create a directory tmp with internal identifier w_dir in the directory we are currently in (usually [GAMSDIR]\apifiles\Python). This file will be used as working directory later. From the main function we call the function create_save_restart giving it directory tmp and the desired name for the save/restart file (tbase) as arguments.

...
w_dir = os.path.join(".", "tmp")
create_save_restart(os.path.join(w_dir, "tbase"));
...

In function create_save_restart we create a workspace with the given working directory (w_dir refers to tmp). Then we create a GamsJob from a string. Note that the string given via get_base_model_text contains the basic definitions of sets without giving them a content (that is what $onempty is used for). Afterwards we specify a GamsOption to only compile the job but do not execute it. Then we create a checkpoint cp that is initialized by the following run of the GamsJob and stored in the file given as argument to the function, in our case tbase. This becomes possible because the add_checkpoint method accepts identifiers as well as file names as argument.

...
def create_save_restart(cp_file_name):
if len(sys.argv) > 1:
ws = GamsWorkspace(os.path.dirname(cp_file_name), sys.argv[1])
else:
ws = GamsWorkspace(os.path.dirname(cp_file_name))
j1 = ws.add_job_from_string(get_base_model_text())
opt = ws.add_options()
opt.action = Action.CompileOnly
cp = ws.add_checkpoint(os.path.basename(cp_file_name))
j1.run(opt, cp)
del opt
...

So what you should keep in mind before we return to further explanations of the main function is, that the file tbase is now in the current working directory and contains a checkpoint that will work exactly like a restart file.

In the main function we define some data using Python data structures as we already did in Transport4 before we create the GamsWorkspace and a GamsDatabase.

...
if len(sys.argv) > 1:
ws = GamsWorkspace(w_dir, sys.argv[1])
else:
ws = GamsWorkspace(w_dir)
db = ws.add_database()
...

Afterwards we set up the GamsDatabase like we already did in Transport4. Once this is done we run a GamsJob using this data plus the checkpoint stored in file tbase.

...
cp_base = ws.add_checkpoint("tbase")
t4 = ws.add_job_from_string(get_model_text(), cp_base)
opt = ws.add_options()
opt.defines["gdxincname"] = db.name
opt.all_model_types = "xpress"
...

Note that the string from which we create job t11 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 cp_base which is equal to the one we saved in tbase.