21
AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash Kianfar Feb 2008

AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

Embed Size (px)

Citation preview

Page 1: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

AMPL: A Modeling Language for Mathematical Programming

A Tutorial

Prepared by:

Kiavash Kianfar

Feb 2008

Page 2: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

Contents

1 Introduction 3

2 Model and Data 32.1 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.2 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.3 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72.4 Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82.5 Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3 Examples of AMPL Model and Data Files 93.1 Example 1: Steel Production Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.2 Example 2: Diet Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.3 Example 3: Multicommodity Transportation Model . . . . . . . . . . . . . . . . . . . 113.4 Example 4: Multiperiod Production Model . . . . . . . . . . . . . . . . . . . . . . . 13

4 Solving an AMPL model 15

5 Display Commands 165.1 display Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165.2 Suffixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175.3 printf Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.4 show Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.5 expand Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185.6 Generic Synonyms for Variables, Constraints and Objectives . . . . . . . . . . . . . . 18

6 Command Scripts 196.1 let Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196.2 for Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206.3 if-then-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

7 Some Useful Functions 20

8 Exporting Models in MPS format 21

References 21

2

Page 3: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

1 Introduction

AMPL is a language for generating mathematical programming models. These models can laterbe solved using various solvers including CPLEX. This tutorial aims at providing the knowledgerequired to write moderate-level mathematical programming models using AMPL. It should benoted that AMPL has many more features which you can learn by referring to [1].

2 Model and Data

In AMPL the model itself and the data for the model are stored in two different plain-text files.Therefore to create a solvable model you should create two text files using a text editor like NotePad:a model file and a data file. The model file is stored with .mod extension and the data file is storedwith .dat extension.

Important Notes:

• The AMPL language is case sensitive. Therefore PROD, prod, Prod denote different identi-fiers.

• The “#” symbol is used to insert a comment line. The comment ends at the end of the line.The pair “/*...*/” can be used to generate a block of comment.

• Every statement in the code must end with a semicolon (;).

An AMPL model has the following elements which are normally declared in the model file in thesame order:

• Sets

• Parameters

• Variables

• Objective

• Constraints

The membership of sets and the value for parameters are provided in the data file. In the followingsections we discuss each of the above elements along with many more details.

2.1 Sets

Sets are the most fundamental components of an AMPL model. Almost all of the parameters,variables and constraints in a typical model are indexed over sets, and many expressions containoperations (usually summations) over sets. Set indexing is the feature that permits a concise modelto describe a large mathematical program.The most elementary kind of set is an unordered collection of character strings. For these setsusually the set itself is declared in the model file as follows

set setname;

and its members are declared in the data file.Another kind of set is a set of numbers. For these sets the set itself and its elements are declaredin the model file:

3

Page 4: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

set setname =numberrange;

numberrange can be a set of numbers 1,2,3,4 which can be denoted as 1..4. The keyword bycan be used to specify an interval other than 1between the numbers for example 1990..2010 by4 which denotes the set of 1990, 1994,. . ., 2010.Examples of declaration of sets in the model are

set PROD;set ORIG;set DEST;set FOOD;set NUTR;set PERIOD = 1..4;set YEAR = 1990..2010 by 4; #The members would be 1990,1994,1998,...,2010;

Examples of declaration of members for the above unordered sets in the data file are

set PROD := bands coils plate;set ORIG := GARY CLEV PITT ;set DEST := FRA DET LAN WIN STL FRE LAF ;set FOOD := BEEF CHK FISH HAM MCH MTL SPG TUR ;set NUTR := A B1 B2 C ;

2.2 Parameters

In AMPL parameter are named numerical values. They represent the known data in the model.They are either supplied by the modeler or computed from other values. They can be individualscalar values but they are usually in the form of vectors and matrices and are indexed over sets.

In the model file a parameter is defined as follows:

param paramname { pramindexingop } paramattributesop;

The op subscript means that the use of that part of the command is optional. For exampleparamindexing is only used when the parameter is not a scalar. paramattributes is a list ofconditions that will be checked by AMPL for the values given to the parameter such as >=0 or >0.

Examples:

param T;param avail >=0;param profit {PROD};param market {PROD} >=0;param rate {PROD} > 0;param capacity {1..T} >0;param demand {DEST,PROD}; #two-dimensional parameter over DEST and PROD setsparam cost {ORIG,DEST,PROD}; #three-dimensional parameter over

