GAMS Development Corp. GAMS Software GmbH www.gams.com
GAMS – An Introduction
Hands-on Tutorial on Optimization Frederik Proske & Lutz Westermann
GAMS Software GmbH
GAMS An Introduction Hands-on Tutorial on Optimization Frederik - - PowerPoint PPT Presentation
GAMS An Introduction Hands-on Tutorial on Optimization Frederik Proske & Lutz Westermann GAMS Software GmbH GAMS Development Corp. GAMS Software GmbH www.gams.com Agenda GAMS at a Glance GAMS Hands On Examples Outlook A
GAMS Development Corp. GAMS Software GmbH www.gams.com
Hands-on Tutorial on Optimization Frederik Proske & Lutz Westermann
GAMS Software GmbH
2
Agenda
GAMS at a Glance GAMS – Hands On Examples Outlook
4
1976 - A World Bank Slides
GAMS came into being!
5
The aim of this system is to provide one representation of a model which is easily understood by both humans and machines.
[J. Bischopp, A. Meeraus, On the Development of a General Algebraic Modeling System in a Strategic Planning Environment. Mathematical Programming Study 20 (1982) 1–29.]
Self-documenting model. A GAMS model is a machine-executable documentation of an
[M. Bussieck & A. Meeraus, Algebraic Modeling for IP and MIP (GAMS), Annals of Operations Research 149(1): History of Integer Programming: Distinguished Personal Notes and Reminiscences, Guest Editors: Kurt Spielberg and Monique Guignard-Spielberg, February, 2007, pp. 49-56 ]
6
What did this give us?
7
➢Roots: World Bank, 1976 ➢Went commercial in 1987 ➢Locations ➢GAMS Development Corporation (USA) ➢GAMS Software GmbH (Germany) ➢Product
➢The General Algebraic Modeling System
Company
8
Broad User Community and Network 30+ Years
GAMS Development
14,000+ licenses Users: 50% academic, 50% commercial GAMS used in more than 120 countries Uniform interface to ~40 solvers
9
Broad Range of Application Areas
Agricultural Economics Applied General Equilibrium Chemical Engineering Economic Development Econometrics Energy Environmental Economics Engineering Finance Forestry International Trade Logistics Macro Economics Military Management Science/OR Mathematics Micro Economics Physics
10
Foundation of GAMS Powerful algebraic modeling language Open architecture and interfaces to
11
Declarative and Procedural Language Elements
Declarative elements
notation
language elements: sets, parameters, variables, equations, models
(algebraic) description of the problem
Procedural elements
(e.g. loops, for, if,…),
algorithms within GAMS
12
Independence of Model and Operating System
Platforms supported by GAMS: Models can be moved between platforms with ease!
13
Cross Platform GUI – GAMS Studio
➢ Open source Qt project (Mac/Linux/Win) ➢ Published on GitHub under GPL ➢ Released in beta status ➢ Group Explorer ➢ Editor / Syntax coloring / Spell checks ➢ Tree view / Syntax-error navigation ➢ Option Editor ➢ Integrated Help ➢ Model Debugging & Profiling ➢ Solver selection & setup ➢ Data viewer ➢ GAMS Processes Control
14
Independence of Model and Solver
All major commercial LP/MIP solver Open Source Solver (COIN) Also solver for NLP, MINLP, global, and stochastic
One environment for a wide range of model types and solvers
Switching between solvers with one line of code!
…
15
Independence of Model and Data
between GAMS and applications – Platform independent – No license required – Direct GDX interfaces and general API – … GDX
GAMS SOLVER
csv
16
Independence of Model and User Interface
Python, C++
Model is written in GAMS
encapsulates a GAMS model
18
Free Model Libraries ➢ More than 1400 models!
19
applications
Why GAMS?
21
Sets
set[s] set_name ["text"] [/element [text] {,element [text]} /] {,set_name ["text"] [/element [text] {,element [text]} /] } ;
value 1986 and ‘01’ ≠ ‘1’
22
Data
23
Data: Parameters
24
Data: Table
25
Data: Assignments
26
Data: Expressions (I)
Expression: an arbitrarily complex calculation instruction Arithmetic operators: +, -, *, /, ** (exponentiate)
27
Data: Expressions (II)
Indexed Operations:
28
Variables
Examples:
29
Variable Attributes
Attributes of a variable: Examples:
30
Equations (I)
Declaration:
Definition:
[...] [...]
31
Equations (II)
Example: Attributes of an equation:
32
Model Statements (I)
33
Model Statements (II)
34
Solving a Model
[...]
36
A Simple Transportation Problem
problem can be formulated in GAMS
change model type and, consequently, solver technology
exchange with GAMS
37
LP
minimum transportation cost
shipment volumes
MIP
decisions
least 100 cases
MINLP
in unit cost with growing volumes
Scenarios
38
A Simple Transportation Problem
Freight: $90 case / thousand miles
Canning Plants (supply)
Markets (demand) shipments
(Number of cases)
39
Minimize Transportation cost subject to Demand satisfaction at markets Supply constraints
350 San Diego 600 275 300 325 Topeka 1.4 2.5 1.8 1.8 1.7 2.5 Supply
(cases)
Demand
(cases)
Distance
(thousand miles)
New York Chicago Seattle
Freight: $90 case / thousand miles
A Simple Transportation Problem
40
Mathematical Model Formulation
Indices: 𝑗 (Canning plants) 𝑘 (Markets) Decision variables: 𝑦𝑗𝑘 (Number of cases to ship) Data: 𝑑𝑗𝑘 (Transport cost per case) 𝑏𝑗 (Capacity in cases) 𝑐𝑗 (Demand in cases) min 𝑑𝑗𝑘 ∙ 𝑦𝑗𝑘
𝑘 𝑗
(Minimize total transportation cost) subject to 𝑦𝑗𝑘
𝑘
≤ 𝑏𝑗 ∀ 𝑗 (Shipments from each plant ≤ supply capacity) 𝑦𝑗𝑘
𝑗
≥ 𝑐
𝑘 ∀ 𝑘 (Shipments to each market ≥ demand)
𝑦𝑗𝑘 ≥ 0 ∀𝑗, 𝑘 (Do not ship from market to plant) 𝑗, 𝑘 ∈ ℕ
Hands-On
41
GAMS Syntax (LP Model)
42
GAMS Syntax (Data Input)
43
Solution to LP model
Freight: $90 case / thousand miles Total cost: $153,675
50 275 300 275
Canning Plants (supply)
Markets (demand) shipments
(Number of cases)
44
LP
minimum transportation cost
shipment volumes
MIP
decisions
least 100 cases
MINLP
in unit cost with growing volumes
Scenarios
45
x (continuous variable)
ship (binary variable)
MIP Model: Minimum Shipment of 100 cases
add constraints: 𝑦𝑗,𝑘 ≥ 100 ∙ 𝑡ℎ𝑗𝑞𝑗,𝑘 ∀ 𝑗, 𝑘 (if ship=1, then ship at least 100) 𝑦𝑗,𝑘 ≤ 𝑐𝑗𝑁 ∙ 𝑡ℎ𝑗𝑞𝑗,𝑘 ∀ 𝑗, 𝑘 (if ship=0, then do not ship at all) 𝑡ℎ𝑗𝑞𝑗,𝑘 ∈ 0,1
100
ship = 0 ship = 1 Cost ($) Not possible x (Number of cases) Hands-On
46
MIP Model: GAMS Syntax
47
MIP Model: Results
48
MIP Model: Solution
Freight: $90 case / thousand miles Total cost: $153,675
325 300 275
Canning Plants (supply)
Markets (demand) shipments
(Number of cases)
49
LP
minimum transportation cost
shipment volumes
MIP
decisions
least 100 cases
MINLP
in unit cost with growing volumes
Scenarios
50
MINLP: Cost Savings
100
ship = 0 ship = 1 Cost ($) Not possible The cost per case decreases with an increasing shipment volume Replace: min 𝑗 𝑘 𝑑𝑗𝑘 ∙ 𝑦𝑗𝑘 (Minimize total transportation cost) With min 𝑗 𝑘 𝑑𝑗𝑘 ∙ 𝑦𝑗𝑘𝒄𝒇𝒖𝒃 (Minimize total transportation cost) x (Number of cases) Hands-On
51
MINLP Model: GAMS Syntax
52
MINLP Model: Results
53
MINLP Model: Solution
Freight: $90 case / thousand miles
325 300 275
Total cost: $115,438
Canning Plants (supply)
Markets (demand) shipments
(Number of cases)
54
LP
minimum transportation cost
shipment volumes
MIP
decisions
least 100 cases
MINLP
in unit cost with growing volumes
Scenarios
55
solution of many optimization problems
hand does not work with a single monolithic model, e.g.
but it takes days)
→GAMS Grid Facility →Gather-Update-Solve-Scatter
Motivation
56
Controls GAMS function when linking to solver. Model transport /all/ ; transport.solveLink={0 %Solvelink.ChainScript%, 1 %Solvelink.CallScript%, 2 %Solvelink.CallModule%, 3 %Solvelink.AsyncGrid%, 4 %Solvelink.AsyncSimulate%, 5 %Solvelink.LoadLibrary%, 6 %solveLink.aSyncThreads%, 7 %solveLink.threadsSimulate%}; solve transport using lp minimizing z;
SolveLink Option
57
+ Maximum memory available to solver + protection against solver failure (hostile link)
+ protection against solver failure (hostile link) + no swap of GAMS database
+ fast memory based model communication + update of model object inside the solver (hot start)
SolveLink Option – Sequential Solves
58
[0]
[2]
[5]
different solveLink settings
SolveLink Option Sequential – Exercise
Hands-On
59
SolveLink Option – Sequential Solves
ChainScript 6.710, CallModule 2.694, LoadLibrary 0.578
60
Grid computing environment
core without use of temporary files, GAMS does not wait for the solver to come back
SolveLink Option – Asynchronous Solves
61
[3]
[6]
different solveLink settings
SolveLink Option Asynchronous – Exercise
Hands-On
62
SolveLink Option – Asynchronous Solves
aSyncGrid 4.259, aSyncThreads 0.496
ChainScript 6.710 CallModule 2.694 LoadLibrary 0.578 aSyncGrid 4.259 aSyncThreads 0.496
63
SolveLink Option – Asynchronous Solves
ChainScript 29.807 CallModule 30.004 LoadLibrary 28.864 aSyncGrid 9.112 aSyncThreads 7.901
64
GUSS – Gather-Update-Solve-Scatter
aka Scenario Solver
Generation Solution Update Simple Serial Solve Loop Scenario Solver/GUSS Generates model once and updates the algebraic model keeping the model “hot” inside the solver. Loop Generation Solution Update
65
GUSS – Gather-Update-Solve-Scatter
aka Scenario Solver
ChainScript 6.710 CallModule 2.694 LoadLibrary 0.578 aSyncGrid 4.259 aSyncThreads 0.496 GUSS 0.273
66
loop
collection loop. Keep number of submitted models <=
#threads
Grid & GUSS – Examples from the model library
* Freely adapted from the poetry of Gertrude Stein, 1874-1946, American writer
68
What is a Model?
69
mathematical language (from: Wikipedia) ➔ Mathematical Programming (MP) Model: List of Equations
What is a Model?
70
mathematical language (from: Wikipedia) ➔ Mathematical Programming (MP) Model: List of Equations
What is a Model in GAMS?
71
project/model
have different views
descriptions
Model as Communication Vehicle
72
type of vagueness
model
Model as Analytic Framework
73
(input data)
problems
access to results via independent result analyzers for non model experts
metric
Model as Contract
74
Model as Cost Saver
Model Roles over Time
Communication Vehicle Analytic Framework Contract Cost Saver
From simple sequential to highly parallel solve statements
76
Off-the-shelf software (speedup via parallelization)
How does GAMS support problem specific solution approaches that are well suited/customized for HPC?
Optimization Problem core core core core memory Multi-core shared memory Distributed (shared) memory
. . .
core core core core memory
Node 0
core core core core memory
Node 1
core core core core memory
Node n-1
Available Computing Resources standard HPC
77
Non-zero Plot of matrix Solve sequence of problems (e.g. in Benders Decomp.) … … … Parallelize … … … …
time time
… … Decompose Use structure exploiting solver User Annotation to define block structure 1 2 GAMS supports different levels of parallelization GAMS provides annotation facilities and HPC solver links Optimization Problem
78
expensive solve statement:
Sequential Solve Statements in Loops
Model generation Solution process … Model generation Solution process Model generation Solution process
time
79
conventions
Parallel Solves – GAMS Grid Facility
MG S MG S MG S
time
80
mpiexec –n 5 gams myfile
Excursus 1: Message Passing Interface (MPI)
gams myfile gams myfile gams myfile gams myfile gams myfile
81
broadcast(db,0) mpiexec –n 5 gams myfile
Excursus 1: Message Passing Interface (MPI)
gams myfile <-- %sysenv.PMI_RANK%=0 gams myfile <-- %sysenv.PMI_RANK%=1 gams myfile <-- %sysenv.PMI_RANK%=2 gams myfile <-- %sysenv.PMI_RANK%=3 gams myfile <-- %sysenv.PMI_RANK%=4 1 2 3 4 gather(db,0) 1 2 3 4 myfile.gms – pseudo code
82
mpiexec –n 5 gams myfile
Excursus 1: Message Passing Interface (MPI)
gams myfile <-- %sysenv.PMI_RANK%=0 gams myfile <-- %sysenv.PMI_RANK%=1 gams myfile <-- %sysenv.PMI_RANK%=2 gams myfile <-- %sysenv.PMI_RANK%=3 gams myfile <-- %sysenv.PMI_RANK%=4 myfile.gms – pseudo code MG S … MG S MG S
time
83
mpiexec –n 5 gams myfile
Excursus 1: Message Passing Interface (MPI)
gams myfile <-- %sysenv.PMI_RANK%=0 gams myfile <-- %sysenv.PMI_RANK%=1 gams myfile <-- %sysenv.PMI_RANK%=2 gams myfile <-- %sysenv.PMI_RANK%=3 gams myfile <-- %sysenv.PMI_RANK%=4
code but allows parallel solve
(part of MPI)
MPI → Embedded Code
myfile.gms – pseudo code
84
Excursus 2: Embedded Code Facility
85
set scen 'scenario set' / scen1*scen100 / s(scen) 'dynamic secenario subset' k 'benders iterations' / k1*k1000 /; ... // preparatory work loop(k$( NOT done ), ... // setup model for master-problem solve master min obj_master use lp; ... // fix first stage variables loop(scen, ... // setup model for sub-problem
solve sub min obj_sub use lp; ... // process results ); ... // compute cuts for next master ... // free fixed first stage variables ... // set done=1 if convergence criterion is met ); ... // reporting
Example: Sequential Benders Decomposition
86
set scen 'scenario set' / scen1*scen100 / s(scen) 'dynamic secenario subset' k 'benders iterations' / k1*k1000 /; ... embeddedCode Python: from mpi4py import * comm = MPI.COMM_WORLD ... pauseEmbeddedCode ... // preparatory work $ifthen.MPI 0==%sysenv.PMI_RANK% loop(k$( NOT done ), ... // setup model for master-problem solve master min obj_master use lp; ... // fix first stage variables continueEmbeddedCode: comm.bcast([[done]] + <data for sub>, root=0) cut = comm.gather(None, root=0)[1:] ... // gathered data → GAMS data struct. pauseEmbeddedCode <load GAMS data struct.> ... // compute cuts ... // free fixed first stage variables ... // set done=1 if convergence criterion is met ); continueEmbeddedCode: comm.bcast([[done],<empty>], root=0) endEmbeddedCode ... // reporting $else.MPI
Example: Parallel Benders with mpi4py
set scen 'scenario set' / scen1*scen100 / s(scen) 'dynamic secenario subset' k 'benders iterations' / k1*k1000 /; ... embeddedCode Python: from mpi4py import * comm = MPI.COMM_WORLD ... pauseEmbeddedCode ... // preparatory work $else.MPI s(scen) = ord(scen)=%sysenv.PMI_RANK%; while(1, continueEmbeddedCode: primal_solution = comm.bcast(None, root=0) // broadcasted data → GAMS data struct. pauseEmbeddedCode <GAMS data struct.> abort.noerror$done 'terminating subprocess'; solve sub min obj_sub use lp; ... // process results continueEmbeddedCode: comm.gather(<subproblem results>), root=0 ) pauseEmbeddedCode ); $endif.MPI
PMI_RANK=0 PMI_RANK>=1
87
21,029,101 rows, 23,217,077 columns, 85,721,477 non-zeroes
All runs were made with GAMS 25.1.2 on JURECA@JSC with 24 cores per node, 2.5 GHz, (Intel Xeon E5-2680 v3 Haswell), 128 GB RAM 1: single node, 16 cores, CPLEX barrier, no crossover 2: single node, 4 cores per solve statement, CPLEX barrier, advind 0 3: 17 nodes, 404 cores in total, 4 cores per solve statement, CPLEX barrier, advind 0
Computational Result(s)
TIME [sec] Method sub- problems master- problem total Deterministic Equivalent1 4059.00
2394.92 0.18 2395.10 MPI Benders3 28.35 0.16 28.51
89
Calling GAMS from your Application
Creating Input for GAMS Model → Data handling using GDX API Callout to GAMS →GAMS option settings using Option API →Starting GAMS using GAMS API Reading Solution from GAMS Model → Data handling using GDX API
Application
GDX
GAMS SOLVER
90
several languages (C, C++, C#, Delphi, Java, Python, VBA, …)
requirements of different Object Oriented languages
Low level APIs → Object Oriented API
91
develop applications → Programming required to build your applications
92
From GAMS Model to Visual Web User Interface
93
Basic setup: ✓ Annotating GAMS model (defining the input and output data to be displayed in the WebUI)
From GAMS Model to Visual Web User Interface
94
✓
Fully functional interface by only specifying input and output data
✓
Tabular view of input (editable) and output data
✓
Graphical visualization via pivot charts
Basic Setup – GAMS Model Annotations
95
Basic Setup – GAMS Model Annotations
96
Basic Setup – GAMS Model Annotations
97
Basic Setup – GAMS Model Annotations
98
Basic setup: ✓ Annotating GAMS model (defining the input and output data to be displayed in the WebUI) Advanced setup: ✓ Configuration of standard graphics and UI ✓ Sophisticated (custom) graphics (R API) ✓ Scenario management with internal database
From GAMS Model to Visual Web User Interface
99
Advanced Setup – Configuration
✓
Configuration via JSON file
✓
Access to a number of pre- implemented tools for graphical representation
✓
Focus on configuration, not programming
100
Advanced Setup – Sophisticated graphics
✓
Sophisticated graphics created in R can be included as modules
✓
Access to the entire R ecosystem
✓
Easily extendable with the wide spectrum of the R programming language
101
Advanced setup: ✓ Configuration of standard graphics and UI ✓ Sophisticated (custom) graphics (R API) ✓ Scenario management with internal database Enterprise setup: ✓ User- and Application management Initialization: ✓ Annotating GAMS model (defining the input and output data to be displayed in the WebUI)
From GAMS Model to Visual Web User Interface
102
Enterprise Setup – User and Application Management
✓
Local or server-based solution
✓
User authentication (e.g. LDAP, OAuth 2.0, Google, GitHub, Facebook)
✓
Multi-Application support with docker-based technology
Yaml config file
103
Enhanced Model Deployment in GAMS using R/Shiny
model
✓ Data exchange via local files or database ✓ Modification of the input data ✓ Extensive visualization options ✓ Comparison of different scenarios ✓ Multi-user support based on Docker technology ✓ User authentication
(configuration vs. programming)
interested in getting involved, please contact support@gams.com
104
Welcome to Jupyter @ GAMS!
105
GAMS Jupyter Example
Hands-On
106
→ No local installation needed
GAMS
models
visualize data that comes in all sort of ways
to tell optimization story with text, data, graphs, math, and models
Give it a try at https://jupyterhub.gams.com/hub/login
Using GAMS Jupyter Notebooks to tell “optimization stories”
108
Stochastic Programming in GAMS
EMP Information
(uncertain Par.)
Reformulated Model Solution
Mapping Solution into original space
Deterministic Model
Translation
Solve with established Algorithms
EMP/SP ➢ Simple interface to add uncertainty to existing deterministic models ➢ (EMP) Keywords to describe uncertainty include: discrete and parametric random variables, stages, chance constraints, Value at Risk, ... ➢ Available solution methods: ➢ Automatic generation of Deterministic Equivalent (can be solved with any solver) ➢ Specialized commercial algorithms (DECIS, LINDO)
109
Transport Example – Uncertain Demand
bf Prob: 0.3 Val: 0.90 Prob: 0.5 Val: 1.00 Prob: 0.2 Val: 1.10
➢ First-stage decision: How many units should be shipped “here and now” (without knowing the outcome) ➢ Second-stage (recourse) decision: ➢ How can the model react if we do not ship enough? ➢ Penalties for “bad” first-stage decisions, e.g. buy additional cases u(j) at the demand location:
costsp .. z =e= sum((i,j), c(i,j)*x(i,j))+ sum(j,0.3*u(j)); demandsp(j) .. sum(i, x(i,j)) =g= bf*b(j) - u(j) ;
Uncertain demand factor bf
110
Uncertain Demand: GAMS Algebra
111
Uncertain Demand: Results
112
framework is used to replace parameters in the model by random variables
constraint models
either use specialized algorithms or create Deterministic Equivalent (new free solver DE)
https://www.gams.com/latest/docs/UG_EMP_SP.html
Stochastic Programming in GAMS