ORIG, DEST, and PROD sets

In the examples above the indexing is done just by stating the sets that each parameter is definedon. Sometimes in defining the attributes of the parameter it is helpful to use what is called adummy index. For example

4

Page 5: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

param f_min {FOOD} >= 0;param f_max {j in FOOD} >= f_min[j];

Here j is a dummy index on the set FOOD used to define lower limits for the parameter f_max.

The data for the parameters is usually provided in the data file. Examples of designation of datafor parameters in the data file are as follows:

• Data for scalar parameter:

param T:=4;param avail:=40;

• Data for 1-dimensional parameters:

param rate := bands 200 coils 140 plate 160;param capacity:= 1 20 2 30 3 45 4 60;

• Data for 2-dimensional parameters:

param demand: bands coils plate :=FRA 300 500 100DET 300 750 400LAN 100 400 0WIN 75 250 50STK 650 950 200FRE 225 850 100LAF 250 500 250;

The row labels give the first index (DEST) and the column labels give the second index (PROD).The data can be provided in the transposed format using the tr option:

param demand (tr):FRA DET LAN WIN STL FRE LAF :=

bands 300 300 100 75 650 225 250coils 500 750 400 250 950 850 500plate 100 100 0 50 200 100 250 ;

• The data can be given for higher dimensional parameters too. For example for the 3-dimensional parameter shipcost{ORIG,DEST,PROD}we can write:

param cost :=[*,*,bands]: FRA DET LAN WIN STL FRE LAF :=

GARY 30 10 8 10 11 71 6CLEV 22 7 10 7 21 82 13PITT 19 11 12 10 25 83 15

[*,*,coils]: FRA DET LAN WIN STL FRE LAF :=GARY 39 14 11 14 16 82 8

5

Page 6: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

CLEV 27 9 12 9 26 95 17PITT 24 14 17 13 28 99 20

[*,*,plate]: FRA DET LAN WIN STL FRE LAF :=GARY 41 15 12 16 17 86 8CLEV 29 9 13 9 28 99 18PITT 26 14 17 13 31 104 20 ;

In this format the * symbols represent the dimensions of row and column labels.

• The data can be provided at the same time for several parameters defined on the same set:

param: avail_min avail_max time_penalty :=1 35 42 31002 35 42 30003 30 40 37004 35 42 3100 ;

Here parameters avail_min, avail_max and time_penalty are defined over the set 1..4.

• Also the set members and the data can be given in a single statement:

param: PROD: profit market :=bands 25 6000coils 30 4000plate 29 3500;

Here the members of the set PROD and the parameters profit, and market are given in asingle statement.

Helpful Tip: For the number sets it is the common practice to use parameters for the start andend of the range and the interval for example

param start integer;param end > start integer;param interval > 0 integer;set YEAR = start..end by interval;

The value of the parameters start, end, and interval are then provided in the data file.

Computed Parameters

We can also have computed parameters in terms of other parameters. These are provided in themodel file. For example

param mininv {p in PROD, t in 0..T-1} = 0.1 * market[p,t+1]

6

Page 7: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

Randomly Generated Parameters

When testing a model, it is convenient to use randomly generated data. These parameters arelike computed parameters except that in their defining expressions the built-in random numbergeneration functions of AMPL are used. Examples of defining randomly generated parameters inthe model file are as follows:

param avail_mean > 0;param avail_variance > 0; < avail_mean / 2;param avail = max(Normal(avail_mean, avail_variance),0);

or

param avail_mean {STAGE}> 0;param avail_variance {s in STAGE} > 0; < avail_mean[s] / 2;param avail {s in STAGE} = max(Normal(avail_mean[s], avail_variance[s]),0);

Some random generators are as follows:

• Normal(mean,var): generates a random number from the normal distribution with meanmean and the variance var.

• Normal01(): generates a random number from the normal distribution with mean 0 andvariance 1.

• Uniform(a,b): generates a random number from the uniform distribution on [a,b).

• Uniform01(): generates a random number from the uniform distribution on [0,1).

• Irand224(): generates a random number from the integer uniform distribution on [0,224).

• Exponential(): generates a random number from the exponential distribution with λ = 1.

All of the AMPL random functions are based on a uniform random number generator with a verylong period. When you start AMPL or give a reset command, however, the generator is reset andthe random values are the same as before. You can request different values by changing the AMPLoption randseed to some integer other than its default value of 1. The command for this purposeis

option randseed n;

where n is some integer value. Nonzero values give sequences that repeat each time AMPL is reset.A value of 0 requests to pick a seed at based on the current value of the system clock, resulting ina different seed at each reset.

2.3 Variables

The variables of a linear program have much in common with its parameters. Both are symbolsthat stand for numbers, and may be used in arithmetic expressions. Parameter values are suppliedby the modeler or computed from other values, while the values of variables are the ones to bedecided and are determined by the optimizing algorithm.

Variables are defined in the model file. Syntactically, variable declarations are the same as theparameter declarations except that they begin with the keyword var rather than param:

7

Page 8: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

var varname { indexingop } varattributesop;

varattributes is a list of conditions on the variable that should be satisfied in the solution. Sign re-strictions are the most common ones (>=0, <=, =). binary and integer are some other possibilities.Dummy indices can be used in declaration of attributes for variables.

Examples:

var Make {p in PROD} >= 0, <= market[p];var Buy {j in FOOD} >= f_min[j], <= f_max[j];var Trans {ORIG,DEST,PROD} >= 0;

If we want variable Buy to be integer then the declaration above should be modified to

var Buy {j in FOOD} integer >= f_min[j], <= f_max[j];

2.4 Objective

The objective function is declared in the model file. The declaration of an objective functionconsists of one of the keywords minimize or maximize, a name, a colon, and a linear expression inpreviously defined sets, parameter and variables:

maximize (or minimize) objname: objexpression;

Example:

maximize Total_Profit: sum {p in PROD} profit[p] * Make[p];minimize Total_Cost: sum {i in ORIG, j in DEST, p in PROD}

cost[i,j,p] * Trans[i,j,p];

The sum operator is frequently used in declaration of the objective and constraints. Dummy indicesare utilized for this purpose. It is one the indexed operators in AMPL. Its general form is as follows:

sum {indexing} expression;

The expression is evaluated once for each member of the index set, and all resulting values areadded up. prod, min, and max, are examples of other indexed operators.

2.5 Constraints

The simplest kind of constraint declaration begins with the keywords subjectto, a name, and acolon. Even the subjectto is optional. AMPL assumes that any declaration not beginning witha keyword is a constraint. Following the colon is an algebraic expression of previously definedsets, parameters, and variables. However, many constraints in large linear programs are defined asindexed collections, by giving an indexing expression after the constraint name. Thus the generalform of a constraint is as follows:

[subject to]op constname {indexing}: constexpression;

Example:

subject to Time: sum {p in PROD} (1/rate[p]) * Make[p] <= avail;subject to Diet {i in NUTR}:

n_min[i] <= sum {j in FOOD} amt[i,j] * Buy[j] <= n_max[i];subject to Demand {j in DEST, p in PROD}:

sum {i in ORIG} Trans[i,j,p] = demand[j,p];

8

Page 9: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

The first example is the declaration of a single constraint named Time. The second example declaresa set of constraints over the set NUTR. The third example declares a set of constraints over the two-dimensional set {DEST,PROD}.As you can see in the second example AMPL allows double-inequalityconstraints.In general everywhere in an AMPL model conditioning expressions can be added to the index setsafter a colon. For example

subject to Const {i in 1..I}:sum {j in 1..J: j>i and p[j]>q[i]} X[i,j] = supply[i];# for each i summation is done over all j’s that are greater than i.

3 Examples of AMPL Model and Data Files

All model examples in [1] come with the AMPL distribution. They can be found in the AMPLfolder under \examples\models. The following examples are taken from there.

3.1 Example 1: Steel Production Model

In this example the production level of some steel products are to be determined to maximize theprofit subject to production time limit. There are lower bounds and upper bound on the productionlevel. The model and data files are as follows:

set PROD; # products

param rate {PROD} > 0; # produced tons per hourparam avail >= 0; # hours available in weekparam profit {PROD}; # profit per ton

param commit {PROD} >= 0; # lower limit on tons sold in weekparam market {PROD} >= 0; # upper limit on tons sold in week

var Make {p in PROD} >= commit[p], <= market[p]; # tons produced

maximize Total_Profit: sum {p in PROD} profit[p] * Make[p];

# Objective: total profits from all products

subject to Time: sum {p in PROD} (1/rate[p]) * Make[p] <= avail;

# Constraint: total of hours used by all# products may not exceed hours available

Figure 1: steel3.mod

9

Page 10: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

set PROD := bands coils plate;

param: rate profit commit market :=bands 200 25 1000 6000coils 140 30 500 4000plate 160 29 750 3500 ;

param avail := 40;

Figure 2: steel3.dat

3.2 Example 2: Diet Model

In this example we would like to find out how much of each food to include in a diet to meet somenutrient requirements such that the cost of food is minimized. There are upper and lower limits onthe amount of each nutrient in the diet and also on the amount of each type of food that can bepurchased. The model and data files are as follows:

set NUTR;set FOOD;

param cost {FOOD} > 0;param f_min {FOOD} >= 0;param f_max {j in FOOD} >= f_min[j];

param n_min {NUTR} >= 0;param n_max {i in NUTR} >= n_min[i];

param amt {NUTR,FOOD} >= 0;

var Buy {j in FOOD} >= f_min[j], <= f_max[j];

minimize Total_Cost: sum {j in FOOD} cost[j] * Buy[j];

subject to Diet {i in NUTR}:n_min[i] <= sum {j in FOOD} amt[i,j] * Buy[j] <= n_max[i];

Figure 3: diet.mod

10

Page 11: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

set NUTR := A B1 B2 C ;set FOOD := BEEF CHK FISH HAM MCH MTL SPG TUR ;

param: cost f_min f_max :=BEEF 3.19 0 100CHK 2.59 0 100FISH 2.29 0 100HAM 2.89 0 100MCH 1.89 0 100MTL 1.99 0 100SPG 1.99 0 100TUR 2.49 0 100 ;

param: n_min n_max :=A 700 10000C 700 10000B1 700 10000B2 700 10000 ;

param amt (tr):A C B1 B2 :=

BEEF 60 20 10 15CHK 8 0 20 20FISH 8 10 15 10HAM 40 40 35 10MCH 15 35 15 15MTL 70 30 15 15SPG 25 50 25 15TUR 60 20 15 10 ;

Figure 4: diet.dat

3.3 Example 3: Multicommodity Transportation Model

In this example we would like to find out how much of each product to ship from each origin to eachdestination to meet the demand at destinations such that the total cost of shipments is minimized.There are limits on transportation capacity from each origin to each destination. The summationof supply is equal to the summation of demand for each product (look at the use of the checkcommand in the model). The model and data files are as follows:

11

Page 12: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

set ORIG; # originsset DEST; # destinationsset PROD; # products

param supply {ORIG,PROD} >= 0; # amounts available at originsparam demand {DEST,PROD} >= 0; # amounts required at destinations

check {p in PROD}:sum {i in ORIG} supply[i,p] = sum {j in DEST} demand[j,p];

param limit {ORIG,DEST} >= 0;

param cost {ORIG,DEST,PROD} >= 0; # shipment costs per unitvar Trans {ORIG,DEST,PROD} >= 0; # units to be shipped

minimize Total_Cost:sum {i in ORIG, j in DEST, p in PROD}

cost[i,j,p] * Trans[i,j,p];

subject to Supply {i in ORIG, p in PROD}:sum {j in DEST} Trans[i,j,p] = supply[i,p];

subject to Demand {j in DEST, p in PROD}:sum {i in ORIG} Trans[i,j,p] = demand[j,p];

subject to Multi {i in ORIG, j in DEST}:sum {p in PROD} Trans[i,j,p] <= limit[i,j];

Figure 5: multi.mod

12

Page 13: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

set ORIG := GARY CLEV PITT ;set DEST := FRA DET LAN WIN STL FRE LAF ;set PROD := bands coils plate ;

param supply (tr): GARY CLEV PITT :=bands 400 700 800coils 800 1600 1800plate 200 300 300 ;

param demand (tr):FRA DET LAN WIN STL FRE LAF :=

bands 300 300 100 75 650 225 250coils 500 750 400 250 950 850 500plate 100 100 0 50 200 100 250 ;

param limit default 625 ;

param cost :=

[*,*,bands]: FRA DET LAN WIN STL FRE LAF :=GARY 30 10 8 10 11 71 6CLEV 22 7 10 7 21 82 13PITT 19 11 12 10 25 83 15

[*,*,coils]: FRA DET LAN WIN STL FRE LAF :=GARY 39 14 11 14 16 82 8CLEV 27 9 12 9 26 95 17PITT 24 14 17 13 28 99 20

[*,*,plate]: FRA DET LAN WIN STL FRE LAF :=GARY 41 15 12 16 17 86 8CLEV 29 9 13 9 28 99 18PITT 26 14 17 13 31 104 20 ;

Figure 6: multi.dat

3.4 Example 4: Multiperiod Production Model

In this example we would like to find out the optimal level of production, inventory, and sales ofeach product in each period subject to the production time limits such that the total revenue minusthe production and inventory cost is minimized. The model and data files are as follows:

13

Page 14: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

set PROD; # productsparam T > 0; # number of weeks

param rate {PROD} > 0; # tons per hour producedparam inv0 {PROD} >= 0; # initial inventoryparam avail {1..T} >= 0; # hours available in weekparam market {PROD,1..T} >= 0; # limit on tons sold in week

param prodcost {PROD} >= 0; # cost per ton producedparam invcost {PROD} >= 0; # carrying cost/ton of inventoryparam revenue {PROD,1..T} >= 0; # revenue per ton sold

var Make {PROD,1..T} >= 0; # tons producedvar Inv {PROD,0..T} >= 0; # tons inventoriedvar Sell {p in PROD, t in 1..T} >= 0, <= market[p,t]; # tons sold

maximize Total_Profit:sum {p in PROD, t in 1..T} (revenue[p,t]*Sell[p,t] -

prodcost[p]*Make[p,t] - invcost[p]*Inv[p,t]);

# Total revenue less costs in all weeks

subject to Time {t in 1..T}:sum {p in PROD} (1/rate[p]) * Make[p,t] <= avail[t];

# Total of hours used by all products# may not exceed hours available, in each week

subject to Init_Inv {p in PROD}: Inv[p,0] = inv0[p];

# Initial inventory must equal given value

subject to Balance {p in PROD, t in 1..T}:Make[p,t] + Inv[p,t-1] = Sell[p,t] + Inv[p,t];

# Tons produced and taken from inventory# must equal tons sold and put into inventory

Figure 7: steelT.mod

14

Page 15: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

param T := 4;set PROD := bands coils;

param avail := 1 40 2 40 3 32 4 40 ;

param rate := bands 200 coils 140 ;param inv0 := bands 10 coils 0 ;

param prodcost := bands 10 coils 11 ;param invcost := bands 2.5 coils 3 ;

param revenue: 1 2 3 4 :=bands 25 26 27 27coils 30 35 37 39 ;

param market: 1 2 3 4 :=bands 6000 6000 4000 6500coils 4000 2500 3500 4200 ;

Figure 8: steelT.dat

4 Solving an AMPL model

AMPL environment will start by calling ampl.exe from the AMPL directory. It is a good idea togo to the working directory that the model and data files are stored and then call ampl.exe. TheAMPL directory should be in the path for this purpose. By starting the AMPL environment theampl: prompt will be displayed and AMPL is ready to receive commands.

To use cplexamp solver if it is not already the default solver of the AMPL we issue the followingoption command:

option solver cplexamp

To read the model, say diet.mod, with the data file diet.dat and solving them we issue thefollowing commands:

reset;model diet.mod;data diet.dat;solve;

It is always a good practice to reset the model and data (clear them off the AMPL memory) at thebeginning. You can reset the data only by reset data; command.The AMPL session can be logged into a file by specifying the log_file option:

option log_file diet.log;

Before passing the problem to the solver, AMPL does a presolving phase in which it tries to gettighter bounds on variables, get rid of the redundant constraints, drop fixed variables and in generalimprove the model for solving. If you do not want this phase you can turn it off by the followingcommand:

15

Page 16: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

option presolve 0;

To quit the AMPL environment issue

quit;

5 Display Commands

AMPL has a wealth of commands to display the data and results of the solution. We review someof them here.

5.1 display Command

The easiest way to examine data and result values is to type display and a description of whatyou want to look at. To display variable Make you can type:

display Make;

Helpful Note: You can redirect the output of many AMPL commands (including the displaycommand) to a file by using the following syntax:

display Make > ’make.txt’;

or

display Make >> ’make.txt’;

The first form overwrites any existing file at the opening while the second form causes the outputto be appended to the current contents of the file that it opens. You need to close the file after youare done:

close ’make.txt’;

You can display sets:

display PROD;display ORIG, DEST;

You can display the value of variables or parameters:

display T;display avail;display rate["bands"], rate["coils"];display rate, profit, Make;

You can display the value of indexed expressions:

display sum {p in PROD, t in 1..T} revenue[p,t]*Sell[p,t];

16

Page 17: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

Or you can dummy index to display:

display {p in PROD, t in 1..T} (revenue[p,t]*Sell[p,t],prodcost[p]*Make[p,t]);

You can display the value of the objective by using its name:

display Total_Profit;

You can control the width of the display by the display_width option and you can set the maximumnumber of values that AMPL displays in the one column format by the display_1col. You cansuppress the display of zero values in the display of variables by the omit_zero_rows option.

option display_width 50;option display_1col 0;option omit_zero_rows 1;

Use these options to control the display of numbers:

• display_eps : smallest magnitude displayed differently from zero)

• display_precision : digits of precision to which displayed numbers are rounded (full preci-sion if 0)

• display_round : digits left or (if negative) right of the decimal place to which the displayednumbers are rounded, overriding display_precision.

5.2 Suffixes

AMPL distinguishes the various values associated with a model component by use of “qualified”names. These names consist of a variable or constraint identifier, a dot, and a predefined suffix.The suffixes .lb and .ub on a variable denote its lower and upper bounds and the .slack suffixdenotes the difference of a variable’s value from its nearer bound. The reduced cost associated withvariables is denoted by the suffix .rc.

display Buy.lb, Buy.ub, Buy.slack, Buy.rc;

The concepts of the bound and slacks have an analogous interpretation for the constraints. AnyAMPL constraint can be put into the formlowerbound ≤ body ≤ upperboundwhere body is a sum of all terms involving variables, while lowerbound and upperbound dependonly on the data. The suffixes .lb, .body, and .ub, give the current values of these three parts.Clearly, >= constraints have no upper bounds and <= constraints have no lower bounds.The suffix .slack refers to the difference between the body and the nearer bound.

display Time.lb, Time.body, Time.ub, Time.slack;

The name of the constraints without any qualifying suffix or with the suffix .dual denotes thevalue of the dual variable for that constraint (shadow price of the constraint). The following twocommands are the same

display Time, Time.slack;display Time.dual, Time.slack;

17

Page 18: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

5.3 printf Command

This command can be used to display values. The first print item in this command is a characterstring that provides formatting instructions for the remaining items. The rules of formatting ismuch the same as the printf command in C programming language. An example is

printf "The results are:\n";printf {t in 1..T} "%3i%12.2f%12.2f\n", t,

sum {p in PROD} revenue[p,t]*Sell[p,t],sum {p in PROD} prodcost[p,t]*Make[p,t];

5.4 show Command

The show command by itself lists the names of all component of the current model:

show;

This display can be limited to components of one or more types using following words:

show vars;show obj, constr;

The show command can also display the declaration of individual components saving the troubleof looking them up in the model file:

show Total_Cost;show Trans;

5.5 expand Command

In checking a model and its correctness you may want to look at some of the specific constraintsthat AMPL is generating or the objective. The expand command displays all constraints is a givenindexed collection or specific constraints that you identify:

expand Time;expand Total_Cost;

When expand is applied to a variable, it list all the nonzero coefficients of that variable in the linearterms of the objective and constraints.

5.6 Generic Synonyms for Variables, Constraints and Objectives

Sometimes it is useful to make a listing or a test that applies to all variables, constraints, or objec-tives. For this purpose AMPL provides parameters that hold the numbers of variables, constraints,objectives in the currently generated problem instance:

• nvars number of variables

• ncons number of constraints

• nobjs number of objectives

Correspondingly the following indexed parameters contain the AMPL names of all the components:

18

Page 19: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

• varname{1.. nvars} names of variables

• conname{1.. ncons} names of constraints

• objname{1.. nobjs} names of objectives

Finally the following synonyms are available for the model components:

• var{1.. nvars} synonyms for variables

• con{1.. ncons} synonyms for constraints

• obj{1.. nobjs} synonyms for objectives

These synonyms let you to refer to components by number rather than by the usual indexednames. var[5] refers to the fifth variable in the model. Therefore for example its upper bound isvar[5].ub while varname[5] is a string giving the variable’s true AMPL name.Examples of use of the synonyms above are

display {j in 1.._nvars} (_varname[j],_var[j],_var[j].ub,_var[j].rc);display {j in 1.._nvars : _var[j] < _var[j].ub - 0.000001} _varname[j];

6 Command Scripts

A script is a sequence of AMPL commands, captured in a file, to be used and re-used. Scripts areuseful to save time and effort in issuing similar commands over and over. For example the followingis an script file named diet.run:

model diet.mod;data diet.dat;solve;option omit_zero_rows 0;display Total_Cost > ’diet.txt’;display Buy

Figure 9: diet.run

You can call a script file at the ampl: prompt by the include or commands command:

include diet.run;

or

commands diet.run;

6.1 let Command

One of the AMPL commands that is frequently used in the script files is let. The let commandis used to give value or change the value of parameters. This is useful when you want to solve amodel for different values of a parameter or a set of parameters. Examples of this command are:

let T:=3;let {p in PROD} rate[p]:=100;let {p in PROD} rate[p]:=1.1*rate[p];

19

Page 20: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

6.2 for Statement

The for statement can be used to execute a collection of statements once for each member of someset. For example:

model steelT.mod;data steelT.dat;

for {1..4} {solve;display Total_Profit;let avail[3] := avail[3] + 5;}

The for statement can be issued at the ampl: prompt or can be used in a script file. An exampleof a script file using for to generate random values for parameters is as follows

let avail_mean:= 10;let avail_variance:= 4;for {j in 1..4}{let avail_mean:=avail_mean+10;avail[j] = max(Normal(avail_mean, avail_variance),0);}

6.3 if-then-else Statement

The if-then-else statement conditionally controls the execution of groups of statements. Forexample:

if Make["coils",2] < 1500 then {let market["coils",2] := market["coils",2] * 1.1;printf "Fewer than 1500 coils in week 2.\n";}else {let market["coils",2] := market["coils",2] * 0.9;printf "At least 1500 coils in week 2.\n";}

7 Some Useful Functions

The following are some helpful functions that can be used in arithmetic expressions:

• ceil(x) : next higher integer

• floor(x) : next lower integer

• precision(x,n) : x rounded to n significant digits

• round(x,n) : x rounded to n digits past the decimal point

• round(x) : x rounded to the nearest integer

20

Page 21: AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared … · 2018-09-07 · AMPL: A Modeling Language for Mathematical Programming A Tutorial Prepared by: Kiavash

• trunc(x,n) : x truncated to n digits past the decimal point

• trunc(x) : x truncated to an integer (fractional part dropped)

• min(x,y,. . .): minimum of 2 or more arguments

• max(x,y,. . .): maximum of 2 or more arguments

• abs(x): absolute value

• sqrt(x): square root

• exp(x): exponential

• log(x): natural logarithm

• log10(x): common logarithm

8 Exporting Models in MPS format

The MPS format is a very common format used to store models. AMPL can export the modelin this format. The generated file can then be read into any solver such as CPLEX. By usingthe write command and giving the letter m at the beginning of the file name, AMPL exports thegenerated model in MPS format in a file with .mps extension. An example is

write ’mdiet’;

With this command the model will be stored in the file diet.mps in the MPS format.

If you like to export the model exactly as it is without any manipulation by the AMPL presolvermake sure the turn off the presolver by option presolve 0; before issuing the write command.

The MPS format gives the variables and constraints sequential codes. It is useful to have thecorrespondence between the names and these codes. To do this we can use the following commandbefore issuing the write command.

option auxfiles rc;

This will cause generation of diet.row and diet.col files along with the diet.mps file. The firsttwo files have the list of variables and constraints of the model in the order that are coded in theMPS file.

References

[1] R. Fourer, D. M. Gay, and B. W. Kernighan. AMPL: A Modeling Language for MathematicalProgramming. Duxbury (Thompson), CA, second edition, 2003.

21