Professional Documents
Culture Documents
A Modeling Language
Second Edition
AMPL
A Modeling Language
Second Edition
Rohcrt Fourer
Northwestern Univeisity
D a vi d M . G a y
A M P L Optimizatia) L L C
Princcton University
DUXBURY
THOMSON
A l i righfc nrxerwd. N « paul o f Ihis publicalicin nuv h: n.*produn.*d. sUred in a fttricval syxlem, o r
(suismittcd in inj' f<mi o r by xny mcauH. electronic. nu.-chinir.il. phcifcicapyirçs. rcccrdoig. o r
aOicrwKc. witfuiut flie pru* wríttcn pcrmi^kin a í <he publr^hcr. Prinled in lhe l.hiiícd Síaàrs o f
America. Pubhshed simultincuusly in C.uud.i.
About the authors:
Brian Kcrnighan received h& Ph.D. inelectrica) engineering from Princcton University in
1969. He w a s in the Computing Science Research Center at Bell Laboratories fxom 1969
t o 2000. and n o w Kraches in the Computer Science department ai frinceton. He is the
co-author o f several computer science booJcs. including Th? C Progrwwning Languagê
and The UNIX Programming EnvironmenL
Copyrisht O O T by Robcrf Fourcx, David XLGayaiid B r i » W . K o n ç l a n
Contents
Intniductkin xv
C l » j p t e r 4. B u l d i n » L * i * r r MadH* 55
4.1 A multocxmmodity traiKpciitilkin model 56
42 A multiperiad praduclkin model 59
43 A model af produetian juiJ traiKportUkin 63
vil
vfl W F L A W O C e . P*3 U W 3 U A 3 E F C R WATHEWAT CM. F R D G R A V M N 3
52 S e « s o f number* 75
53 Se« operaians 76
54 S d m e m h m h i p cípcratums aixJ funclions 78
5.5 Index mg exprcs*ions 79
5J6 O f d e f v d Heis 82
Predeíincd sct< aixJ in( cr vai cxpressxim 86
U i a p t r r 8. l i n e a r P i t g r m t : V a H a M o , O b j e c t f r d and C o m t r a l n t * 129
8.1 Varnbl» 129
8-2 I.xncoi cxpnrttktiK 132
8.3 Objccti ves 134
84 Corotraints 137
C l » a p l c r 9 . S p c d t y í n * Data 143
9.1 r o m u f t c d d a t i : (hc d a L a conimaixl 143
92 DatainKtfx 145
I-islx of o n : dimensional seis and jurameters 145
I-islx o f I w o dimemkirul set* oixJ pdranu.-t.Ts 146
Listx o f h i g h c r dimensional srtsand piramrtcrs 148
Combincd h * s o f SC* JLJXI p i T i m e i T t 151
9.3 Daninlabh» 151
T w o dniu:n\i<Hial ubVrs 151
T w o dimensional slices of hi£hcr dimeRskiiul dita 156
I b c h c r d i m e r e x i i u l lables 157
Choice o f f o n n a l 159
94 Otfier feafcjres of d u a « a t e m e n f c 1«)
IX-fauk vahiex 160
lixlcxi-d collcctumsof sct< 161
Initial valurs kw vohahlcs 162
A V R _ A WCC€L N 3 LAN3UAGE F C R WATHEMATCAL F T O 3 R W W N 3 VIII
Q i a p t r r 1 CL D a t a f e n r Acct-K 169
10.1 (jL-ner.ilpnncipk.-s o f daticornrqiondence \(f)
102 l u a m p l e s o f latile hindlms « a f c m c n f c 174
103 Rcodi ne d i l a f r o m relatatmal (atiles 1«)
Re adi ng p arame* rs on ly 1»)
Re adi ng a se< anJ juraniclers 182
Irstibbshing cones peind eives 1&£
Re adirçgolher vai ues 185
104 W n l i n g dala ( o n h l l o m l tibk-s 186
Writiqg rows m f c n e d í k h i lhe d i l a specificaikiits 186
Writorçs rows m f e n v d fixmi a key speci ficaik>n 189
10.5 Readirç; aixJ w r t m g lhe sane titiV: 191
Readirç; andwnCmg u s m g l w o L a b l c dcclaralions 192
Readirç; andwnCmg u s m g l h : some L a b l o dcclaration 193
10.6 Indexed colkvtkins o f Iatiles and columns 193
Indexrd collectionsof I atiles 193
Indexed collcctumsof d a t i c o h j m n s 1%
10.7 S U n d i r d a n J t i i n k in latile hindlers 197
Using lhe tfandard CM>BC latile hanJkrr 19S
Using lhe slaixlard ODBC latile hanJlcx wüh Access aixl lixcel 200
liuik «n latile hindlers kw letf and hiiurv files 201
Index 501
Coftyrçhl O 2003 by Robcrt Fourer. DtvkJ M . Qay ai»J BrianW. Kcrnishan
Introduction
A s our title suggests. there are t w o aspects I o lhe subject o f this book. T h e first is
maihematical programming. lhe optimi/aiion o f a funcik>n o f many variables subject t o
constrainfe. T h e second is the A M P I . modeling language. which w e d e s i g n e i and imple-
mentei! t o help p e o p l e use computers *> d e v e l o p and apply maihematical programming
models.
W e intend this book as an introduction both t o maihematical programming and t o
AMPI.. K>r readers already familiar w k h maihematical programming. it can serve as a
user's gukle and referente manual for the A M P I . software. W e assume n o pcevious
knowledge o f the subject h o w e v e r . and hope thai this bix>k w i l l also encourage the use o f
maihematical programming models by those w h o a r e new t o the fie kl.
Maihematical programming
T h e term " p r o g r a m m i n g " was in use by I9-10 k> describe the planning or scheduling
o f activities within a large organi/aiion. ' ' P r o g r a m m e r s " found thai they could represem
the ami>unt or levei o f each activity a \uriiible whose value was t o be determined.
T h e n they coukl malhe matkally describe the restrictions inherent in the planning or
scheduling problem a sei o f equations or inequalities involving the variables. A solu-
tion t o ali o f these itmsínúus woukl be considered an acceptable plan or schedule.
Hxperience six>n showvd that it was hard k> nnxlel a compkrx operaiion simply by
s p e c i f y i n g constraints. l f there w e r e t o o f e w constraints. many inferior solutions could
saiisfy them: if there were ux>many constraints. desirable solutions wxsre ruled o u t or in
the worst case n o solutions were possibkr. T h e success o f programming ultimately
dependôJ on a key insight thai provided a w a y around this ditTicuhy. One could s p e c i f y .
in addition t o the constraints, an objeelfre: a ftmction o f the variables. such as ci>st or pro-
fit, thai could be used t o decide whether one solution was bener than another. T h e n it
didn't maiter thai many dilTerent solutions satisfkrd the constraints — it was sufficient t o
find one such solution that minimi/cxl i>r maximi/ed the objective. T h e term /mtsht/miii-
uil prógranuning carne t o be used k> describe the minimi/atk>n or maximi/aiion o f an
objective functk>n o f many variables. subject t o constraints on the variables.
xvi NTFODUCTON
A M PI. olTers an interactive command environment for setting up and solving mathe-
malical programming probleirc. A flexible interface enables several solvers *> bc avail-
able at once so a user can switch among solvers and sekct options that may improve
sol ver performance. Oncxr optimal sohitions have been found. they are automatically
translawrd hack to the m o d e l e i s form so that peopb can view and analyze them. AH o f
the general set and arithmetic expressions o f the A M P L nnxleling language can a l i o be
used for displaying data and results: a variety o f optioos are available ii> formai data for
bcowsing. printing repons. or preparing input k> other programs.
Through its emphaiis on A M P L thfc lxx>k differs considerably from the presentation
o f nnxleling in standard mathematical programming fcxts. The approach taken by a typi-
cal textixx>k is still strongly infhienced by the circumstances o f 30 years ago. when a stu-
dent might be lucky to have the opportunity *> solve a f e w small linear programs o n a n y
actual computar. As encouniered in such textlxx>ks. mathematical programming ofien
appears to require only the conversion o f a " w o i d probkrm" mio a small system o f
inequalities and an objeetive function. which are then presentcd to a simple optimi/ation
package that prints a short listing o f answers. W h f l e ihis can be a good approach for
intrixluctory purpixses. it is not \v\>rkable for dealing with the hundreds or thousands o f
variables and constraints that are found in mo&t real-world mathematical progran*.
W e have not attempted u» oover lhe optimi/ation theory and algorilhmic detaik that
oompr&e the greawrst pan o f mo&t mathematical programming texts. Thus. for readers
who want to study lhe whole field in some depth. ihis lxx>k is a complemeni to ex&ting
textlxx>ks, not a replacement. O n the other hand. for those whose imiiudiate concem is
to apply mathematical programming t o a particular problem, the book can provklc a use-
fui mtxoduction on itsown.
T h e second odition. like the first, is organi/ed conceptually mto four parts. Chapters
I throughl are a tutoria] introduction tomodels for linear programming:
These chapirrs are intended to gel you staned using AMPL ai quickly as possible. They
include a brief review o f linear programming and a discussion o f a handful o f simpkr
modeling ideai thai underlie moca large-scale optimizatk>n problenfc. They a b o illustraic
how to provide the daia thai convert a nnxlel n t o a specific problem instante, how to
solve a problem. and how to d&play the answeo.
T h e next four chapters describe the fundamental components o f an A M P L linear pro-
gramming nxxlel in deiail. using mote complex exampkrs to examine major aspects o f the
language systematically:
5. SimpleSetsand Indexing
6. Compotmd Sets and Indexing
7. Parameters and Expressk>ns
8. Linear IVograms: Variables, Objectives and Constrainti
We have tried to cover the mo&t important feaiures. so thai these chapters can serve ai a
general user's guide. Each feature is introduced by one or more examples. building oci
previous examples wherever pos&ible.
Thefolknving six chapters describe how to use A M P L in more sophisticatcd \vays:
9. Specifying Data
IO. Datahaie Access
U . Modeling Commands
12. Dtvplay Commands
13. Command Scripts
14. In*ractk>ns wilhSolvers
The first two of these chapters explain how k> provide the daia values thai define a spe-
cific instance o f a nnxlel: Chapter 9 descri bes AMPL's fcrxt file daia formai, while Chapter
10 presents fea tires for access to informaiion in relational databaie systentv. Chapter 11
explains the commands that read modeb and data. and invoke solvers; Chapter 12 shows
how to dtvplay and save resulfc. A M P L provkles facilities for creating scripfc of c o m -
mands. and for writing l o o j » and oonditional staiements; these are coveied in Chapter 13.
Chapter 14 goes into more detail on how k> interact with solvers so ai to make the best
use o f their capabilities and the information they provide.
Finally, w » turn k> the rich v a r k t y o f problems and applicatk>ns beyond purely linear
models. The remaining chapters dcal with six importam special caies and generaliza-
tions:
XX NTFODUCTCN
Chapters 15 and lòdescribe additk>nal languagc feaiures thai help AMPL represem par-
ticular kinds o f linear programs more naturally, and thai may help to specd translalion
and solution. The b i t four chapters oover gcnerali/aiions thai can help modek k> be
more realistic than linear programs. although they can alio make the resulting optimiza-
tion problems harder tosolve.
Appendix A isthe AMPL referente manual: it describes ali languagc features. includ-
ing some not mentioned elsewhere in the text. Bibliography and excrcise* may be found
in mo&t o f the chapicrs.
A M P L ha* evolved a lot in ten years, but hs core remains esáeniially unchangcd. and
almost ali of the mixlcls from the first cditk>n work with the current program. Although
we have made substantial revisk>ns throughout the irxt, much of the br and new material
is conccntratcd in the third pari where the original single chapter on the c\>mmand envi-
ronment has been expanded into five chapters. In particular, databaie atvcss. scripts and
programming constmcfc represem oompletely new material, and many additional A M P L
cx>mmands for examining mixlcls and accc*sing sol ver informaiion have been added.
T h e first edition was written in 1992, just before the cxplosion in Internet and w * b
use. and while personal oomputers ware siill rather limivrd in their capabilhies: the first
student versions of A M P L ran on IXXS on tiny. slow machines. and were diitributcd on
floppy dtvks.
Today, the \v\rb site at w w . a m p l . c o m a the central sourcc for ali AMPL informa-
iion and software. Pages ai th& site cover ali that you need to Lrarn about and experiment
with optimi/alion and the use o f A M P L :
• Free versions of AMPL for a variety o f operating systems.
• Free versions of several solvers for a variety of probkrm types.
• AH o f the model and data files used ai examples in this txx>k.
The free software is fully funetionah save thai it can only handle pcobleim o f a few hun-
dred variables and constraints. Unrcstrictcd commercial versions of AMPL and solvers
are avaflable as w*D; see the website for a l&t o f vendors.
Y o u can a b o try A M P l . without downloading any software, through browser inter-
faces ai u v r f . â n p i . c o m / T R Y A X ? L and the NHQS Ser ver ( n e o s .rrves . a n l . g o v ) .
The AM PI. web she also provides informaiion on graphical user interfaces and new AMPI.
language features. which are under oontinuing developmeni.
N1F9QDUC1CN XXI
W e are deeply gratelul t o Jon Bentlcy and Margaret Wrigjht, w h o made extensive
oomments on seve/al dralts o f the manuscript. W e al&o receivod i r a n y helpful sug^es-
tions on AMP1. and the txx>k f r o m Co)leite Coullard. Gary Cranier, A r n e Drud. Grace
Emlin. GusGavsmann. Eric Grasse, Paul K e l l y . Mark Kernighan. T o d d L o w t B o b Rich-
ton. Michael Sauikkrs. Robert Seip, LaLshman Sinha. C h m V a n W y k , Juliana Vignali.
Thong Vukhai.-. and ütudents in lhe mathematical programming clames ai Northwxstern
Univershy. Lorinda Cherry helpoJ with indexing, and Jerome Shepheard with typeset-
ting. Our sincere thanks t o ali o f them.
Bibliography
IL M . 1.. Hcalc. "Matri* Gcncraksx and Oulpul Arulyzcrs." In llairald W . Kuhn (cd.), Procerd-
in$s <jf lhe PtinrrJm Sympasium an \{<i!hr/)kitictil Pmx>tv}w\in%, Princcton IJniwrrsily PJVSS
(Princctcin. NJ. 1970) pp. 25-36. A hisUrv and cxpUnatian o f nialrix gener.il<r software for linear
pxigrammirçg.
Johonnes Ifoschop and Alexander Mecraus, " O n lhe IX-vekipmcnl o f a General A ^ e l r a i c Model
irçg System m a Str.i«e£ic PUnnirçg Enviranmml." Malhemalical Programmirçg SluJy 20 (1982)
pp. 1-29. An mtroductian IoGANIS. oneof lhe firsl andmosl widely used algcbraic modclm^ lin
guines.
Robert IL Ihxby. "Solving Real W<*ld linear Programs: A Decade anJ More o f Progre**." <)pcr
otians Rcvarch 50 <20(12) pp. 3>-15. A histcry o f reccnt advancx-s in solrevx for linear program
mirçg. Also in Ihis issue are accounls o f lhe early dtys o f nUhenialural pragramnung b) pkinccrs
ofCiefiekl.
George II. Dart/ig, " l i n e a r Programmirçg: The Stcry Abou! How I( Ilc£in." In Jan Karel L e m
lau AkrxaixJer II. G . RinncKiy Kan aixJ A k:\aixJer Schrijrer. eds.. //«mry <if Malhtmalka! Pm
RnwvjiinR: A Cal Irei i/n» of Ptrsnnal Rrminuictncrs. Iskirlh liillaixl (Amslerdim. 1991) pp. 19-31.
A sourcx" f<r our brief occounl of lhe hKfcirvof linear programming. Dinl/jg was a pkincvr of surh
kcv ideas as objeclive functkim ax*J lhe simplcxalgorilhm.
Robert Tourer. "Modeling I-inguages rersu* Malrix Oenerofcirs f<* Linear Programming." ACM
Traniuctkim on Malhenialical Software 9 (1983) pp. 143- 183. The case for modeling linguages.
C . A . C . Kuip, "A|gctraic Languiges f<r MjÉietiuicml FVc»granuiuns." Huropesm Jounul o f
Opcmianal Research 67(1993) 25-51. A sur\x*>'.
CopvrishtO 2003 by R<*>crt Fourcx, DavidM. Oay and Brian W . K a n ç h v i
1
Production Models:
Maximizing Profits
1
2 FBDCCCTCN V O C & S W A X W Z N 3 PttOF.TS CHVTÇR1
T o funhcr complicate ma t te rs. the f o l b w i n g w e e k l y production amounts are the most thai
can be justified in light o f t h e currenily bookcxl orders:
T h e questk>n facing the company is as foDows: I f 4 0 hours o f pnxluctk>n time are avail-
able this wxrek. h o w many t o n s o f bands and h o w many tons o f c o i l s shoukl be pnxluced
t o bring in the greatest total pcofit?
W h i l e w e are g i v e n numeric values for pnxluction rates and pcr-unh profits. the tons
o f bands and o f c o i l s t o be pnxluced are as yet unknown. These quanthies are the deci-
sion i w i i t b l t s whose values we must determine s o as t o m a x i m i z e profits. T h e purpose
o f the linear program is *> s p e c i f y the profits and productk>n ümitaiions ai explicit for-
mulai involving the variables. s o thai the desired values o f the variables can be deter-
mincxl systematically.
In an algebraic statement o f a linear program. it is customary t o use a maihematical
shonhand f o r the variables. T h u s w ê wiU wrhe -V # for the numbcr o f tons o f bands t o be
pnxluced. and X c f o r k>ns o f c o i l s . T h e total hours k> pnxluce ali these tons & then given
by
This numbcr cannot exceed the -10 hours available. Since lw>urs per ton is the reciprocai
o f the tons per hour given above. w e have a consinunl on the variables:
0 £ X a £ 6000
0 í X c £ 1000
SECT-GN 1 1 ATY/OVARAHLE LNE/flFTOGWW 3
In the statcmcnt of the problem above, the upper limits worc speeified, but the k>wer lim-
its wene assumcd — it was obvious that a negative productk>n of hands or cofls would be
m e a n i n g l ê s IXaling with a computer, howxrver, it is necessary to be quiic expliciL
By analogy with the formula for total hours, the total profit must be
That is. our objeetive is *> maximize 25 Xü + 30 Xc. Puoing this ali together, have
the following linear program:
This is a very simple linear program, so we' 11 solve h by hand in a couple o f ways, and
then check the answer with AMPL.
First, by multiplying profit per ton times tons per hour, can determine the profit
per hour o f mfll time for each product:
Bands are ckrarly a more profitable use o f mill time, so ii> maximize profit we should pro-
duce ai many bands ai the produetion limit wfll allow — 6,000 tons, which takes 30
hours. Then should use the rcmaining 10 hours to make cofls — 1,100 tons in ali.
The profit is$25 times 6,000 tons plus $30times 1,100 tons, f o r a total o f $ 192,000.
Ahernaiively, since there are only two variables, can show the possibilities graphi-
cally. If XB values are ploncd ak>ng the horizontal ax&, and Xc vahies ak>ng the vertical
axis, each point reprcsenti a du>ice of values, or solution, for the dccision variables:
4 F F O D U C T C N W O C S - S : W A X W ZNG PRCFTS CHífTÇR 1
Co*
Ba^
0 2000 4000 6000 SÜÜO
N
COJÜ
CcttK 4000
N
o Ba^
0 2000 4000 6000 S000
SECT-GN 1 2 THE TY/O V A R A H L E L N E A R F R D 3 W W N A W F L 5
T h e line segment for profit equal t o $135,000 is panly within lhe fea&ible region: any
pt>ini on this line and within lhe region corresponds n> a solution lhat a c h i e v e s a profit o f
$135,000. O n the other hand. the line for $220,000 does not interseet the feasible region
at ali: this tells us that there is n o way t o achieve a profit ai high as $220,000. Vfexwxl in
this w a y , solving the linear program reduces t o a n s w ^ i n g the f o l l o w i n g question:
A m o n g ali profit fines that interseet the feaüible region, which is highest and funhest t o
the right? T h e answxrr is the middle line, which just touches the region at one o f the oor-
ners. This point corresponds k> 6,000 tons o f bands and I.-100 *>ns o f c o i b , and a profit
o f $ 1 9 2 , 0 0 0 — t h e same ai we found before.
v a r XB:
v a r XC;
maximize P r o f i t : 2S * XB 30 * XC:
s u b j c c L Lo T i m e : < l / 2 0 0 j * XB «• <1/14 0 ) * XC <= 40:
s u b j c c L Lo B _ l i m i L : 0 <= XB <= 6 0 0 0 :
s u b j c c L Lo C _ l i m i L : 0 <= XC <= 4 0 0 0 :
ampl: aolvo;
M1MDS S . S : o p t i m a l s o l u L i o n f o u n d .
2 i L e r a L i o n s , o b j o c L i v c 192 000
ampl: quit;
Maximize: Z'7*/
0 £ X} £ ur for estchjeP
s*t P;
param a ( j in P};
param b ;
param c ( j in P};
param u ( j in P};
var X ( j in P};
maximize T o t a l _ P r o £ i t : num ( j in P} clj] * X[jJ:
subjcct Lo T i m e : sua ( j in P} <l/a(jl) * X [ j J <= b ;
subjccL Lo L i m i L (j in P } : 0 <= X l j l <= u[jJ:
to process by a program. There are A M P L constmctions for each o f the basic components
listed above — sets. paramefcrrs. variablcs. objectives. and constraints — and ways to
wrke arithmetic expressions. sumi over sets, and s o o n .
W e first give an AMPL model thai resembles our algebraic model ai much ai possible.
and then present an improved version that takcs better aJvantage of the language.
For the baiic produetion model o f Figure l - l , a direct transcription into A M P L would
look like Figure 1-2.
T h e key word s e t declares a set nane. a* in
ML P:
The membersof set ? will be provided in separa* data stakrments, which \vv?'ll show ina
moment.
param b ;
or a oollection of values indexed by a set Where algebraic notation says that "there is an
n f for e a c h ; in P ' \ o n e writes in A M P L
param a (j in P};
which means that a is a collection o f parameter values. one for each member o f the set P.
Subscripts in algebraic notation are written with square brackets in AMPL. so an individ-
ual value like a i is written a [ j ) .
T h e v a r declaratk>n
var X ( j in P}j
names a collection o f variables. one for each member o f P, whose values the sol ver is to
determine.
S E C T tON 1-4 THE L N E A R F T O 3 R W W N 3 M D C € L N A W F L 9
The name T o t a l _ P r o £ i t is arbitrary: a nanie is required by the syntax, but any name
Will do. The precedence of the sum operator is lowxrr than thai of so the expression is
indeed a sum o f pnxlucts. as intended.
Finally, the constraints are given by
The T i me constraint says that a certa in sum over the set ? may not exceed the value o f
parameter b. The L i m i t constraint is aetually a family o f constraints. one for each
member j o f P: each X [ j ] is bounded by zero and the corresponding u [ j 1.
T h e constmct { j in P } is ca lie d an indexing exprêssian. As you can see from our
exampkc, indexing expressions are used not only in declaring parameters and variables,
but in any context where the algebraic model does something * 'for each j in P". Thus the
L i m i t constraints are decLared
subject to Limit (j in P}
because \v>í want to impo&e a dilTerent restriction 0 < = X I j ] < = u t j ] for each different
pnxluct j in the set P. In the same way, the summaiion in the objective is written
to indicate thai the dilTerent terms c l j l * X ( j J, for each j in the set P, are to be added
together in computing theprofit.
T h e layout o f an AMPI. model is quiie free. Sets. parameiers. and variables must be
dcclarcd before they are used but can other wise appear in any order. Staicments end with
semicolons and can be spaced and spüt across lines k> enhance readabilhy. Upper and
lowor case letters are dilTerent, so t i m e . T i m e , and T I M E are three dilTerent names.
Y o u h a v e undoubiedly noticed several plaees where traditional mathcmalical notalion
hai been adapied in AMPI. to the limitacions o f normal kcyboards and character sets.
AMPI. uses the word sum instead o f L t o express a summaiion, and i n ralher than € for
set membership. Set specificatk>ns are enckxsed in braces. as in { j i n P ) . Where math-
ematical notation uses adjacency tosignify muhiplicaiion in * j X r AMPI. uses the • oper-
ator of most programming Languagcs. and subscripts are denoted by brackets. so C j X j
becomesc l j 1 • X I j ) .
Y o u will find thai the rest of AMPI. is similar — a few more arithmetic operak>rs, a
f e w more key words üke sum and i n . and many more ways to specify indexing expres-
sions. Like any other computer tanguage, AMPI. a precise grammar, but w e won't
stress the mies too much here: most will become clear ai we g o a l o n g . and lull deiails are
given in the reference manual, Appendix A .
Our original two-variable linear program is one of the many L W thai are instances o f
the Figure 1-2 model. T o specify h or any other such instance. need tosupply the
10 FRXUCT C N W C C € L S : WAX V Z M 3 P R D F T S CHífTÇR 1
s o l F : = bands coils:
pa ram: a c u :=
banâs 200 25 6000
coils 140 30 4000 :
param b : = 4 0:
membership o f P and the values o f the various parameters. There is no standard way to
describe these daia values in algebraic notation: usually some kind of informal tables are
used. such as the ones showwl earlier. In AMPL, there & a speeific syntax for data
tables. which 6 sufficiently regular and unambiguous to be translated by a computer.
Figure 1-3 give* daia for the basic productk>n model in that form. A s e t stakrment sup-
plies the members ( b a n d a and c o i l s ) o f set P, and a p a r a m table gives the corre-
sponding vahies for a , c , and u. A simple pararnstatement gives the vahie for b. These
daia staiements, which are described in detail in Chapter 9, have a variety o f options that
let you list ortabubte parameters inconvenient ways.
An improved model
W e could g o on immcdiately to solve the linear program defined by Figures 1-2 and
I -3. Oncvr w e have written the model in A M PI., howvver, need not feel constrained by
ali the conventions o f algebra. and w e can insiead conskler changes that might make the
model easier to worlc with. Figures I - l a and I-4b show a possible 4 'improved*' versk>n.
The shon " m a t h e m a i i c a r names for the sets, parameters and variables have been
replaced by longer, more meaningful ones. The indexing expressk>ns have become {p
i n P R O D ) , or just ( P R O D ) in those decbrations that do not use the index p. The
bounds on variables have been placed whhin their v a r declarai ion. rather than in a sepa-
rate constraint: analogous bounds have been placed on the parameters, to indicatc the
ones that must be positive or nonnegative in any meaningful linear program derived from
the model.
Finally, oomments have been addcd to help explain the model to a reader. Comments
begin with * and end at the end of the line. As in any programming bnguage. judicious
use o f meaningful names, comments and formatting helps to make A M P L models more
readabke and understandable.
There are always many ways to describe a particular model in AMPL. It is left to the
modelar topick the way thatseems clearest or most convenient Our earlier, mathemati-
cal approach is often preferred for working quickly with a familiar model. On the other
hand. the socond version is more attractive for a model that wfll be maintained and modi-
fied by several people over months or years.
S E C T CN 1.4 T H E L N E / « F B D C R f t W M N j W C C € L N AhFL 11
I f we put ali o f the nuxlel declaratk>ns in*> a file called s t e e l .sted. and the data
specification into a file s t e e l . d a t , then ai before a solution can be found and dis-
played by typing just a few statements:
a m p l : diaplay Kako;
Make l * 1 : =
bands GOOO
coils 1400
The r > c d e l and d a t a c\>mmands each speeify a file k> be read. in this caie the nnxlel
from s t e e l .mod, and the daia from s t e e l . d a t . The use o f two file-re adi ng com-
mands encourages a clean separatk>n o f nxxlel from data.
Filenamescan have any form recogni/od by your com puter's opera ti ng sysiem: A M P L
doesn'tcheck them for correctness. The filenames here and in the restof the book refer
toexample fiksthat are available from the AMPL w e b site and other A M P L distributions.
12 F R X U C T CN W C C € L S : WAX V Z M 3 P R D F T S CHífTÇR 1
Once lhe nuxlcl hai been solved. \v>í can show the optimal values o f ali o f the vari-
ables M a k e [ p ] , by typing dioplay The output fiom d i s p l a y uses the same
for mais ai A M P L ilata input. so that there is only one set o f for ira ts to krarn. (The t * 1
indi caies a variable or parameter with a singkr subscript. It is not strictly necessary for
input. since >íake is one-dimensional, but d i s p l a y prints it ai a reminder.)
Catching errors
Y o u will inevhably make some mtitakesas you developa modeL A M P L detects vari-
ous kinds o f incorrect statementi. which are reponcd in error messages following the
n o d e l , d a t a or s o l v e oommands.
A M P L catches many errors ai soon ai the modcl is read. For exampkr. if you use the
wrong syntax for the bounds in the declaraiion of the variable >£ake. you will receive an
error message like this. right altar you enter the r > c d e l command:
s t o o l . m o d . l i n e 8 ( o í f s e t 2S0J Í
.T/nLax e r r o r
c o n L c x t : v a r Make ( p i n PttDD> » > 0 < « <= Mak« [ p ] <= market [ p ] :
s t o o l . m o d . l i n e 11 < o £ £ s « t 3 3 9 ) :
make i s n o t do f i n o d
c o n L c x t : maximizo T o t a l _ P r o £ i t :
num ( p i n PWDD} p r o f i t l p ] * » > make[pl « < :
In each caie. the offending line is printed. with the approximatc location of the error sur-
rounded by » > and < < < .
Other common sources o f error messages include a mixlel component used before it is
declare d. a missing semicok>n ai the end o f a command. or a reserved \v\>rd like su.-n or
i n used in the wrong conlext. (Section A . I contains a l&t of reserved words.) Syntax
errors in daia statementi are simibrly reported right after you enter a d a t a c\>mmand.
Errors in the daia vahies are caught after you type s o l v e . I f the number o f hours
wvrre given ai —10. for instance. you would see:
It is good practice ii> include as many validity checks as possible in the modcl. so that
errors are caught at an early stage.
Despi te your best eíTorts to formulai? the modcl correctly and to include validity
checks on the data. sometimes a mixlel that g e n e r a i s no error messages and that elicits
SECT-GN 1 5 A E O N 3 LO//&R B O J N D S T O THE W C C € L 13
an "optimal solution" report from lhe sol ver will nonetheleis pnxluce a clearly wrong or
mcaninglcss solution. Ali o f the pnxluction leveis might be zero, for example. or the
pnxluct with a lower profit per hour may be pcoduced at a higher volume. In caies like
these, you may have to spend some time reviewing your formulation before you discover
what is wrong.
T h e e x p a n d command can be helpful in your search for errors, by showing you how
AMPL instantiated your symbolic nnxlel. T o see what AMPL generaied for the objeetive
T o t a l _ P r o £ i t . for example, youcould type:
a m p l : oxpand T o t a l Profit j
maximize T o t a l _ P r o f i t :
25*Make ( v bands ' 1 «• 30*Mak«['coils');
This corrciponds directly to our explich formulation back in Section 1.1. Expanding the
constraint works similarly:
a m p l : oxpand Tixao;
s u b j e c L Lo T i m e :
D. 0 0 5 * M a k « [ ' b a n d s ' ] «• 0. 007 142BG*Make l • c o i l s • 1 <= 40:
a m p l : oxpand Kako['coila');
C o e f f i c i e n L s of M a k e l • c o i l s • 1 :
Time 0.00714286
ToU»l_Prof i t 30
Either single quotes < ' ) or doublequotes < • ) may surround the subscript.
Suppose first thai add another product. steei plate. The nnxlel stays the same. but
in the data have to add p l a t e k> the list o f members for the sei PROD, and w have
toadd a lineof paramctcr values for p l a t e :
We pui this versionof the data in a file calkrd s t e e l 2 . d a t . and use A M P L ai before to
get thesolution:
Piofits have incrca&ed oompared to the two-variable versk>n. but now it is best to pnxluce
no ooils ai ali! On closer examination. thii resuh is not so surprising. Plate yields a pro-
fit ofS-1610 per hour, which is leis than for bands but more than for coils. Thus plate is
pnxluccd toabsorb the capacity not taken by bands: coils would be pnxluccd only if both
bands and plate reached their markct limits before the availabkr hours wxrre cxhausfcrd.
In reality, a whole pnxluct line cannot be shut down solely to incrcasc wviekly profits.
The simplest way to reílect this in the nnxlel & to add lower bounds on the prtxluction
amounts. a* shown in Figures l-5a and I -5b. We have dcclarcd a new collcction of
paramctcrs namcd correnít, to represem the lo\v>ír bounds on productk>n that are
imposed by sales commitmcntv. and \v>í have changed >= 0 to > = c c r e n í t t p ] in the
declaraik>n o f the variables Jíake [ p ] .
After lhese changes are made. can run AMPL again k> get a nn>rerealistic solution:
Figure l - 5 a : Lowerboundsonproduetion(steel3.mod).
produee bands up to the market limit. and then to produee plate with the remaining avail-
able time.
s u b j e c t t o Time ( s i n OTAC3B}:
sun ( p i n PttDD} < 1 / r a t e lp. s ) J * M a k e l p l <= avail[s];
4 In e a c h s t a g e : t o t a l o í b o u r s u s o d by a l i
4 p r o d u e t s may n o t e x c e e d h o u r s a v a i l a b l e
s u b j e c t t o Time ( s i n 5TAGB}:
sum ( p i n PROD} < 1 / r a t e [ p . s 1J * Make[p| <= a v a i l ( s i :
ampl: raaot;
a m p l : xzodol atoolé.xsod: data otoolá .dat; aolvoj
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
«1 i t e r a t i o n s . o b j e c t i v e 190071.4286
S E C T - G N 1.6 A C O W 3 R E S O U R C C O O U S T R f c N T S T O THE W C C € L 17
a m p l : diaplay Tiizo;
Time l * | : =
rohcaL 1800
roll 32 00
*XTI.'J*U«;VMtM • l 1
llle te* tftvw l>\plíY V.W lu« • HIM
:
• tvrfi rr H-«-» «»»-- -»
• ptt^it-J to? rot «roer 1
/ «
/
'1
1.7 A M P L interfaces
T h e examples that wvr have presented so far ali use A M P L ' s cx>mmand interface: the
user types textual commands and the system responds with textual results. This ts what
wvr will use throughout the book t o illustrate A M P L ' s c a p a b i l i t i e s . It permifc a c e e s s t o ali
o f A M P L ' s rich collection o f features. and it w i l l be the same in ali environments. A
text-based interface i s m o s t natural for creating scripts o f fr&juently used commands and
for writing programsthat use A M P L ' s programming constructs<the t o p i e s o f Chapter 13).
And text commands are used in applk.ations where A M P L is a hklden or behind-the-
scencs pan o f s o m e larger process.
SECT.QN 1.7 W F L NTEFFACSS 19
VAMM/TK
Bk- E»« vtew 3cml Hz\ç>
New Mricf Dafcx 3av? Otyifcy fVcv Mrar.| Fml:
l |d w:liv cc.nl. WiU. nsiVít Mo«i»V7«>vWW©cO;iwl
rrmjçnpl A PKO-- *
•
p«rui í » t t :?n:o > C. * oecà^ctc. tem p:r
• •• J -vlvv A . J .'.VÍl > C: ^ li.* U' úi «
t pccí:- ÇÍC
:i v»<i»Mm, »I lin**r
1 cicalmin .. iiU LirMdi: 3 :LIK«I .'Í cmarít. |;nia| >- fl; » I r w i l i i i t "O »/in«
1 LcAãi .vUví: 2 Íüoti-^a. .^I/Al l.'HULI >- 0: 4 l.B.L .11 IVUU
M-Kft- «". «rr.iral A-.Inhi-n fnrrf
2 i:i.-«tíoM* eb : ves;T« l^SIS Í714
IVWl 1'i.r.l: J*. ÍJ. iu.*tttLI
- C coroit, r»<k»t.
í lh)«r.hv* tatal prrr^tji -r.-k
buu). 1MÚ tOM
v.il; :430 SM
<VU
V M" PTS"ft h r í * «Vil» p
- JU-
m ÍVU.
Í.M I • •AII m r.n ^1111
.CO
JKC9* -vMl -
AU that said. howvrver, there are plenty o f time* where a graphical user interface can
make a program catier *> use, helping novices t o get started and cavual or infrequent
users t o recall details. A M P L is n o exceptk>n. Thus there are a variety o f graphical inter-
faces f o r A M P L kx*sely analogous t o the ''integraicd devek>pment e n v i r o n m e n t s " f o r
conventk>nal programming languages, though A M P L ' s environments are much l e s s e l a b o -
rate. A n A M P L graphical interface typically provides a w a y *> easily execute standard
c\>mmands. set options, invoke solvers, and d i s p b y the resulfc, often by pushing buttons
and selecting menu kems instead o f by typing cx>mmands.
Interfaces exist f o r standard operating system p b t f o r m s . H>r example. Figure l-7a
shows a simple interface based on Java that runson Unix and Linux, W indows, and M a c -
intosh. presenting much the same appearance on each. ( T h e M a c interface is s h o w n . )
Figure I - 7 b shows a similar interface b & e d on Tcl/Tk, shown running on Unix but also
ponabkr t o W i n d o w s and Macintosh. Figure l - 7 c shows another interface, creatcd with
Visual BasL- and running on W i n d o w s .
There are also web-based interfaces that provide client-server access t o A M P L or
solvers over network connections, and a number o f application program interfaces
( A P T s ) for calling A M P L from other programs. T h e A M P L w ^ b site, v w v . a m p l . c e a x
provides u p t o date information on ali types o f availabkr interfaces.
20 FRCOUCT CN WCC€LS: VAX M ZP*3 P R D F T S CKVTER1
Bibliography
Julius S. Aronofsky. John M . Dutfon xixi Michicl T. T a y ^ U i n , Xíanagtrial PiannínR wtíh IJn
tar PmjyamnúnR: In Prcctsx InSusüy Operdians. John Wfley &. Sons (New York. N Y , 1978). A
ddoilcd occounl o f a variety o f profit nLi\imi/.in£ jLpphc.ition*. wiéi cmpfUKK on éie petrobum
arxl pctrochemicil industries.
Vifefc C h v í u l . LÀntar Piv&amminx* W . II. rrecimn (New Y<rk. N Y . 1983). A eoncise xixi eco
nomicd introduclkin I» thc<nv<x.il JLndalgorithnüc topic* in linear pfqgnmming.
Títxir r^tnan. " A Linear Progrinuning Modcl of Integratcd Iron aixJ Steel Productian." Marucc
mei* Scimcr 4 (1958) pp. 415-449. A n applicatkin k» ali stiges of xfcclmaiirç; — fram c o i l JUKI
qk tfirough finishcdproducls — firam lhee-ulydays o f K n » pograaiaiiiç.
Robeft Lourer anJ (joutom Dutüu " A Sunry of M a t i e u u i c i l Prqgrammin£ Apphcatums in Inte
giUcd Steel Plonls." Monufacturíng A: Service Operolkim M-in-iscnicnt 4(2001) pp. 387-400.
ftivxJ A . Kcndrick. Ak-x-inJer M C C T J L U S JLIKÍ JJLOIU: Alofcirre. J7J<- Pbinninj; of Invranvnl Pro%mn\s
inl)v Sstfl IneJuxD-y. T h : Johro Hopkiro IJravvrsHy Pnrss (BahimOfe. M D . 1984). Severaldeiuk-d
nurthenutical progrjLmmirçg modcl*. usinclh: Mexican steel inJwtry as jui cxjunpk-.
Excrcises
1 - 1 . TTirs e x e r c i t e slorfc with a ( w i variable linear pregram similar in slru^ure Io the ora? cif S o e
Ikim 1.1 and 12. butwith a quite diflercnt slery behmd it.
( a ) Y o u ojx- in charge cif an adverti-a ng campugn fcir a i r w preieiuct wíéi a budccl o f 51 mil liem.
Y o u can adverti se cm T V o r in magn/ines. O n e mmute of TV" time ceists $20.000 and nraches
million polential cuetomers; a nuca/me pa^e ce^t* SI(1000 JLHJ radia 1 míDíoa. Y o u muct sign
up fer aA b i s l 10 minutos o f T V time. I l o w sheiukl you spend your bue^gel to m a x i m i z e your aueii
ence? Formula*? lhe probkrm «n A M P L and solve i t C h e d éie seilutkin by hind inmg aí I c w l eme
o f lhe appmaches ek-scribed m Seclkin 1.1.
<b) It tikes aeaávc tilent Io crente e f f e d i v e ad\x-rti<ing; in your ergani/atiem. it takex Ihree
persem wx-cks Io enrole a nuca/me j u g e . and on? person w c v k ( o ctcaAc a T V mmute. Yeiu h i v e
onlv 100 persem wx*vks availibk*. Aekl thrs ceimlraint lo t h : meidel and determine heiw you sheiukl
neiw speraJ veiur budçel.
( c ) Radk» ad\vrtr*mc nraches a quaftcr milhem peopfe per minute, cosls $2.000 per minute. arai
xequives only 1 person day o f time. Iferw d a » lhr< médium affecl your sohitiems?
( d ) I l o w does lhe seilutkin chinge if you Juve l o sign up fer al k-asl ( w o W g u i n ? juges? A maxi
mu m eif 12 0 mi nu les ei f raeb ei?
1 -2. U i e sleel meidel eif úm chapter can be further modified to reflecl varkiu< changes in preiehic
Ikm requiremeiUs. For each pari belerw. expiam the meiehfuraikim Co l o u v e s 1 6 a and 1 6 b Ihil
would be xx-ejuned l o achiesv lhe ek-snx-d changes. ( M a k e each charçge separalely. ralher thin accu
mu lati ng lhe chinges fremi eme part l o lhe n e x t )
(a> I l o w weiukl you chinge lhe cemslramfe se» lhal leital kiurs m e d by ali preieiuct* mu«l rqi*il lhe
leital hcmrs avaibbk* fer each slage? S o l v e lhe linear preigram with Ihrs clunge. and verify Ihil y o u
g d lhe « m e resulta. Ilxplam w h y . inlhis c a » , Ihere is no diffcrence in lhe seilutkin.
<b) H o w weiukl vou add l o lhe meidel l o ix-slricl lhe fcilil wx-ighl eif ali preidiKls Io be lcfitt Ihin a
new p n m e l e r , n v a x _ w c i g h t _ ? Sol\e lhe linear preigram for a weight limil o f 6500 tom, axxl
explun how Oik extra ix-slrictiem changes lhe ix-suks.
( c ) The incentive syslem for mill moiugers may lend locncxiuragc lhem to preidi^e as many tom as
pertsible. Iferw would vou change lhe objecti\x- funclkin l o maximi/e leital lems? Ter lhe dati eif
our example. dex-s ihis make a cfiffcraice l o lhe optimal soluliem?
( d ) Suppose lhal imlead o f lhe leiwer bounds nrpnrsenled by cccnmiL l p 1 in eiur moelel. w e want to
xequae lhal each preieiucl t e f e s c r t a ceitiin share o f lhe leital tom pfoduced. In lhe a^gefraic neita
I k i n o f I^guie 1 - l . l h i s new- ceimlraint misht be nrpnrsenled as
where s. K lhe m m i m u m s h i r e asscciafcd with projecl j. I l o w would JXIU change lhe A M P L model
l o use Üik ceimlraint m pUce o f lhe kiwx*r beiuixls c c c i m i L l p | ? If lhe mmimum shanrs aix- 0.4 for
b^ieis and plale. aixl 0.1 fer c o i K whal k lhe seilutkin?
V e r i f y Ihil i f y e j u chai^ge lhe minimum shan.-s Io 0.5 for baixJs aixl plale. aixl 0.1 for c e i h . lhe l«n
cai preigram gives an 0p4imal seilutkin Ihil proehicx-s neithii^, al z e r o preifit Ilxplam why Ihrs
makes s e m e .
22 FRCCCCT QN WCC€LS WAX W Z M 3 P R D F T S CHífTÇR 1
<e) S u p p o » there is an .ukJitkirul fmwhírçg s t i g e for pUtes onlv. wiéi a cajucity of 20 hours And a
rale o f 150 tons per hour. lixplam how you could madify the dita. without chjmgirçg lhe m o d e l «o
incxrp<rate this new tf age.
1 - 3 . "Hiis exercite deals with some i w u » o f "sensiti vity " in the steei m o d e h .
( a ) For lhe b m r p r o g n m of R g u i » l - 5 « aixl 1 5b, displiy T i m e anJ M a k c . r c . What cki these
values tcD you about the sohition? ( Y o u may wish t o r c v i e w lhe exploiutkin o f nurgiiul values
oixi reduced costs in Sertion 1 j6. >
<b) HxpLun why the rehe.il lime cxirotraints jxí.led in Figure 1 6 a resuM m a higher produrtkin o f
p L l e anJ a lower produrtkin of bonJs.
By tn ing some olher values of t h : reh-ot time. confirm that the profit incremex by $1800 per extra
hour for any number o f hours between 35 aixJ 37 "Ma. but that any i n c i c v e in lhe reheat time
bcyand 37 ty 4 hours ckiesn't gi\x" any furth-r p r o f i t
Drsw a plot of lhe profit versus lhe number of reheat hiurs available. for hours £ 35.
( d ) T o fínd lhe skipe of th- plot f r o m ( c ) — profit versus xvhrat time avaiUbke — at any particular
reh-at time value. you necd only look at th- N f g j r a l vahie of T i m e ( " r e h e a t " J. Using Ihrs
ofocrvalion as an aid. extenJ your pkit f r o m ( c ) d o w n to 25 hours of reheat time. V e r i f y thit lhe
skipe o f th- pkit remams at $6000 per hiur from 25 hiurs d o w n to lem thin 12 hours o f reh-at
time. lixplam w h i t hippens when lhe avaíLible reh-at time drops Io 11 hours.
(a> What are lhe dati values thit define this problem? l l o w would you dcclare th- *e<s axxl param
etrr values for this problem «n A M P L ? What are lhe decision variibles. and h i w woukl you dcclare
thrm in A M P L ?
<b) Amumii\g thit th- objeclive is to maximúe total profit. how would you d e c b r e an o t j e c t i w in
A M H . f<r this proUevn? H o w woukl JXIU declare lhe comtraints?
( c ) For purposes of experiment suppose that there ãic Ihrec iinJs of cars. kncrwn at th- factory as
T . C and /.. thit 120 hiurs aie available. aixJ thit lhe time per car. pr<ifit per car and dealer orders
fer each kinJ of car are as foliou*s:
Gr orne is
T 1 200 10
C 2 ÍOO 20
L * 700 15
SECT-GN 1 7 W F L NTEPFACES 23
l i o w much o f cach c u should hc praduccd. aixl w h i l is é i e mxximum prafiC? Y o u shaukl firaJ thit
yaur solution x p e c i f í » a fracticmal amoimt a f ane o f lhe e u s . As a praclic.il m s t e r , haw cauld yau
m o l e w c o f Oik salutkm?
( d ) l í yau maximize the total number af e u s praduccd imtcad af the ktlil profit, haw m n y more
e u s d » yau m a t e ? I l a w niuch l e « profit?
( c ) liach kinJ a í c u achk-vcs a ccvtain fuel efficiency. aixl the manufacturcr is required by h w k»
mxintun a certain " f f c d a v e r a g e " e f f i c i e n c y . The fleet average camputcd by m u l i p l y i i ç the
efficiency af cach k«nd af c u limes the number af that kiixl praduccd. sumnung ali af i i e resulting
p e d u e t t , anJ dividmg by t\c «Mal af ali cars praduccd. HXICIKI yaur A M P L model k» cantam a
mini muni fleet average efficiency canstraint. Rearrange the canstraint as n e c e » > y k» makc * lin •
c u — nc» variables di vided infci ather variables.
( 0 R n d the aptimal salutkin fer (hc case where cars T, C and /. achieve fuel efficicncies af 5(1 30
anJ 20 mik-s.^allan. and é i e flce* aserage e f f i c i e f i c y m i n t b e at least 35 milccfeallan. I:\plam haw
this charçges «hc produetian amounts and the k>Ul p r a f i t D n ü i n g wiéi t h : fraclkirul amounfc in
the salutkin k not sa cawy in Ihis case. What might yau d a ?
If yau had 10 me«e haurs af produetian time, yau cauld makc m o r e p r o f i t Does the additan af the
fk-et average efficiency canstraint makc t h : extra 10 haurs manr ar lew valuible?
<g) HxpLun haw yau cauld further lefine thrs model ki account for different pxiductian stages thit
have different numbers af kiurs availibk' per stage. much xs m the sleel model af Scrtian 1 A
1 - 5 . A group a f young entiepreneurs cairo a (tempcirarily) steady living by adquiri rç; madcquitcly
suptrvr<cd items frant clectronic* steres aixl re selling them. I:ach item hxs a street value, a
wcvghl aixl a volume: there an: Imüts <«i the numbers af available items, and an the total w e ç h t
aixl volume thatcan be moiugcd at ane time.
(a> Formula*: an A M H . model thit wiD help ki determine haw much af each item k» pick up, ki
m a u nu/c a n e d a y ' s profit.
<b) I i n d a sohitian for the case given by the falktwing table.
TV 50 Í5 s 20
adtt 15 5 i 50
cureis 4 2 20
(l>ph\ce 40 % 1 30
VC» 50 15 5 30
alawctfJer 120 20 4 15
1 - 6 . Profit miximi/ing mudeis o f oil rcíkikig vxrc o n e o f th? fina applicatkins o f linear program
mirç;. This exercise x á s you Io nwidcl a s m i p b f i f d \ersion o f é i e fiiul stage o f # i e l e f í n i q g pro
CCSS.
A refinery breaiscnide « 1 inlo « i m c collection o f mfcnnedute materiais. then bk-nds these nui-ri
ais t u c l tagrther infci finished produets. G i v c n the volume* of irtermcdiaftrs tfuU will b e a v a i l o b l e ,
w e w m I ki determine how t o blend t h : mfcnnedutes s o thit t h : resultirçg produets are rnost p r « f
itaUe. T h ? deciskin is n u d e man? complicataJ. h o w e w r . by t h : e x i i d e m o f upper hmits o n eer
tam afltributes of t h : produets. which mustbe nrspected in inj- feasfcV: solution.
T o formulo*? analgi-brajc linear progranuiung nwidcl f<* this problem, w e can start by definiqg sets
/ of intermediucs. J o f fiiul produets. and K of altributes. T h : ivlevant lechncikigical dita may bc
represei*ed h)'
H i e o b j e c i w is Io
ma»núe
S . / . V = for each i c / .
H i e anwiunt of a producl n u d e must equil the sum o f anwiunts o f the componmts blenJed inki ü:
lx»r each producl. the «citai at tributes contributed by ali âifcrmcdiates must reit exceed t h : fcilil
allowed:
SIC X RF CG B DZ 00 RS
21170 500 16140 4610 170 250 11600 25210
The ir*ermedia«es thit can be blenJed infci each p r o d u z , jmd the amo unto of the attri bules thit they
p<K*rcc. an: as folktw* (with blink enlries represenling zerot):
Limits l e i blank, surh as demMy for gasoline, an: irrek-vanl and may be se< lo some reblivefy
large numbcr.
Creafc a dati fik" for your A M P I model anJ determine t h : optimal bk*nd anJ produetion amo unto.
( d ) It looks a little strange thit t h : attnbule amounts for research ortane an: neg atire. What is the
Imutcomtraint forthw attnbule leodly saying?
Copyrisht O O T by Robcrf F o u r » , David M . G a y j m d B r i » W . K o n ç l a n
2
Diet and Other Input Models:
Minimizing Costs
27
32 D E T A N D O T H S ^ NPUT W O C & S W NMI W5 C O S T S CHífTÇR2
These dinners provide the f o l b v v m g percentages. per packagc. o f the minimum daily
requirementv for vitamins A . C , BI and B2:
A C BI B2
total cost =
3.19 XKSS + 259 XOÍX + 229 XFIS„ + 2.89 XHAM +
I £9 XMOI + 1.99 Xt\nL + 1.99 X5PO + 2.49 X1VK
This amouni needs t o be greater than or equal t o 700 percent. There is a similar formula
for each o f the other vitamins. and each o f these a b o needs t o be 2 700.
P u t t n g these ali together, have the f o l l o w i n g linear program:
SECT CN 2 1 ALNEAPRFOGRfiVFORTHE DET R F O e i f V 29
Minimize
3 . I 9 X^ar + 2 3 9 X<„K + 229 + 2.89 XHAM +
I £9 XMOI + 1.99 X i V / J . + 1.99 + 2.49 X1VK
Subject to
6 0 -Y ^mxr + & XATK + & JLÜ/ + 40 X J/AM +
15 Xmch + 70 X iW/J . + 23 X w ; + 6 0 X ^ 5 700
1 0 X ^ + 20 XATX + 15 X / J S W + 3SXHAM +
15 X * ™ + 15 XMFL + 23 X w ; + 15 X7VK 2 700
At the e n d w e have addcd the common-sense requircnvrnt that no fewxx than zero pock-
age&of a f o o d can be purchaícd.
As first did with the production L P o f Chapter I. can transcribe k> a file, say
d i e t O . m o d , an A M P L statement o f the explicit diet LP:
m i n i m i z e cossts
3.19* Xbecf 2 . 59* Xchk «• 2 . 2 9 * x £ i s h * 2.B9*Xham *
1.89*Xmch «• 1 . 9 9 * X m t l «• 1 . 9 9 * X . c p g «• 2 . 4 9 * X L u r ;
s u b j c c L Lo As
GO*Xbocf * 8*Xchk • 8*Xfish • 40*Xham *
IS*Xmch «• 7 0 * X m L l «• 25*X:=pg «• G 0 * X L u r >= 700:
s u b j c c L Lo Cs
20*Xbocf * 0*Xchk • 10*Xíish • 40*Xham *
35*Xmch «• 3 0 * X m L l «• 5D*X:=pg «• 2 0 * X L u r >= 700:
s u b j c c L Lo B i s
10*Xhocf * 20*Xchk • 15*X£ish • 35*Xham *
IS*Xmch * lS*XmLl • 25*X.cpg • l S * X L u r >= 700:
s u b j o c L Lo B2s
I S * X b o c í * 20*Xchk • 10*X£ish • 10*Xham *
IS*Xmch * lS*XmLl * 15*X.cpg • 1 0 * X L u r >= 700:
Again a f e w A M P L ooftimands then suffice ii> read the f i l e . send the L P to a sol ver. and
retrieve the results:
32 D E T A N D O T H S ^ NPUT W O C & S W NMI W5 C O S T S CHífTÇR2
T h e optimal solution ii found quickly. but it is hardly what w e might have hoped for.
T h e cost is mini mi/cd by a monotonous diet o f A é r A packages o f maçaroni and cheese!
Y o u can check thai this neaily providos 15% x 4 6 % = 7 0 0 % o f the requirement for vha-
m i n s A . B I and B2. and a lot more vila min C lhan necessary: the cost is only S I . 8 9 x
4 6 % = $88.20. ( T h e tiny negative values for meat loaf and spaghettican be regarded ai
zeros, like the tiny positive values w e saw in Scction 1.6.)
Y o u might guess thai a better solution woukl be gcneratcd by rcquiring the amount o f
each vitamin t o cqual 7 0 0 % exactly. Such a requirement can e a ú l y be imposcd by
changing each > = t o = in lhe A M P L constraints. if you g o ahead and s o l v e the changcd
L P , you will fínd thai the diet does indced b e c o m e m o r e varied: approximaiely 19.5 pack-
ages o f chicken. 16.3 o f maçar oni and cheese. and 4 . 3 o f meat loaf. But since cqualities
are more restrictive than incqualitiei. the cost g o e s up t o $89.99.
s o t NUTR;
S O t FOOD:
Next necd t o s p e c i f y the numbers requircd by the nnxlel. Certainly a positive cost
should be given for each food:
W e also s p e c i f y that f o r each food there are lowor and upper limits on the number o f
packages in the diet:
S E C T CN 2.2 A N M J F L W C C € L F O R THE D ET P B D E l f V 31
Notice thai need a dummy index j t o nin ovar FOOD in the declaration o f £ _ s » a x , in
arder t o say that the m a x i m u m f o r cach f o o d must bc greater than or cqual k> the corre-
sponding mini mum.
T o make this nnxlel somewhal more general than our examples so far, w e also s p e e i f y
similar lowxrr and upper limits on the amount o f e a c h nutrient in the diet:
param n j n i n ( N U T R } > = 0:
p a r a m n nvax ( i i n >J"JTR} > = n j n i n l i l :
Finally, for each combination o f a nutrient and a food. wxr need a number that represents
the amount o f the nutrient in one package o f the food. Y o u may reeall f r o m Chapter I
that such a 4 'product'' o f t w o sets is written by listing them both:
T o complete the n n x l e l w e need only s p e e i f y that cach such sum must lie betwxren the
appropriate bounds. Our constraint declaratk>n begins
subject Lo D i o L (i in JJUrR} :
M L NITTR:
FOOD:
A "double inequality" like this ti interpretcxl in theobvious way: lhe value of the sum in
the mkldlc must lie between n _ m i n t i ! and n_rnax [ i ] . The complete nnxlel is shown
in Figure 2-1.
in which case wvr would have haJ to write arnt [ j . i ) in the constraint.
Suppose thai nnxlel and daia are stored in the files d i e t . s t o d and diet.dat,
respectively. Then AMPL t% used as folio ws to read these files and to solve the resuhing
linear program:
ampl: a o l v o ;
Ml NOS S . S : o p L i m a l s o l u L i o n í o u n d .
6 i L e r a L i o n s , o b j o c L i v c BB. 2
S E C T CN 2 3 USNGTHE AVR.DETWCC€L 33
M t NlfTR : = A B l B2 C ;
sscL FOOD : = BKKF ÜLK FISJI 1JAM MC1I MTL SPG TUR :
param: cosi £_min íjnax
BKHF 3.19 0 100
Cl IX 2.59 0 100
FISH 2.29 0 100
HAM 2.B9 0 100
1.89 0 100
JffL 1.99 0 100
SP3 1.99 0 100
TUR 2.49 0 100 ;
param: n_min n nvax : =
A 700 10000
C 700 10000
Bl 700 10000
B2 700 10000 •
param amt <trj :
A C Bl B2 í
BBBF GO 20 10 IS
CiJX 8 0 20 20
P1S11 8 10 IS 10
HAM 40 40 3S 10
ML* 11 IS 35 IS 15
XV L 70 30 15 15
SPG 2S SO 2S 15
TUR GO 20 IS 10 ;
a m p l : d i a p l a y Buy/
Buy 1*1 : =
BBBP 0
CllX 0
K1S11 0
1JAM 0
MCi! 4G.GGG7
MTL -1.07823«-l G
SB3 -1. 32893«-l G
TUR 0
M t NlfTR ! = A B l B2 C NA CAL :
£ « t FOOD : = BKKF ÜLK F1S11 HAM MC1I MTL SPG TUR :
ampl: aolvo;
M1MDS S . S : i n f e a n i b l c problem.
9 iLeraLions
The message i n f e a s í b l e p r o b l e s i Krlls us that \v\r have constrained the diet ux»
tightly: there is no way thai ali of the restrictions can be satisfied.
AMPI. leis us examine a varkrty o f values pnxlucvrd by a sol ver as it attempfc l o find a
solution. In Chapter I, used margina) <or dual) values to investigavr the sensitivity of
an optimum solutk>n to changes in lhe constraints. Ilere there is no optimum. but the
solver does return the lavt solutk>n thai it found while attempting to salisfy the con-
straints. W e can look for the source of the infeaiibility by dispbying some values associ-
aied with this solution:
S E C T CN 2 3 USNGTHE AVR.DETWCC€L 35
For each nutri? nt. D i e t . b c d y t> lhe sum o f lhe terim arnt [ i . j 1 * Buy [ j J in lhe
constraintDietli]. The D i e t . l b and D i e t . u b vahies are the " l o w x * bounds" and
"uppcr bounds" on the sum in D i e t I i J — in this caie. just the values n _ m i n [ i ) and
n_rnax ( i 1. W e can see that the diet rcturncd by the sol ver does not supply enough vha-
min B2, whilc the amount ofsodium ( N A ) lua reached ifc upper bound.
A t this point, there are t w o obvious choices: we coukl rcquire less B2 or we could
allow more sodium. If try the latter. and relax the sodium limk to 50,000 n^g, a feasi-
ble sohition becomes possible:
ampi: aolvo;
M1NQS S . S : o p L i n v a l s o l u t i o n í o u n d .
S i t c r a L i o n r . . o b j o c L i v c 1 1 8 . 0 5 9 4 032
a m p l : diaplay Buy;
Buy 1*1 : =
BKKK S. 36061
C11K 2
Kl SM 2
MAM 10
MCil 10
MTL 10
SB3 9 . 3 0605
TUR 2
This is at least a stan toward a palatablc diet, although we have to spend SI 18.06, com-
parcd to $ 8 8 2 0 for the original, less restricted caie. Clearly it would be easy, now that
the mudei is sei up, to try many other possibilities. (Section 113 dcscribes ways to
quickly change the daia and re-solve.)
O n e still disappointing aspect o f the solution is the need to buy 5.36061 packages o f
beef. and 9.30605 o f spagheui. H o w can w e find the best possible solutk>n in ternti o f
whole packages? You might thini that w e could simply round the optimal values to
whole numbers — or integers. as they're often called in the context o f optimi/atk>n —
but h is not so e » y to d o s o in a feasi ble way. Using AMPL to m o d i f y the reponod solu-
tion, we can observe that rounding up to 6 packages o f beef and 10 o f spaghetti, for
example, will violate the sodium limk:
32 D E T A N D O T H S ^ NPUT W O C & S W NMI W5 C O S T S CHífTÇR2
This will only help, howxrver, if you use a sol ver that can dcal with problems whose vari-
ables must be integers. For this, w e turn k> CPLHX, a sol ver thai can handle these so-
called integer program*. If \V>Í add i n t e ç j e r to the declaratk>n o f variable Buy AI
above, save the resulting model in the file d i e t i .r>cd, and add the higher sodium limit
t o d i e c 2 a . d a t . then wvr canre-solve ai follows:
ampl: roaotj
a m p l : xzodol dia ti .XODÓ;
a m p l : diaplay Buy;
Buy l *1 :
BKKF 9
C1IK 2
F1S11 2
UAM e
MCll 10
MTL 10
SB3 7
TUR 2
SECTON2 4 G E N E F V C Z A T O t t S T O e L E N D N S E O C N O V C S AND S C H B X J L N Q 37
Since integralily isan addcd oonstraint. it is no surprise thai the best integer solution costs
about $1.24 more than the best "continuou*" one. But the diffeience between the diets
is uncxpectcd: the amounts o f 3 fcxxls change. each by t w o or more packages. In general
integralhy and other " d i s c r e t e " restrictions make sohitions for a nnxlel much harder to
find. W e discuss this at length in Chapter 20.
s e t INPUT: 4 inputs
s e t OUTPUT; 4 OuLput-S
s u b j c c t t o O u t p u t s ( i i n OITTFJT}:
ou L m i n l i | < = sum ( j i n I N P U T } i o l i . j l * Xljl < = out_nvaxl i ] ;
be used in a variety o f other scheduling contcxts. where the hours, days or months are
replaced by other perkxLs o f t i m e .
Ahhough linear programming can be very uselul in applications like these. w e need to
keep in mind the assumptions that underlie the LI* nnxlel. W e have already mcntk>ncd
the " c o n t i n u i t y " issumption whereby X [ j ] is allowxxl to take on any value betwvxrn
i n _ m i n [ j 1 and i n _ r n a x [ j ] . Thii may be a lot more reasonable for blending than f o r
scheduling.
\V>Í are assuming "linearity o f c o s t s " . that is. that the c o a o f an input is proponional to
the amount o f the input used. and that the total cost is the sum o f the inputs' individual
costs.
In writing the constraints a*
wxr are also avsuming that the yield o f an output i from a panicular input is proponional
to the amount o f the input used. and that the total yiekl o f an output i ti the sum o f the
yields from the individual inputs. This • linearity o f y i e l d " assumption poses no problem
when the inputs are schedules. and the outputs are hours worked. But in the blending
cxampke. linearity & a physical avsumptk>n about the nature o f the raw materiais and the
qualities, which may or may not hold. In early applications k> refinerie». f o r example. it
was recogni/cd that the addition o f lead as an input had a nonlinear e f f e c t on the quality
known a* octane rating in the rcsulting blend.
A M P L makes it easy to express discrete or nonlinear models. but any departure from
continuity or linearity is likely *> make an optimal solution much harder toobtain. At the
SECTON2 4 GENER4. Z A T O K S T O E l ^ N D W S E O C N O V C S AND S C H B X J L N 3 39
least, it takes a more p o w x j f u l sol ver t o opcimize the resulting mathematical programs.
Chaptcrs 17 thxough 20 dfecuss these issues in more detail.
Bibliography
Sasd S. Ifilal jmd Warren lirikson. "M-Mchirçg Supplirs lo Sase tive*: linear Progromniins lhe
Produdkin of Ifearl Valves." Interfaces 11. 6 (1981 > pp. «S8-56. A l e « appcti/.ins eqüivaler* o f
LHRDÍL-1 problem. involvinglhe choice o f p i g hearlsuppliers.
Excrcises
2*1. Suppose Ih? food< i ü e d b e b w have embries, protein. calci um. vüamin A . and cosi* per
p<iurxJ as shuwn. In whil ornou nls shciuld lhese food be purcha.\ed Io m e d at least lhe diily
roquiremenfe hsled while nútúminng lhe letal cosi? <"Thi< problem comes from George B.
I>int/js's chssic book. tintar Progmmmin% <md Exlensions. juge 118. W e will toke his word <*i
nuCntional volues. aixi for nostA^ic remanx hi\v lefl the prices is Éicy w e f e when lhe book « K
pubbshed in 1963.)
2 - 2 . (a) You have been advKcd by your doei cr lo g d more exercite.. specifically, lo burn off al
IOLSI 2CK10 etfra cakiries per week by some combination o f w i & i n g , JQGGIR^G. xwimming. exercite-
nuchinu-. coILriuralivc inckxr recreai kin, and pushmg yourself away from lhe table al meakimcs.
You have a hnutcd fcik-rancc fer each activily in hourtfaeck; each expends a ceitiin number o f
cakirics per hour. as A a w n bclow:
Ilow should you divide your exercxtmg anuíig lhese octi vitocs lei mini mi/e lhe amount of lime you
spend?
II. I I 111
S
* *
li
SÍ> 3
ST*
"S
I l i
*
«
£ "O
•8 "5 * e i J ^ - S
ii ii i nii
i|
i ã
i|
» 8
* jri
f s c
; s a fca P i ? !
r i E * v £ . 8 $ §
S i ã1 1 a ; 6 5 i g.
1 i i « 8 2 8 2
§ s| -aI ? =
ü ^ V s * X — -SC
! Iig 5* IS 1111
l g j J l l
* • c & Ê i § s *§
1 111 I S
a i Í 1 zi "5
S * . . . 'Z! í^ - £á í - 6
s 1
- S R J á 3 i ! .
c 3 s
2 2 3 - 2 "O - í
1 i n II..
0 ü . «s tS g £
iíiUi 9 • * jí
Q * • g 1 *B * < * 5 í 5 *
5 I ^ I 5 ? f 2 4 S I 8 s J
S»..
3
ffl H H M J1 «
o h h g g h o
0)
* ,
i!
4 H M
% «X CJ
a <Ü
3 m r» g g g m
0) ri ri ri
V . ,
H u s
Hfi 'À * assa:
tí rt O O 5« f Hl O b»
SECTCN2 4 GENER4. Z A T O K S T O E L E N D W S EOCNOV CS AND S O C U L N 3 41
Based o n this information. if you want tc» s a w money by eating m o r e thin 10 packages o f some
faad, which one k bkely lei be your bestchoice?
2-5. A chiin of fa*t ícxid restiuranls o p e r a * » 7 days a weck, and nx|um» the following nüninium
numftxx o f kitchen employees firam Monday éirough Sundiy: 45. 45, 50. 65. 35. 35. liach
employee is scheduk-d lei w a k o n e w c e k m d d i v (Saturdiy o r .Sundiy) and four < < h i d i y s in a
w w k . T h : maiugcment wanfe t o know the nünimuni fctlil number of employees nceded lei satisfy
th- requi remei* s cm e\ery day.
(a).Set upand solve thrs problem asa li nrar pragram.
<b) In bght o f the dncussion in Scclion 2.4, expiam h o w this p n b b n can be viewed as a spcciil
case of the blenJing model in Figure 2-4.
2-6. H i e output of a papex miII consists of stindurd rolls 110 inrhes ( 1 1 0 " ) wide, which are cut
intosmaller r o l i s t o meetorders. TTIÍS weckthens areerders f<R rolk of the folkiwing widths:
Widfc Otfkrs
2tr 4S
45"
3KT 24
55" 10
75- a
H i e o w n e r o f the nu 11 wanfe to know what cunmgpanems t o apply s o a s to ftll the ordexs ming the
snullest number of 110" r o l k .
( a ) A cuHmg panem consistsof a ceitiin number of rolls of each width. such as t w o o f 45" and one
o f 20", <r eme of 50" and eme of 55" (and 5 " o f waste). SupfKKc, to stirt with. thit w c c o m i d e r
only the folkiwirç; six jufterns:
W«Mk 1 2 i 4 5 6
xr * 1 0 2 1 *
45" 0 2 0 0 0 1
5CT* 1 0 1 0 0 0
55" 0 0 1 1 0 0
75" 0 0 0 0 1 0
l l o w manv rolls shoukl be cut accxrding tci each panem. to minimi/e th- number of 110" rolk
used? Formula*; and solve thw problem as a linear program.assuming thit th- number o f smaller
rolk produred n e e d o n l v be grealer than <r equil to th- number erdered.
<b) Re s o h e th- problem, w i t h th- restriction thit the number o f rolls produced m each si/e mu st
be between 10K under anJ o v e r th- number ordered.
( c ) Find another panem that when adJed to Él«<e abo\e, i m p r o w s the optimal so lutem.
( d ) A l i of the solutions abou: u<e fraclkinil numbers o f rolls. Can you finJ sohitions that a b o *it
isfy the comtrainls. but thit cut a whole number of rolk in each panem? l l o w mucfi does your
whole number solutkin caule the o b j e c t i w íimcti<m value tc» go up in each case? (See CTupter 20
f<r a dxsciKsion of how tci fmd optimal whole number. o r integer, sohitions.)
SJC 9JS7
K Ü2S7
RF 1169
CG ioaa
B 6lW
Other dali ase as in H m c i « 1 -6. Corotrucl a blcnding model and dita file ( o reprenenl thw prab
lan. Run them through A M P L fci determine the aptimal campotitkinof the blend.
2-8. Recall that Jigure 2-4 generab/es the diet model as a nünmium « w l input selectian model.
with corotraints <«i the outpufc.
( a ) In the sinu: w i y . g c n r r . i l n r the produdkinmodel o f f i g u r e 1 6 i as a m a x i m u m re\x-nue outpi*
sdectian model. with canstrainfe an the mputs.
<b) l h e cancept af an "input o u l p u t " model was anc af the fírst applicatkim a f linear program
ming in economic analysis. Surh a model can bc descrihed «n I s u M af a se< .1 af aclivities and a
set M o f materuls. T h : decnkin variables are the levds X ; £ 0 at which the aclivities are rim: thev
have l o w e r limita « and upper limite .
liurh activitv j his àther a levcnuc per ura! c # > ( l <r a cost per unit represerted by cg<Q. Thus
tat.il prafit fram ali aclivities is £ which K IO be maximi/cd.
/# A
liurh unil af aclivity j pxiduces an amounl a f material i given by a» £ 0. consumes an aniaunl
a f materiil i represenled by fl^<Cl Thus if £ ^ * ^ ía,*l produetian a f materiil
i by ali aclivities; if < ( l it isthe fctlil c o m u m p t a n af material i by ali a d i vi ti es.
Ixircach material i, é i c f e is eilher an upper Imut an the fctlil produdkin gi\cn by h* > ( l <* a lower
Imut <*i the total coimimptian given by b* < 0 . S i m i l a j K . there is either a lower Kmit on the fcitil
pxiductian given by b~>Cl <r an upper Imut <«i the total cansumptkingivcn by />: < 0 .
Write aut a fcrmulitkin af this model «n A M M . .
( c ) HxpLun haw the mmmium cxwt input sebelion model anJ maximum xevenue output selectian
model can be viewed asspecial cases o f the inpul output model.
Copyright C 2CKD byRobert Fourcr, Dfcvid M . G « y aikJ B r i » W.Kcrnighan
3
Transportation and
Assignment Models
T h e linear program* inChapters I and 2 are ali exampies o f c l a s s i c a l " a c t i v i t y " nnxl-
els. In such n n x l e k the variables and constraints deal with distinctly different kinds o f
activities — tons o f sieel prcxluced versus hours o f mill time used, or packages o f f o o d
bought versus percentages o f nutrients supplied. T o use these n n x l e k you must supply
coelTicients like k>ns per hour or percentages per package thai c o n v e n a unit o f activity in
the variables t o the corresponding a m o u n t o f aciivhy in the constraints.
T h & chapier addresses a signifkantly different but equally c o m m o n kind o f nnxlel. in
which üomcthing is shipped or assigned. but not converted. T h e resulting constraints.
which rellect both limitatk>ns on availability and requirements for delivery, have an espe-
cially simple form.
W e begin by describing the so-callcd transportaiion problem, in which a singkr gtxxl
is t o be shipped from several orjgins t o several destinations at minimum overall c o s i
This problem g i v e s rise *> the simplest kind o f linear program for minimum-cost flows.
W e then generalize t o a transponation nnxlel. an cssential step if wxr are t o manage ali the
data, variables and constrainfc elYectivety.
A s whh the diet n n x l e l the power o f lhe transponaiion nxxlel lies in its adaptability.
W e continue by considering s o m e other inierpretaiions o f the " f l o w " from or^gins t o
destinations. and work through one particular inierpretaiion in which the variables repre-
sem aisignments rather than shipments.
T h e transponaiion nnxlel is only the most elementary kind o f m i n i m u m - c o a How
nnxlel. M o r e general n n x l e b are often best expressed as networks. in which mxles —
s o m e o f w h i c h may be origins or destinations — a r e connected by ares thai carry How s o f
s o m e kind. A M P I . olYers convenient feaiures f o r describing nei\u>rk flow mixlels. includ-
ing n e d e and a r e decbrations thai specify network stmciure directly. Network nnxlels
and therelevant A M P I . feaiures arethe topic o f C h a p t e r 15.
43
44 T R A t t S F O R T A T O N tf® A S S G W B Í T WCC€LS CHífTÇR3
T h e total o f 6,900 tons must be shipped in various aniounts t o meet orders at seven loca-
tions o f j u t o m o b f l e factories:
W e n o w have an optimization problem: What is the kravt expensive plan f o r shipping the
coils f r o m m i l k t o plants?
T o a n s w e r thequestk>n. w e n e c d t o c o m p i l e a table o f shipping costs per ton:
FRA 39 27 24
DET 11 9 14
LAN II 12 17
W N 11 9 13
STL 16 26 28
FRF. 82 95 99
LAF 8 17 20
Minimize
3 9 ClARY:RRA + 27 CLEV:PRA + 24 PTTT.fkA +
14 GARY:DET + 9 CLEVDET + 14 POTíDET +
I I C A R Y : L A N + 12 C L E V l A N + 17 PI ! 1:1 A N +
14 G A R Y : W I N + 9 c u k \ : w w + 13 F I T T W I N +
There are 21 dccision variables in ali. Even a small transpor tatk>n problem like this one
h^v a k>t o f variables, beca use there i s o n e for each combinalion o f mill and factory.
S E C T GN 3.2 A N A W R . W O C S . F C R THE T R A t t S F O R T A T O N F T O B L E W 45
B y supplying cach factory f r o m the mill that can ship most cheaply to h, w e oould
achieve the lowest conceivable shipping cost. But WÊ w o u l d then be shipping 9 0 0 tons
from PMT, 1600 from CLFCV, and ali the rest from GARY — amounts quite inconsistent
with the pnxluction leveis prevk>usly decided upon. W e need t o a d d a constraint that the
sum o f the shipments from G A R Y to the seven factories isequal k> the production levei o f
1100:
G A R Y * R A + G A R Y D E T + GARY:LAN + GARY:W1N +
CLFCV:S11. + C L E V : R T E + C L E V Í L A F = 2600
HTTÍPRA + PITTÍCFET + H T T L A N + W T T : W K +
There also have to be constraints like these ai the factories, to ensure that the amounts
shipped equal the amounts ordered. A t FRA, the sum o f the shipments received from the
three mills must equal the 900 tons ordered:
GAR V * R A + O I V : P R A + H T T : H U = 900
G A R Y D E T + CLEVDTT + M T T D £ T = 1200
W e have len constraints in ali, one for each mill and one f o r cach factory. If w e add the
requirement that ali variables be nonncgative, w e have a c o m p l e t e linear program for the
transpor tation problem.
W e w o n ' t even try showing what it would be like to type ali o f these constraint* into
an A M P L nnxlel f i l e . Clearly \V>Í want to set up a general nnxlel *> deal with this prob-
lem.
s e t O K l Cl:
s o t OBST:
There is a supply o f something ai each orjgin (tons o f stcel coils produced. in our case),
and a demand f o r the same thing ai each destinatk>n (tons o f c o i l s orderod). AMPl.
defines nonnegaiive quantities like these w h h p a r a m statements indexed o v e r a set: in
this case we add one extra refinenient, a c h e c k statement t o lest the daia for validity:
T h e c h e c k staiemeni says thai the sum o f the supplics has t o equal the sum o f the
demands. T h e way thai our model is t o be set up. there can't possibly be any sohitions
unless this condhion is satiified. By putting it in a c h e c k statement we tell A M P l . t o
test this condhion afterrcading the data. and t o issue an error message if it is vk>lated.
For each combination o f an origin and a destination. there is a transpor tal i o n c o s t and
a variabkr representing the amount transponed. A g a i n . the ideai from previous chapters
are casily adapicd t o p r o d u c e the appropriaie A M P l . staiements:
p a r a m c o s t ( O K l G , DKST} >= 0 :
v a r T r a n s ( 0 R 1 G . DKST} >= 0:
costli.jl * Trancli, jl
minimize Total_Cost:
sum ( i i n O R l G . j in DKST} c o s t l i . jl * Transli. jl :
orai
T o complete the S u p p l y constraint for origin i , \v>í nced t o say thai the sum o f ali ship-
ments out o f i is equal t o the supply available. Since the amount shipped out o f i k> a
partkrular destination j ti T r a n s [ i , j ] , the amount shipped k> ali destinations must be
SEC7CN32 A N A W R . W O C S . F C R THE 7 R A N S F O R T A T O N F T O B L E W 47
s u b j e c t t o Supply ( i i n ORlG}:
sum ( j i n DEST} T r a n s l i . j l = supplylil:
( N o t e that the names s u p p l y and S u p p l y are unrelated: AMPL distinguishes upper and
lowor c a i e . ) T h e other oollection o f constrainfc is much the same, except that the roles o f
i in O R I G , and j in DEST, are exchanged. and the sum equals d e m a n d [ j ] .
W e can now present the complete transponation mixlel. Figure 3 - I a . A s you might
have noticed. w e have been consistem in using the index i to run over the set O R I G , and
the index j ii> run over DEST. This is not an AMPL requirement but such a convention
makes it easier *> read a nnxlel. You may na me your o w n Índices whatever you like, but
keep in mind that the scope o f an index — the part o f the nnxlel where it has the same
meaning — is *> the end o f the expression that defines it. Thus in the D e r « n d c o n s t r a i n t
s u b j e c t t o Dcmarxi ( j i n D E S T } :
sum ( i i n ORIG} T r a n s l i . j l = d e m a n d [ j l ;
the scope o f j runs to the semicolon at the end o f the decbration, while the scope o f i
extends only through the summand T r a n s t i . j i • Since i ' s scope is inside j 's scope,
these t w o Índices must have diíTeient names. A l s o an index may not have the same na me
av a set or other nnxlel oomponent. Index scopes are discusscd more fully, with further
examples, in Seetion 5.5.
Data values for the transponation nnxlel are shown in Figure 3 - l b . T o define DEST
and d e m a n d , w e have used an input formai that permits a set and one or more parameters
indexed over it to be specified together. The set na me ti surrounded by cok>ns. ( W e also
show some commenti, which can appcar among data statements just ai in a nnxlel.)
48 T R A t t S F O R T A T O N tf® A S S G W B Í T WCC€LS CHífTÇR3
param c o s t :
FRA DKT LAN WIN STL FRK LAF
GARY 39 14 11 14 1G 82 8
CLKV 27 9 12 9 2G 9S 17
P1TT 24 14 17 13 28 99 20
a m p l : xsodol tranap.niodj
a m p l : data tranap .datj
ampl: aolvo;
CPLKX 8 . 0 . 0 : o p L i m a i s o l u t i o n ; o b j o c L i v e 19G2 00
12 d u a l s i m p l c x i L c r a L i o n c ( 0 i n p h a s e 1J
a m p l : diaplay Trana;
Tranr. l * . * l <Lr)
: CLKV GARY PITT
DKT 1200 0 0
FRA 0 0 900
FRK 0 1100 0
LAF 400 300 3 00
LAN G00 0 0
SVL 0 0 17 00
WIN 400 0 0
By displaying lhe variabkr T r a n s , \V>Í see lhat most destinations are supplicd from a sin-
g l e mil!, but OJEV, GARY and H T T a l l ship to LAF.
l i is instmctive to compare this solution k> one given by anothersolver, SNOPT:
a m p l : diaplay Trana;
Trans l * 1 <LrJ
: CUÍV OARY PITT
DKT 1200 0 0
FRA 0 0 900
FRE 0 1100 0
LAF 400 0 600
LAN 600 0 0
SVL 0 3 00 14 00
WIN 400 0 0
The minimum cosi is still 196200. but ii & achieved in a diflorem way. Alternative opti-
mal sohitions such as these are often exhibiwrd by transponation problems, particubrly
when the coefllcients in the objective function are round numbcrs.
llnfonunatcly. there is no easy way to charactcri/e ali the optimal solutions. You
may be able to gel a better choice o f optimal solution by w\>rking with several objectives.
howxrver. as w e will illustrate in Section 8 3 .
set DlíST : = C l 18 C l 3 8 C140 C24G C250 C2S1 D237 D239 D241 M233 M239:
param s u p p l y d c f a u l t 1 ;
param dcmand d c í a u l t 1 ;
param c o s i :
C l 18 C l 3 8 C l 4 0 C24G C250 C2S1 D237 D239 D241 M233 M239 : =
Coullard G 9 8 7 11 10 4 S 3 2
Das k i n 11 8 7 G 9 10 1 S 4 2
Uazcn 9 10 11 1 S G 2 7 8 3
Uqpp 11 9 8 10 G S 1 7 4 2
Iravani 3 2 8 9 10 11 1 S 4 G
LinoLsky 11 9 10 S 3 4 G 7 8 1
MchroLra G 11 10 9 8 7 1 2 S 4
N e l snn 11 5 4 G 7 8 1 9 10 2
Smi l c w i t z 11 9 10 8 G S 7 3 4 1
Tamhane 5 G 9 8 4 3 7 10 11 2
Whi t c 11 9 8 4 G S 3 10 7 2
thai person i gives to ofTice j . This convention lets each objective functk>n torm
cost[i,jl * T r a n s t i . j ] represem the preference of person i for office j , if person
i is assigncd ii> office j ( T r a n s I i . j ) equals I ) . or zero if person i is not assigncd to
office j ( T r a n s ( i . j J equals 0). Since the objective is the sum of ali these ternti, it
must equal the sum o f ali the non/ero terms. which is the sum of everyone's rankings for
the otTices *> which they \v\rre assigned. By minimizing this sum, w e can hope to find an
assignmcnt that will pleasea lot of peopfc.
T o use the transponation nnxlel for this purpose. w e need only supply the appropriakr
data. Figure 3-2 is one example. with 11 pcople to be assigned to 11 offices. The
d e f a u l t option been used to set ali the s u p p l y and d e s w m d values to I whhout
typingall the l's. If store this data set i n a s s i g n . d a t , w e can use it with the trans-
ponation mixlcl that w e already have:
a m p l : xsodol tranap.xsodj
a m p l : data aaaign .dat;
ampl: aolvo;
CPLlüí 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j c c t i v c 28
24 d u a l s i m p l c x i t c r a t i o n c ( 0 i n phanc 1J
By setting the option o m i t _ z e r o _ r o v s to I, can print just the non/ero terms in the
objective. <Options for displaying resulfc are presenk.d in Chapter 12.) This listing tells
us each person's assigned r<x>m and his or her preference for it:
SECT-ON 3.3 O T H E R N T E F R R E T A T O M S CF THE T R Í W S F C R T A T O N WCC€L 51
a m p l : option a c i t zoro r o v s 1;
ampl: d i a p l a y ( i in ORIG, i i n coat[i,j) • Trano[i, j);
OOitli,j|"Transli.jl :=
Coullard C11B G
Oaskin D2 41 4
llazcn C2 4G 1
Itopp D2 37 1
iravani C l 38 2
Linotsky C2S0 3
MchroLra D2 39 2
?Jelson C l 40 4
a n i l o w i t z M2 33 1
Tamhano C2S1 3
WhiLc M2 39 1
The solution is reau>nably successful. ahhough it does ass^gn t w o fourth choices and one
sixth choice.
It is not hard *> see thai when ali the s u p p l y [ i ] and d e s t a n d E j 3 values are I. any
T r a n a I i . j ] satisfying ali the constraints must be betwven 0 and I. But how did we
know thai every T r a n s t i . j 1 would cqual either 0 or I in the optimal solution. raiher
than. say. XA ? W e ware able to rely on a special property o f transponaiion modek. which
guarantces thai as long as ali supply and demand values are integers. and ali low*r and
upper bounds on the variables are integers. there will be an optimal solution that is
entirely integral. Moreover, we used a solver that ahvays findsone of these integral solu-
tions. But don't let thi* favorable rcsult mislead you intoassuming that integrality can be
avsurcd in ali other ciicumstances: even in examples thai seem to be much like the trans-
poriation model. finding integral solutions can require a special sol ver. and a lot more
work. Chapter 20 d^cusses issues of integrality ai length.
A problem of assigning 100 people to 100 rexura has ten thousand variables: a*sign-
ing 1000 people to 1000 rooms yields a mfllion variables. In applicatk>ns on thts scale,
however, most o f the assignments can be ruled out in advance. so that the number o f
actual decision variables is not too large. After kx>king ai an initial solution. you may
want to mie out some more ass|gnmentv — in our example. perhaps no ass|gnment to
lowor than fifth choice should be allowvrd — or you may want k> force some assignments
to be made a cenain way, in order to see how the rest could be done optimally. These sit-
uai ions require nxxlels thai can deal with subsets of pairs ( o f people and oíTices, or ori-
gins and destinalions) in a direct way. AMPL*s features for describing pairs and other
" o o m p o u n d " objects are the subject of Chapvrr 6.
52 TRAttSFORTATON tf® A S S G W B Í T WCC€LS CHífTÇR3
Excrcises
3 - 1 . TTirt trampoitilktn model. which deals with fiixJing a least cosi shipping schedule. comcs
fram I)ant/jç's tintar Pmjframming arxi Exitnsinns. A comjunv h » piints in Scaltle aixl San
Diego. with capacitíes 350 aixJ 6(K) cases per week respectiwly. It his cutkimers m New- Vcrk,
Chicago, aixl Topei.a. which arder 325.300. and 275 cases per w c e L T h : distorces involved are:
l h e shipping cosi it $90 per case per tfciutaixl miles. IcmiuLUe this model in A M P L and sohe it
to determine the minimumeoat oixl the amou nisto be shpped.
3 - 2 . A small manufaclurirçg operaliem praduces six kiixls o f juits. usirçg three nuchines. I"<r lhe
cx«mrçs month. a ceitain number of each part it needed. and a evitain number o f pirts can be
occxmimodilcd on each nuchine: ki complicale nulters. il does not cosi lhe same amount k» make
the same paxton different nuchines. Specifuraily. the cxrtts aixl lelaled v alues are as folkrws:
MttfaÉK 1 2 * 4 5 6 CafucK)
1 i * 2 5 2 1 ao
2 4 1 1 2 2 1 30
* 2 2 5 1 1 2 160
Rei^jcd 10 40 60 20 20 30
(a) Uting the model in H g u i e 3-la, cieale a file o f dila siaiements for Ihrt problem; ttesrt lhe
nuchines as lhe <rigint. xixi lhe partt as the deslinations. Ilow nuny of each pirt shoukl be pro
duced <m each macia ne, so as to mini mi/e kitil ccttC?
<b) If the copicity o f nuchiiv 2 it incieased ki 50. lhe nunufacturer may be able Io reduce the ktlil
cxrtl of produ^km somewhil. W h i l snull chance k» lhe model it necessiry k> analy/e Ihrt situo
lk»n? Ilow much it lhe total cxrtlreduced. and «n whil lespcctt does lhe prodiKtkin plan chorçge?
( c ) Now suppate lhal lhe capacities are gi\en in hours. ralher lhan in numbers of partt. aixl lhal it
lakes a somewhil diffeient number of hiurs to make the same part <*i different nuchines:
ftin
1 2 * 4 5 6
1 1J U 12 13 12 1.1 50
2 14 1.1 1.1 1.2 1.2 1.1 SO
* 12 12 13 1.1 1.1 12 175
Modify lhe supply cxintlraint so lhal il hnús total lime of produetion al each " o r i g i n " ralher thin
the total quantity of produetion. How it lhe new optimal sohilion different? C)n which nuchines it
ali avai 1 able time used?
(d) S o h e lhe precedmg problem acaxn. but witfi lhe objectí\'e funetian chinged ki mm«mi/e ktlil
nuchine hours ralher thin kitil cosi.
3 - 3 . TTirt exercite deals with general boi iont of lhe lransp<rtotion model oixl doti of Figure 3 1.
(a) Add I w o parameters. s u p p l y _ p c L and den\and_ p e t , ki represent lhe nuxmium fractian o f
a milTs supply lhal may be senl lo any one fadory. aixJ the nuximum fraction of a fartory's
S E C T - O N 3.3 O T H E R N T E F R R E T A T O M S CF T H E T R Í W S F C R T A T O N W C C € L 53
daiLind tha< may be titxsf ied by any one mill. IncorporJe these paramrters ínto t h : model a í I"ig
UK 3-Ia.
S o l v e for the case in which nct mcre thin 5CKr o f A mill's supplv may b e « f i l to any o n e factory,
axxl no m a e than o f a fartory'% dcmand may be s i t i s f x d by any o n e m i l l H o w does this
c h i n g e the m i f i m u m c o s t and t h : optimal amounts shippcd?
<b) Suppose (ha4 the rollmg mills d o not product: theirown siibs. but instcad obtiin slabs f r o m two
oéicr planta wheie th? following numbers o f tons are to be nudc available:
KXDWK 2700
KMO/SK <200
GARY CL EV PXTP
KUfMK 12 B 17
Wèd/SK 10 S 13
TornuilJc this siluitkin as an A M P L model. Y o u will need two indcxcd collcctions o f varnbles,
o n e for the shipments from plants lei mills, aixl o n e f e r t h : shipmcnls from mills t o factories. Ship
meiKs f r o m each mill will ha\e to eqtnl supplv. aixl shipments to each fartory w i l l h a w to e q u l
dcmand as b e f o i e : a l s o , shipments oul o f each mill w i l l have to equal shipments «n.
S o l v e the lesultirçg linear program. What are the shípment amounts in the mini muni cost solution?
(c> In addition to the d i f l e r e n a » in shipping costs, éicre may b e d i f f e r e n t costs of productxin at the
plints aixl mills. lixplam how prodiKtkincosts coukl be inc<rp<ratcd into the model.
( d ) When slibs an: rolled. some fraction of the sta-1 is lact as scrap. Assuming thit this fraction
may be different at each mi 11. revise t h : model to tàke scrap lats mki account.
( e ) In nmlily, scrap is not really lost, but is sokJ kw rvcycling. Make a further change to the model
to account fcrthe v a l u e o f t h e scrap produced ateach mi D.
<b) A n assignmcnt that gi\es e v e n one person a very low ranked o f f i c e may be unacceptable. even
i f the «citai of the rankings is optimi/cd. In furtiruLir. our solutkin gives one indiváduil her sixth
choice; to mie th rs out. chinge ali piefeiences of six <r larger in t h : cost d a t i to 99, so that they
will beco m e v c i y uruttractivc. <You'll leam mcre oansenient fcatines for d i m g the same thmg in
i J e r chapters, but this cru de approach w i l l work for n o w . ) S o l v e the assignmcnt problem agam.
aixl \erify thit t h : result is an equaOy g o o d assignmcnt in which no one gets worxe thin fifth
dnice.
N o w apply the same apprcuch to try to g i v e e\eryone no werse than fourth choice. What d o you
find?
( c ) Suppose now thit o f f i c e s C l 18, C 2 5 0 aixl C251 hecome unavaibbk-, and you hase to put t w o
pcopie each into C l 38. C 1 4 0 and C316. Add 2Q to each ranking for these é u e e o f f i c e s to n.-fk*rt
the fact that i m t n c woukl pxefer a privale ofHce to a shared ene. ^"hat other modifications to the
model aixl dati woukl be n e c e s « r y to hindle this situitxin? What optimal assignmcnt d o you ge<?
54 T R A t t S F O R T A T O N / N D A S S G W B V T WCC€LS OWTCR 3
4
Building Larger Models
T h e linear programs thai w e have presented so far have been quite small so their data
and solutions cx>uld fit ontoa page. Mo&t o f the L l \ fotmd in pmctical applicatk>ns. h o w -
ever, havehundxeds or thousands o f variables and cx>nstrainfc. and some are even larger.
H o w do linear programs get to be so large? They might be like the ones wvr have
shown, but with larger indexing sets and n*>re data. A steel mill oould be considercxl to
make hundreds o f diíTerent products. for example. if every variation o f width, thickness.
and finish is treawrd separaiely. Or a large organi/alion oould have thousands o f peopkr
involved in one assignment problem. Nevertheless. these kinds o f applicatk>ns are noi ai
common as one might expect. A s a nxxlel is refined k> greaier levek o f detail, its data
values beeome harder *> maintain and its solutions harder to understand: past a ceriain
point. extra detail o f f e r s no benefit. Thus to plan produetion for a few lines, considera blc
detail may be justifiable: but to pbn for an entire company, it may be better to have a
small aggregated. plant-level nnxlel that be run many times whh diíTerent scenarios.
A more common source o f large linear programs is the linking k>gether o f smaller
ones. lt is noi unusual for an applicaiion to g i v e rise to many simple L W o f the kinds wxr
have discussed before: hereare three possibilhies:
• Many products are ii> be shipped. and there i* a transpor tatk>n problem (as in Chap-
ter 3 ) for each product.
• Manufacturing is to be planned over many weeks, and there is a produetion prob-
lem < in Chapter I ) for each week.
• wSeveral produets are maJe at several mills, and shipped toseveral factories: there is
a produetion problem for each m i l l and a transportaiion problem for each product.
\Vhen variables or constraints are aJdcxl to lie these L P s together, the result can be one
very large LP. N o individual pan need be panicularly deiailed: the size is more due to
the large number o f combinationsof origins, destinations. produetsand weeks.
T h i i chapvrr shows how A M P L mudeis might be formubtcxl for the three situaiions
outlined above. The resulting m o d e k are necessarily more complicated than our previous
ones, and require the use o f a few more feaiures from the AMPL language. Since they
build on the terminology and logic o f smaller m o d e k that have already been introduccxl.
howevor, these larger models are still manageable.
56
56 BULDP*3LA«3ERWCC€LS CHÉFTCR4
Then w e have a new collection of (origins) x <destinatk>ns) constraints, one for each ori-
gin i and destinaiion j . which say that the sum of shipments from i to j o f ali products
p may notexceed l i m i t ( i , j):
Subject to these constraints (also shown in Figure l - l ) , wxr can no longer set the amount
of one pnxluct shipped from i to j whhout considering the amounts of other pnxlucts
also shipped from i to j . since it t> the sum of ali pnxlucts thai t% limited. Thus wxr have
nochoice but tosolve the one large linear program.
For the sieel mill in Chapier I, the pnxlucts \vx*e bands, coils, and plate. Thus the
data for the multicommodhy nnxlel could look like Figure 4-2. W e invoke AMPI. in the
usual way toget t h e f o l b w i n g solution:
s e t ORlG: 4 origins
s e t DEST: 4 d e s L i n a L i o ns
s e t FttDD: 4 producLs
c h o c k ( p i n FROD}:
sum ( i i n O R l G } s u p p l y l i . p l = sum ( j i n DEST} demandlj.pl:
minimize Total_CosL:
sum ( i i n O R I G . j i n DEST. p i n FROD}
cosL(i.j.p) * Trans(i.j,p];
s u b j o c L L o S u p p l y ( i i n ORIG. p i n FROD}:
sum ( j i n DEST} T r a n s l i . j . p ) = s u p p l y l i . p j :
s u b j o c L t o Mui t i ( i i n O R I G . j i n D E S T } :
sum ( p i n FROD} T r a n s l i . j . p ] <= l i m i t l i . j ) :
T r a n s l i . j . •bands' 1 l »
: CLEV GARY P1TT
DET 0 0 300
FRA 225 0 75
FRB 0 0 22 5
LAF 225 0 25
LAN 0 0 100
STL 2 50 400 0
WIN 0 0 75
Transli.j. 'coils * 1 l»
: CLEV GARY P1TT
DET 525 0 22 5
FRA 0 0 500
FRE 225 G25 0
LAF 0 150 350
LAN 4 00 0 0
SVL 300 25 G2 5
WIN 150 0 100
58 B U L D N 3 L A W 3 E R P/CCCLS CHÉFTCR4
param d«nar>d ( L r J :
FRA DBT LAN WIN sr L FRB LAF í
bands 300 300 100 75 6S0 22S 250
coils SOO 7S0 400 2 S0 9S0 8S0 500
plaLc 100 100 0 SO 200 100 250 ;
param limit d e í a u l t 62 S •
param c o s L : =
Transli.j. 'plaLc' 1 l»
: CLKV GARY PITT
DKT 100 0 0
FRA 50 0 50
FRK 100 0 0
LAF 0 0 250
LAN 0 0 0
STL 0 200 0
WIN 50 0 0
In both our specificalion o f lhe shipping costs and AMPL'& display o f the solution. a
thíéé dimensional collection o f data <that is. indexed o v e r thxee sets) must be represemed
on a two-dimensional screen or page. W e accomplish this by " s l i c i n g " the data along
one index. so that h appcars as a collection o f two-dimensional tables. The d i s p l a y
command will make a guess as the best index on which to slice. but by use o f an
S E C T CN 4 2 AWULTPERCOFRXOC7CNWCCCL 59
s u b j e c t t o Time ( t i n 1 . . T } :
sum ( p i n PROD} < l / r a t e [ p l J * Makelp.t) <= avail(tj:
4 t o t a l o £ h o u r s usod by a l i p r o d u c t s
* may n o t c x c c o d h o u r s a v a i l a b l e . i n o a c h w e e k
explicit indexing cxprcssk>n as s h o w n above, \v>í can tell ii *> display a lablc for cach
product.
T h e optimal solution above shipsonly 23 tons o f ooils from (iARY k> STL and 23 tons
o f bands from PTTT to LAF. It might be reasonable to require that, if any amount at ali is
shippod, it must be at least say, 50 tons. In terms o f our nnxlel. ehher T r a n s [ i . j . p ]
= 0 or T r a n s [ i . j . p ] > = 5 0 . Unfonunately. ahhough it is possible k> write such an
"either/or" constraint in AMPL. it is not a linear constraint, and so there is no way that an
L P solver can handle it. Chapvrr 20explains how more poworful (but costlicr) integer
programming techniques can deal with \ht% and relatcd k i n d s o f discrete restrictions.
could look for constraints thai involve pnxluct ion in ail o f the w e d a . Most multiperiod
nuxlels takc a different appnxach. however, in which constraints relate each week's pro-
ducl ion to thai o f the following wxrek only.
Suppose thai wx* alk>w some o f a waek's pnxluct ion to be placed in inventory, for sale
in any laier week. W e thus add new decisk>n variables to represent the amounts invento-
ried and sold in each wxxrk. The variables >Cake[ j , t ) are retaincd. but they represent
only the amounts producxrd. which are now not necessarily the same ai the amounts sold.
Our new variable declarations kx>k like this:
The boundâ m a r k e t [ p . t J, which represent the maximum amounts thai can be sold in
a week. arenaturally transferred to S e i 1 [ p . t J.
T h e variable I n v [ p . t ] will represent the inventory o f pnxluct p a t the end o f p e r i o d
t. Thus the quantities I n v [ p , 0 ] will be the inventories ai the end o f week zero. or
equivakently ai the beginning o f the first week — in other \vx>rds. now. Our nuxlel
assumes thai these initial inventories are provided ai pari o f the daia:
It may seem ' 'inefficient" *> devote a constraint like this to saying thai a variable equals
a constant. but when it comes time ii> send the linear program to a solver, A M P L will
automalically substitute the value o f i n v 0 ( p ) for any oceurrence o f I n v [ p . 0 ] . In
most cases, wx* can concentra te on writing the nxxlel in the clearest or easiest way, and
leave matiersof efficiency *> the computer.
N o w thai w e are distinguishing sales, prcxluction. and inventory, w e can explichly
nuxlel the contribution o f each to the profh, by defining three parameters:
maximize T o t a l . P r o f i L :
sum ( p i n PROD. t i n 1 . . T } < r e v e n u e l p . t 1 * S e l 1 lp . 11 -
orodcosLlpl*Makelp.tj - i n v e o s t Ipl * i n v l p . t i ) :
As you can see, r e v e n u e [ p . t l is the amount received per ton o f pnxluct p sokl in
week t : p r c d c o s t l p ] and i n v e o s t [ p ] are the productk>n and inventory carrying
cost per ton o f pnxluct p in any w e e k .
Finally, whh the sales and inventories lully incorporaicd in*> our nuxlel. w e can add
the key constraints thai tie the wxxrks k>gether: the amount o f a pnxluct made available in
S E C T CN 4 2 AWULTFtRCOFRXOC7CNWCC€L 61
a weelc* through pr ixluciion ot from inventory. must cqual the amount disposcd o f in thai
wxrek. through sale of to inventory:
s u b j o c L Lo B a l a n ç o ( p i n PROD. L i n 1 . . T } :
M a k o l p . t l + l n v l p . t - 1 1 = S e l l lp. t ] + I n v l p . L l :
Bccause the irnlex t is from a set o f numbers. the period pre v k>us to t can be w r i l e n as
t-1. In fact, t can be used in any arithmetic expression: conversely. an A M P L cxpres-
sion such av t i - 1 may be used in any context where it makes sense. Notice also that f o r a
first-period constraint < t equal to I), the inventory term on the left is I n v [ p . 0 ] , the ini-
tial inventory.
W e now have a complete nnxlel. as shown in Figure 4-4. T o ilhistrate a solution, wxr
use the small sample data file shown in Figure 4-5: it represents a four-week expansion o f
thedaia from Figure l-4b.
1 f we put the nnxlel and data ink> files s t e e l T . s x x i and ^ t e e l T . d a t , then A M P L
can be invoked to find a solution:
a m p l : izodal ataolT.xsod/
a m p l : data ataolT.datj
ampl: aolvo;
M1MDS S . S : o p L i m a l s o l u L i o n f o u n d .
20 i L o r a L i o n s . o b j o c L i v e S1S033
a m p l : diaplay Kakoj
Make [ * . * 1 < LrJ
: bands coils : =
1 S990 1407
2 6000 1400
3 1400 3 SOO
4 2000 4200
a m p l : diaplay Invj
I n v l * . *1 <LrJ
: bands coi ls
0 10 0
1 0 1100
2 0 0
3 0 0
4 0 0
a m p l : diaplay Soll;
Soll l*.*l < LrJ
: bands coils
1 6000 307
2 6000 2 SOO
3 1400 3 SOO
4 2000 4200
62 B U L D N 3 L A W 3 E R P/CCCLS CHAPTER 4
pa ram T : = 4 :
s e t PttDD : = hands coils;
param a v a i l := 1 «10 2 «10 3 32 «1 «10 ;
param r a t e := haixis 2 00 coils 14 0 ;
param i n v O := barxis 10 coils 0 ;
param p r o d c o s t := bands 10 coils 11 :
param i n v c o s t := bands 2.S coils 3 :
param r e v e n u e : 1 2 3 4 :=
bands 25 26 27 27
coils 30 35 37 39 •»
param m a r k e t : 1 2 3 4 :=
bands 6000 6000 4 000 6500
coils 4 000 2S00 3 SOO 4200 •
Pnxluction o f c o i l s in lhe first week is held over k> be sold ai a higher price in the second
week. In the second through fourth weeks, coils are more prolitable than bands. and so
coils are sokl up to the limit with bands filling out the capacity. (Scning option
d i s p l a y _ l c o l to zero permits this output k> appear in a nicer formai, ai expbined in
Section 12.2.)
s e t PttDD: * products
s e t 0K1Q: i origins (steel millsj
s u b j e c t t o Time ( i i n O R I G } :
sum ( p i n PROD} ( 1 / r a t e i i . p 1J * M a k e l i . p l <= availlil:
We have temporarily dropped the components penaining k> the objective, *> which
will retum lavrr. We have a b o dropped the market demand parameters. since the
demands are now properly associatcd with the destinaiions in the transponaiion modek.
T h e next sicp is to replkraie the transponaiion model. Figure 3- Ia. over pnxlucts. ai
we did in the multioommodity example ai the beginning of this chapter:
s u b j e c L Lo S u p p l y ( i i n ORIG, p i n PROD} :
sum ( j i n DE57I*} T r a n s l i . j . p l = s u p p l y l i . p l :
Comparing lhe resulting produetion and transpor tal k>n modcls. w e see that the setsof ori-
gins ( O R I G ) and products (PROD) are the same in both models. Moreover, the "tons
avaihble at origins" ( s u p p l y ) in the transportatk>n mixlel are really the same thing as
the "tons produced at origins" (>Cake) in the produetion model, since the steel available
for shipping will be whatever is madeat the mfll.
W e can thus merge the t w o nuxlck. dropping the definition o f s u p p l y and substitut-
ing J í a k e [ i . p ] for theoccurrence o f s u p p l y [ i . p ] :
s u b j e c L Lo S u p p l y ( i i n ORIG, p i n PROD} :
sum ( j i n DEST} T r a n s l i . j . p l = M a k e l i . p l :
There are several ways in which w e might add an objective to complete the model. Per-
haps the simplest i s t o define a cost per ton corre sponding to each var a ble. W e define a
parameter r n a k e _ c o s t so that there is a term r ^ k e ^ c o s t [ i . p ] * >Cake [ i . p ] in
the objective for each orjgin i and product p : and w e define t r a n s _ c o s t so that there
isa term t r a n s _ c o s t ( i . j . p l * T r a n s [ i . j . p ] in the objective for each origin i ,
destinaiion j and product p . The full mixlel is shown in Figure 4-6.
S E C T ÇJN 4 3 A W C C € L CF m O C U C T O N MD T R Í W S F C R T A T O N 65
param t r a n s _ c o s L :=
sun ( j in DKSr} T r a n s i i . j ,p l
can be substkuted for > C a k e [ i , p ) . If w e make this substitui ion for ali occurrences o f
J í a k e [ i . p ] in the objeetive and in the T i m e consiraints. w e no longer need to inchidc
the >Câke variables orthe S u p p l y oonstramts in our nnxlel. and our linear programs will
be smallcra* a resuh. Nevenheless, in mo&t caies \v>Í will be better oíT leaving the nnxlel
ai it is shown above. By 4' substitui ing o u t " the J í a k e variables \v>í render the nnxlel
harder to read. and not a gr eat deal easier k> solve.
66 BULDP*3LA«3ERWCC€LS CHÉFTCR4
A s an instance o f solving a linear program b&ed on ihis nnxlel. w e can adapt lhe dato
from Figure4-2. a* shown in Figure 4-7. I icre are some represe ntative resuli values:
a m p l : diaplay Makoj
Make ( * . * !
: bands c o i l s piaLo :=
CLKV 0 1950 0
OAKY 112 S 1750 3 00
PITT 77 5 500 500
a m p l : diaplay Trana;
T r a n s ICLKV. » . M
: coils :=
DST 7 50
LAP 500
LAN 4 00
STL 50
WIN 2 50
IOARY,1
: bands c o i l s plaLo
FRB 225 850 100
LAF 2 50 0 0
STL 650 900 200
(PITT, 1
: bands c o i l s p l a L o
DET 300 0 100
FRA 3 00 500 100
LAF 0 0 250
LAN 100 0 0
WIN 75 0 50
a m p l : diaplay Tiiso;
T i m e 1*1 : =
CLKV -1300
GARY -2800
As one might expect. the optimal solution does not ship ali produets from ali miils to ali
factories. W e have used the options ú t i l t _ 2 e r o _ r o w 3 and o m i t _ z e r o _ c o l s to
suppress the printing o f tabkr rows and columns that are ali zeros. The dual vahies for
T i m e show that additional capacity is likely to have the greatest impact on total cost if it
is placed at GARY. and no impact if it is placed at PITT.
S E C T ÇJN 4 3 A W C C € L CF m O C U C T O N M D TRÍWSFCRTATON 67
W e can al&o investigate the relative oosts o f productk>n and shipping. which are the
t w o componente o f the objective:
Ckrarly the produetion costs dominate in this case. These examples point up the ability o f
A M P L li) evahiate and display any valid expression.
Bibliography
ll. P. Willums, . 1 M t ! BwUing in Halhtfuaáca! Pm grani ming (-th edition). John Wíley Si Som
(New Y<rk. 1999). An etfcnJedcompiLukin af nuny kind% af models ax*l camhinatians af iicm.
Exercisos
4*1. Pannubte a muki period svfsion af the transp<»ta«ian madel m which inventaries are kept al
Ihcof^gini
4-2. I'<rmuLue a cambinatian af A «ransp<»ta«ian xnadcl far cach o f severaü faads, and A dict
model eachdesfinatKm.
4-3. The follawmgqucstians pertam tothe muliperiad praduclian made] anddati af Scclkin 4.2.
(A) Display the nuigiiul v alues as sociited with th: canslraints T i m e [ J. In which periods does it
appear thit additianalprodu^kin capKÍty would hc merst vahiable?
(b) By soliáting ackJitkirul sales, yau might hc atile to i w e th: uppcr bounds markoL l p . L|.
Displiy éie reducrd costs S c l l lp . Ll . r t and use them tci S i ^ H t whether yau would prefer ki
ga after more crders af banJs af coils in each wrck.
(c) If the invenkry costs are ali pctsitw. any optimal salutkin will haw zevo inwnfcirics after the
last w w l . Why is this so?
Th rs phcnamcnan is an exampkc of an "end effecl". Because th: model «mies to an end after
period T. the salutkin tends to hehaw AS if produetian is to be shut ckiwn after thil paint. One way
o f dcalmg with end effects is to i n c r w e the number af wrcks modekcd: then the end effecls shaukJ
have little influencv an the sahitian far the earlier wx-ks. Aixither apprcuch isto modifv the made)
to better rvflccl the nralities af inwnlories. Desenhe same modificatians yau might maie k» the
constraints. anJ the abjeclivc.
4-4. A producer af packagcd cookies xixJ craciers runs xevenl shifts each month AÍ its large hik
ery. This exercise is concvrned with a mui ti period plaiming model for decidi ng haw manv crews
toempkiy each manth. In the algebraic descriptianofthe model there AIC sets .Vai shifts ai*l PAf
68 BULDP*3LA«3ERWCC€LS CHÉFTCR4
pioductc. oixl the piinnirçg hcsi/on is T four u w k period s. T h : relevont operacional dita an: as
falbwx:
T o a i hours required f<r produ^kin in each period may nal exceed tolal hours available f r o m ali
shil*.
As reqinred by th? defmilkin of .1/. Ihrs c o m trai nt reslricfe any chinge to fie bclwccn a reduetion o f
.1/ cnrws and an i n c r e w e of .1/ cnrws.
( a ) Tormulale thw model in A l ü , aixJ s o h e the folkiwirç; i m t i n c v . There an: T= 13 period*./ = 8
pxiduction lines. and a maximum charçge o f .1/ = 3 crrws per p e r i a d T h : produett are 1&RI33,
24RKG. and 2 4PRCX with producl ion rales rp o f 1.194. 1-509 and 1309 icspeclively. Cnrws w a k
eHher a day shift w i t h wages w , o f 144,900. <* a night shift wiéi wages 5123,100. The d e m n d c
and wcrking hiurs an: g i v e n a s f o l l o w s bv period:
feàod/ d **ái..t
1 12120 0-0 156
2 76-0 3062 Oi) 152
3 &U 3190 Oi) 160
4 913* 23ÜK4 Oi) 152
5 115.0 2SCS0 Oi) 156
6 i m 32Z2 Oi) 152
7 79.6 9596 Oi) 152
* 1110 257.6 Oi) 160
9 121.6 335A 0-0 152
10 470.0 m o llCGi) 160
11 731-4 2S4Ü 0-0 160
12 99.4 97D0 Oi) 144
13 1404 343* Oi) 144
S E C T ÇJN 4 3 A W C C € L CF m O C U C T O N M D T R Í W S F C R T A T O N 69
D í ^ k t y the numbcn a f crews lequired cm cach shift. Y o u will finJ manv fractioiul numbers o f
crews; how w o u l d y a u convertthis sohitian ( o a n optimal o n e in wholc numbers?
( c ) Because of the Emit on the charçge in crews fram period t o period, more crews thin neces*iry
are empki\ed in some periods. One w a y t o deal wilh this i s t o c a n y anentories f r o m one period ki
the next, so as to smoath out the amount of praduclion requaed in cach period. Ackl a variablc for
t h : amount of invertery of cach p r o d u z i f t t cach period, as in the model o f Figure 4-4, and odJ
constraints ihit relate m\enlory lo praduclion xixi dcmand. (Because inventaries can be carried
f c r w a r d produetion need not bc £ dcmand in e v e r y period as lequired b ) the previous ver-
sions.) Also make a provi sum for s e * m g m ã u l inverteries Io zero. 1'iiully. odJ an invefltcay cost
p*r period per 1000 b o t e s lo the objecti\e.
L e i the m\enlory costs bc $34.56 for product l&RUG. and J 4 3 A fer 2 4RKG and 2 4 P R O . Sohe
the lesukâig linear program; displiy the crew si/es aixi inverter)' leseis. I l o w diffcrcrt is thrs
solution? I l o w much of a s i v m g is achic\ed in labor cost. at how murh expense in inventofy cost?
( d ) The dcmanJs in the g i w f i dati peak at evitam pericids. when special discount promotions are in
cffect Big inventarie» are built up in advance of these pcaks, p j j i x uLulv before period 4 . Haked
c<Kids are pcrishibk", hawe\er. so thit building up in\enlories just a ceitiin number of periods is
unreabstic.
M o d i f y the model s o thit the inventor)' variables are indcxcd by product. period and age, where
age runs f r o m 1 Io a specified Imüt A . Add constraints that the «n\enlories o f age 1 after any
period canncit cxceed the amounts ju<t produced. aixl thit invcnlcries of age <J>1 after period í
caimot exceed the «nexTilories o f age a - 1 after period l - 1 .
V c r i f y thit. with a maximum in\entofy age of 2 periods. you can use essentially the same sohitian
as in (c>, but that wilh a maximum invertery age o f 1 there are some pcricids that require move
crcws.
( e ) Suppose now that instcad o f atkJing a third index cm inwntory varúbk-s as in <d>. you impose
the following a n e n l o r y constraint: The amount of product p in inventory after period i may not
exceed the fcitil produetion o f product p in periods i-Á + 1 tfiraugh I.
lixplam why this constraint is sufficicrt Io preveni any mventory fram being m o r e than A periods
o kl. provided thit inuentoriex are managed cm a fira in. firas vai/ basis. Support your conchisian
by showing that you get the same results as in <d> when s a l v i r ç wilh a maximum inverter) 1 age o f
2 "cr o f 1.
<f) lixplam how you would modify the models in <c>, <d>, and <e) to accourt fer inicial in\entnries
thit aie nai zero.
4 - 5 . Mui ti period linear programs can be cspcciillv difficull t o devekip. because the)- require dita
p a l a m mg lo the future. T o hct^gc acainst lhe uncertaint)' of the fuluie. a user of these IJN typi«
caDy de\elcç>s various scx-niricts, contiinirçg diffcrcrt fcrccasts o f certiin key jurameters. This
cxercise asks you t o d e v c l o p whatis knounas a stcchastic program. which fmds a solution that can
bc cxmsidercd robust over ali sex^naxiers.
(a> The revenues per tem mighl bc particulirly hard Io predict. because the)- depend on fhictuaàng
m ã i h ^ conditloiK. l x t the l e v e n u e d a t i in 1'igun: 4-5 be scenario 1, aixl also ccmsider scxTiario 2 :
70 BULDP*3LA«3ERWCC€LS CHÉFTCR4
parair. rovonua: 1 2 3 4
bandfl 23 24 2b 2S
COÍLA 30 33 35 36 ;
aixl s c v m r i o 3:
parair. rovonua: 1 2 3 4
bandfl 21 27 33 3S
«OÍlfl 30 32 33 33 ;
By solvirç; the éirec associalcd linear programs. vcriíy thit each o f éicse scvnark>s leads lei a cÜf
ferent optimal produetion anJ sales Xtrategy, e\vn kv the first w A . Y o u necd o n e stralcgy, how
ever, not thrcc. T h : purpose ctf the stochostic programmirçg approach is t o determine a sirçgle sohi
tkinthit produom a g o o d profit " o n avcngo" in a c v i t i i n « n * .
<b) As a first stcp fciword formulatirçg a stochostic prqgran. c o m i d e r h o w the threr scvnorkis could
b e bxiught togelief into o n e linear program. Define a parameter S » t h e number of s a l á r i o * . anJ
replicate t h : n r a n u e dati o v e r the set 1 . . S:
parair. 3 > Q;
par air. rovonua f PBQD, 1 . . T , 1 . . S) >- 0;
Replicate ali th- variables anJ constraints in a sniuUi w « y . ( T h : idea is th- some os e o r l k r in this
chipter. where w e repKcHed model camponents over product* or wccks.)
Define a new collectkin of p n m e t R S p r o b . fc» represent your e s t i m a * of the prc^jiliibty thit
a scxnurio r. t i f a » pixev:
H i e o t j e c i w funetion is the expected profit. which equils the sum o v e r ali sccnarios of the proba
bility o f each « q u r ô times the optimum profit under thxt somaria:
maxlmlaa Expacta<*_Prafít:
fluir* {fi í n 1 . . S ) probTfll •
sum f p í n PROD, t í n 1 . . T ) (rauanuaíp, t , f l ] # S a l l [ p , t , A] -
p r o d - c o f l t r p ] *KMXQ t , «1 - ínvcofltlp] -Invíp, ;
Complete th- fcmiulUkin of this mui ti somaria linear program. and put tagether the dati kw it. Let
th- profaÉbiliticx of xcc«Briat 1, 2 and 3 be 0 4 5 . 0 3 5 and 02(1 lespectively. Show that the sohi*
tkinconsisfs o f a productianxtntegy for each somaria thit K th- xune as t h : xtrategy in (o).
to í p í n PJOD, u í n 1 . . S - 1 ) :
l^fl] - SCaXAíp,
A d d the anakigous constraints k* the Irr/ and S e 11 variibles. S o l w the stcchistic program. aixl
verify that the sohiticn consists of a single period 1 strafc-gy for ali thnx- sccnaricis.
( d ) A f t e r g e « i n s w u r soluticti in ( c ) , use the f o l l o w i n g command lei locik at the profits thit th- i t e
onunended xtrstegy w i l l a c h i e v e underéie three xtfíancrs:
SECT ÇJN 4 3 A WCC€L CF m O C U C T O N MD T R Í W S F C R T A T O N 71
d i f l p l a y ffl in 1 . . S )
fiurr. f p í n PROD, c In 1. . ? ) ( r a v a n i A í p , t , A] - S o l l rp, t , fl] -
prâdâaat rpT!CaX*rp, c^fll - i n v c o o t rp] • I n v r p , t , f l ] ) ;
5
Simple Sets and Indexing
T h e next four chapters o f this book are a compre hensive presentation o f A M P L ' s facil-
ities for linear programming. T h e organi/ation is by languagc features. rather than by
nnxlel types as in the four prcceding l i t o r a l chapters. Since the basic features o f A M P L
tend t o be closely interrelated. d o not attempt t o explain any one feature in isohtion.
Rather. w e assume at the outset a basic knowledge o f A M P L such a* Chapters I through I
provide.
W e begin w k h sets, the mo&t fundamental componenis o f an A M P L nnxlel. Almo&t
ali o f the parameters. variables. and constraints in a ty picai nnxlel are indexed over sefc.
and many expressionscontainoperations (usually summations) over sets. Set indexing is
the feature that permits a concise nnxlel t o describea large mathematical program.
Because sets are s o fundamental. A M P L o f f e r s a broad variety o f set types and opera-
tions. A set's members may be strings or numbers. ordered or unordered: they may occur
singly. or as ordered pairs. triples or l o n g e r 4 t u p l e s " . Sets m a y be defined by listing or
computing their members explicitly, by apptying operations like union and intcrsection t o
other sets. or by s p e c i f y i n g arbitrar y arithmetic or logical c\>nditk>ns for membership.
A n y nnxlel oomponent or iterated operation can be indexed o v e r any set. using a stan-
dard f o r m o f indexing expression. Even sets themselves may be declared in colleetions
indexed o v e r other sets.
This chapter inuoduces the simpler k i n d s o f sets. ai w e l l as set operations and index-
ing expressions: it conchidcs with a discussion o f ordered sets. Chapter 6 shows h o w
these ideas are extended t o c o m p o u n d sets. including sets o f pairs and triples» and indexed
collectk>ns o f sets. Chapter 7 is devoted t o parameters and expressions. and Chapter 8 t o
the variables. objectives and constraints that make u p a linear p r o g r a m
73
74 S HFLE SETSAf*}N D E X N G CHífTÇRS
entity — such as raw materiais, pnxlucts. factories or cities. O f t e n the sirings are chosen
t o have recogni/able meanings ( c o i l s , F I S H , N e v _ Y o r k ) . but they could just ai wc\\
b e c o d e s known only t o the modeler ( 2 3 R P F G , 4 8 6 / 3 3 C ) . A literal string thatappears
in an A M P L model must be delimhed by quotes, ehher single ( ' A & ? ' ) or double
( ' B e l l + H o w e l l •). In contexts, upper case and l o w e r case letters are distinct, s o
that f o r example ' £ i s h " , ' F i s h V a n d • F I S H ' representdiíTerentset members.
T h e dcclaratk>n o f a set need only contain the k e y w o r d s e t and a na me. For e x a m -
ple, a nnxlel m a y declare
ML PROD:
t o indicate that a cenain set will be referred t o by the name PROD in the rest o f the nnxlel.
A name may be any sequence o f letters, numerais, and underscore ( _ ) charaeters that is
not a legal number. A f e w names have special meanings in A M P L , and may only be usod
for specific purposes, while a larger number o f names have predefined meanings that can
be changed if they areused in some other way. H>r example, s u m is reserved f o r the iter-
ated addition operator: but p r c d is merety pre-tlefined ai the iterated muhiplieation
operator, s o you can redefine p r c d as a set o f products:
set prod:
This expression may be usod anywhere that a set is valkl, for example in a nnxlel state-
ment that gives the set PROD a f i x e d membership:
1990 .. 2020 by S
This kind o f expression can be used anywhere that a set is appropriate. and in particular
within the aisignment phrase o f a set declaration:
By giving the set a shon and meaningful name. this declaration may help to make the rest
o f the model more readable.
It is not good practice to specify ali the numbers within a . . expression by literais
like 2 0 2 0 and 5, unless the values o f these numbers are fundamental to the nnxlel or will
rarely change. A better arrangement is seen in the muhiperkxl produetion example o f
Figurei 4-4 and 1-5. where a parameter T is declared to represem the number o f periods.
and the expressions 1 . . T and 0 . . T are used to represem sets o f perkxls over which
parameters. varubles. constrainti and sumi are indexed. The value o f T ti specified in
the data. and is thus easity changed from one run to the n e x t As a more elabora te exam-
ple. \vv? coukl write
param s L a r L i n L o g c r :
param cr>d > s L a r L i n L e g « r :
param i n L o r v a l > 0 i n l o j c r :
s e t YKARS = s t a r t .. o n d by inLorval:
param s L a r L : = 1990:
param e n d : = 2 0 2 0 :
param i n L o r v a l : = 5:
76 S HFLE SETS AfO W E X N 3 CHAPTER 5
s u b j c c t Lo B a l a n ç o ( p i n PROD. t i n 1 . . T } :
Hakclp.tl + lnvlp.t-11 = S e l l l p . t j + Invlp.tJ:
Y o u might expect 0 and I t o be members o f this set. but things d o not work out that w a y
due t o rounding error in the lloaiing-point computatk>ns. h is unwise t o use fractional
numbers in sets. if your model r e l i e s o n set members having precise vahies. There should
be n o c o m p a r a b l e problem with integer members o f reasonablc size: integers are repre-
sented exaetly for magnitudes up t o 2 5 3 (approximately I O 1 6 ) f o r IEEE standard arith-
metic, and up lo 247 (approximately IO14) f o r a l m o s t any computer in current use.
A u n i o n 13 unem: i n c i i i c r A c r B
A inter B intcrcclkin: in both A JLJKI B
A di££ B difíerencv: inAbutncitB
A !^mdi í £ B xymxm-tric diflevencv: in A or B but not b<ith
The operands o f set operators may be other set expressions, allowing more compkrx
expressions to be built up:
The operands must always represem sets. however. so that for example you must write
Y l u n i o n ( 2 0 2 5 ) , not Y l u n i o n 2 0 2 5 .
Set operators group to the left unless parenthesei are used to indkratc otherwise. The
u n i o n . d i f f , and a y m d i f f operators have the same precedence, just below that o f
inter. Thus, for example,
A u n i o n 13 i n L e r C d i í í D
is parsed ai
<A u n i o n <B i n L e r CJ J d i í í D
m l M12JR19J: i n u L r i e n L c w i t h minimum r o q u i r c m c n L r .
M L MAXR&Q: i n u L r i e n L c w i t h maximum r o q u i r c m c n L r .
M L NITTR: * a l i n u L r i e n L s (IHJBIOUSJ
But then you would be relying on the user o f the nnxlel to make sure that NUTR contai ns
exactly ali the members o f M I N R B Q and MAXRBQ. At best this is unnecessary work, and
at worst it will be done incorrectly. Instcad you can define NUTR as the unk>n:
A l i three o f these sets are necded, since the nutrient mínima and maxima are indexed o v e r
M I N R E Q and XAXRBQ,
T h e modificatk>n o f the rest o f the nnxlel is straightfonvard: the result is shown in Figure
5-1.
A s a general principie, it is a had idea t o set up a nnxlel s o that redundam information
hav t o be provided. Instead a minimal necessary collection o f sets should be chosen t o be
supplied in the data, while other relevant sets are defined by expressions in the nnxlel.
"*B2" in NUTR
is true if and only if the string • B 2 ' is a member o f the set N U T R . T h e expression
MINRKQ w i t h i n NlfTR
SECTCNSS NC€X NG EXFPESS CNS 79
is tme if ali members o f the set X I N R E Q are also members o f N U T R — thai is. if
X I N R E O i s a subset o f (or is the same a s ) N U T R . T h e i n and w i t h i n operators are the
A M P L c\>unterpark o f € and c in traditk>nal algebraic notation. T h e distinction betwxxrn
members and sets ii especially imponant here: the left operand o f i n must be an expres-
sion thai evahiates *> a string or number. whereas the left operand o f w i t h i n must be an
exprcssion thai evakiates t o a set.
A M P l . also providos operators n o t i n and n o t w i t h i n . which rever se the tmth
value o f their rcsult.
Y o u may apply w i t h i n directly t o a set you are dcclaring. k> say that it must be a
subset o f s o m e other set. Reiurning t o the diet cxample. if ali nutrients have a minimum
requirement but only some subset o f nutrients has a maximum rcquiremcni it would
make sense t o declare the sets ai:
.cot N U T R ;
.cot MAXR&Q w i t h i n NUTR:
A M P L will rejcct the daia f o r thii nuxlel if any member s p e c i f i e d f o r MÀXREQ ti not also
a member o f N U T R .
T h e buih-in function c a r d computes the number o f members in ( o r cardinality o f ) a
set: f o r example. c a r d ( N U T R ) is the number o f members in N U T R . T h e a r g u m e n t o f
the c a r d function may be any exprcssion that evaluaies t o a set.
p a r a m r a t e (PttDD} > 0:
param a v a i i ( 1 . . T > > = 0:
Laier in the model. refer ene es t o these param et ers are subscriptcd with a single set mem-
ber, in expressions such ai a v a i l ( t ) and r a t e ( p ) . Variables can be dcclarcd and
used in exactly the same w a y , except thai the key word v a r takcs the p l a c e o f p a r a m .
T h e namei such as t and i that appear in subscripfc and other expressions in our
nuxlels are examples o f dummy Índices thai have been defincd by indexing expressions.
In fact, any indexing exprcssion may optk>nally d e f i n e a dummy index thai mns over the
specified set. D u m m y Índices are convenient in s p e c i f y i n g bounds on parameters:
80 S H F L E S E T S Af*} N D E X N G CHífTÇRS
and on variables:
They are also essential in specifying the sets o v e r which constraints are definod. and the
sets over which summaiions are done. W e have often seen these uses k>gether. in decla-
rai k>ns such as
s u b j c c L Lo T i m e ( L i n 1 . . T } :
num ( p i n PROD} < l / r a L o l p l J * Make l p . Ll <= availlLl:
s u b j c c L Lo D i o L _ M i n ( i i n M1NR133}:
num ( j i n FOOD} a m L [ i . j l * B u y l j l >= n_min[i\:
An indexing expression consists o f an index name. the keyword i n . and a set expression
ai before. W e have been using single letters for our index names. but this is not a
requircment: an index nanie can be any sequcncc o f letters. digite, and underscores that is
not a valid numbcr. just like the name for a model componeni
Akhough a name defined by a nnxlel componentes declaratk>n is known throughout
ali subsequent statements in the model. the definition o f a dummy index name iseffective
only whhin the scope o f the defining indexing expression. NormaDy the scope isevident
from the context. For instancvr. in the D i e t _ M i n declaralion above. the scope o f { i in
M I N R B Q } r u n s t o t h e e n d o f thestaiement, sothat i can be used any where in the descrip-
tion o f the constraint. On the other hand. the scope o f { j i n FOOD) covers only the
summand ârnt [ i . j 1 * Buy t j 1. The scope o f indexing expressions for sums and other
iterated operak>rs isdiscussed fuxther in Chapter 7.
Oncvr an indexing expression's scope has ended. its dummy index becornes undefined.
Thus the same index name can be defined again and again in a model, and in fact it is
gcxxl practice to use relatively f e w different index names. A common convcntion is to
associate certain index names with cenain sets. so thai for example i always mns over
NUTR and j always mns over FOOD. This is merely a convention. however, not a reitric-
tion imposed by A M P L . Indeed. when \v>í m o d i f i e d the diet model so thai there was a
subset H I N R B Q o f K U T R . \V>Í used Í to run over X I N R E Q as wvll a s N U T R . The opposite
situatk>n occurs. for example. if w e want to specify a constraint that the amount o f each
food j in the diet is at leait some fraction m i n _ . f r a c ( j ) o f the total food in the diet:
s u b j e c L Lo F o o d _ R a L i o ( j i n FOOD}:
B u y l j l >= m i n _ £ r a c l j l * sum ( j j i n FOOD} Buy(jj);
Since the scope o f j i n FOOD extends to the end o f the declaratk>n, a diíTeient index j j
is defined to run over the set FOOD in the summation within the constraint.
A s a final option. the set in an indexing expression may be f o l b w c d by a colon < : )
and a lógica) condition. The indexing expression then represents only the subset o f mem-
bers thai sat&fy the condition. For example.
SECTCNSS NC€X NG EXFPESS CNS 81
describes lhe sei o f ali fcxxls whose minimum and ma xi muni amounts are nearly the
same. and
describes the set o f nutriente that are either in MÀXREQ or f o r which n _ m i n is positive.
The use o f operators such as o i and < to form lógica! cx>nditk>ns will be fuDy expbined
inChapter7.
By specifying a condhion. an indexing expression defines a new s e t You can use the
indexing expression *> represem this set not only in indexed declaratioas and summa-
tions» but anywhere else that a set expression may appear. For example. you cx>uld say
either o f
to define NUTRBQ to represent our precxrding example o f a set expression. and you could
use either o f
t o define BODIREX) to be the set o f ali nutrients that have both minimum and maximum
requirements. It's not unusual to find that there are several ways o f describing some
complicated set, depending on how you combine set operatk>ns and indexing expression
conditions. O f course. some possibilities are ea^ier to read than others. so it's worth tak-
ing some trouble to find the mosi readable. In Chapter 6 w e also discuss eíTiciency con-
sideratk>ns that sometimes make one alternaiive preferable to another in specify ing c o m -
pound sets.
In addition to being valuable within the nnxlel. indexing expressions are use fui in
d i a p l a y statements to summari/e characteristics o f the data or solution. The following
example is based on the nnxlel o f Figure 5-1 and the data o f Figure 5-2:
ampl: a o l v o ;
CPLKX 8 . 0 . 0 : o p L i n a l s o l u t i o n : o b j e e t i v e 74.27382022
2 d l i a i s i m p l e x i t e r a t i o n s <0 i n pha.se IJ
A M P L interactive commands are allowad to refer to variables and constraints in the con-
dition phra*e o f an indexing expression. as illustrated by the lavt t w o d i s p l a y staie-
82 S W L E S E T S AND N C € X N 3 CHífTÇRS
M t MINRBO : = A B l B2 C CAL ;
M L MAXRKQ : = A N A CAL ;
sscL FOOD : = BKKF ÜLK F1SJI 1JAM MC1I MTL SPG TUR :
mente above. With kl a nnxlel however. only seis. porameters and dummy índices may
be mentioned in any indexingexpression.
T h e set BODIREX) above might w e l l be empty, in the case where every nutrient ha*
either a minimum or a maximum requirement in the data. but not both. Indexing over an
empty set is not an error. When a nnxlel component i* deelared to be indexed over a set
that turns out k> be empty, A M P L simply skips generating that component. A sur» over
an empty set is zero, andother itcratcd operators over empty sets have the obvious inter-
pretations<see A.4).
describe lhe difTerence between thfc \vvek's inventory and the prevk>us \v\rek's inventory,
for example, we need the weeks to be ordered so that the " p r e v i o u s " week is always wc\\
defined.
A n A M P L model can also define itsownordering for any set of numbersor strings, by
aJding the keyword o r d e r e d or c i r c u l a r k> the set's declaraiion. T h e order in
which you give the s e f s member s, in ehher the nnxlel or the data, is then the order in
which A M P L works with them. In a set deelaroJ c i r c u l a r , the first member is consid-
erei! to follow the lavt one. and the bst to precede the first: in an o r d e r e d set. the first
member has no predecessor and the bst member has nosuccessor.
Ordered sets o f strings often provide better documcntaiion for a model'* data than sets
o f numbers. Reiurning to the multiperiod pnxluciion mixlel o f Figure 4-4, w e observe
thai there is no way ii> tell from the daia which wveks the numbers I through T refer to, or
even thai they are wxreks instead o f days or months. Suppose thai insteaJ \v>í let the
weeks be represented by an ordered sei thai contains. say, 2 7 s e p , 0 « i o c t , l l o c t and
1 8 o c t . Thedeclaraiionof T is replacedby
M L WEEKS o r d e r ©d:
s u b j e c t Lo B a l a n c e ( p i n PROD. t i n WEEKS} !
Make lp. t | «• I n v l p . p r e v ( t ) 1 = S e l l l p . t l «• I n v l p . t l ; 4 WRONG
This is not quite right, howxrver, because when t is the first wvxrk in WEEKS. the member
prev {t} is not defined. When you try k> solve the problem, you will get an error mes-
sage like this:
One way n> fix this is to give a separaic balance constraint for the first period, in which
I n v l p . p r e v ( t > ] is replaced by the initial inventory, i n v O [ p ] :
s u b j e c t t o B a l a n c e O ( p i n PttDD}:
Make ( p , f i r s t (WEEKS) 1 «- i n v O l p l
= S e 1 1 l p » f i r s t ( W E E K S ) ] + I n v l p . f i r s t (WEEKS) 1 :
The complete nnxlel and daia are shown in Figures 5-3 and 5-4. As a traJeoíT for more
meaningful wede names, we have to write a slightly more complicated nnxlel.
A s our example demonstrais, AMPL provides a variety o f funetions that apply speeif-
ically to ordered sets. These funetions are o f three basic types.
84 S W L E SETS A f C N C € X N 3 CHífTÇRS
s a t PttDD: * productc
s e t WEBXS o r d c r o d ; i number o £ w e e k s
param r a l e (PROD} > 0 : * t o n s p e r hour produced
param i n v O (PROD} > = 0 : 4 i n i t i a l inventory
param a v a i l (WKUXS} > = 0 ; * h o u r s a v a i l a b l e i n week
param m a r k e t {PROD. WKHXS} > = 0 ; 4 l i m i t on t o n s s o l d i n week
maximize T o L a l _ P r o £ i t :
sum ( p i n PROD. t i n WKKXS} < r e v e n u e ( p . t j * S e l l ( p . t j -
p r o d e o s t Ipl *Make lp . t j - i n v e o s t ( p 1 * l n v [ p . t ] J :
i Objective: Lotai revenue less costs in ali weeks
s u b j e c t t o Time ( t i n WKKKS}:
sum ( p i n PROD} (1/ratelplJ * Make l p . t l <=availltl;
4 T o t a l o £ h o u r s u s e d by a l i p r o d u e t s
4 may n o t e x c e e d h o u r s a v a i l a b l e . i n c a c h wcck
s u b j e c t t o B a l a n c e O ( p i n PttDD}:
Make l p . f i r s t ( W E I i X S J | «• i n v O l p l
= S e l l [p . f i r s t ( W K U K S J 1 + I n v ( p . f i r s t (WKKKS) 1;
s u b j e c t t o B a l a n c e ( p i n PROD. t i n WKBXS: o r d ( t J > 1 } :
Make ( p , t l + i n v l p . p r e v ( t ) 1 = S e l l l p . t j + I n v l p . t J ;
i T o n s p r o d u c e d arxi t a k e n f r o m i n v e n t o r y
4 must 0 3 u a i t o n s s o l d arei p u t i n t o i n v e n t o r y
First, there are funetions that return a member from some absolute position in a s e i
You can \vrite f i r s t {WEEKS} and l a s t {WEEKS} for the first and last members o f
the ordered set WEEKS. T o pick out other members. you can use r»es\ber { 5 . W E E K S } ,
say, for the 5th member o f WEEKS. The argumenta o f these funetions must evaluaie t o a n
ordered set. except for the first argument o f m e s t b e r , which can be any expression that
evaluates *> a positive inie ger.
A second kind o f funetion returns a member from a positk>n relative to another mem-
ber. Thus you can write p r e v { t . WEEKS} for the member immediately before t in
WEEKS, and n e x t { t . WEEKS} for the member immodiaiely after. More generally,
expressions such ai p r e v { t . WEEKS. 5 } and n e x t { t . WEEKS. 3 > refer to the 5th
member before and the 3rd member after t in WEEKS. There are also " w v a p o r o u n d "
versk>ns p r e v w and n e x t w that work the same except that they treat the end o f the set
ai wrapping around to the beginning: in effect, they treat ali ordered sets ai if the ir decla-
SEC7CN56 CFC€FED3ETS 85
param a v a i l := 27 s e p 4 0 0 4 o c t 40 lloct 32
param r a t e := b a n d s 200 c o i l s 140 :
param i n v O := bands 10 coils 0 :
the functk>ns o r d ( t ) and p r e v { t > are interpreted as if they had been written
o r d { t . WEEKS} and p r e v { t , WEEKS \.
Ordered sets can also be used with any o f the A M P L operators and funetions that
apply to sets generally. The resuh o f a d i £ i operatk>n preserves the orderingof the krft
operand. so the material baiano? constraint in our example oould be wrhten:
s u b j e c t t o B a l a n c e ( p i n PROD. t i n WEEKS d i í í ( í i r s t ( W E E X S ) } } :
Makelp.tl + Invlp .prev <tj 1 = S e l l l p . t l + I n v l p . t J ;
For u n i o n . i n t e r and s y r > d i £ £ , however, the ordering o f the result is not wvll
defined: A M P L treats the result as an unordered set.
86 S HFLE SETS Af*} N D E X N G CHífTÇRS
F o r a set that is containcd in an ordered sei. A M P L provides a way t o say that the
ordering shoukl be inherited. Suppose for e x a m p l e that you want to try running the mul-
tiperiod pnxluction mixlel with hori/ons o f d i f f e r e m lengths. In the f o l l o w i n g declara-
tions» the ordered set À L L _ W E E K S and the parameter T are given in the data. while the
subset WEEKS is defined by an indexing expression fc> include only the first T wxreks:
s e t ALL_WKKXS o r d e r e d ;
param T > 0 i n L e g o r ;
interval [ a . b 1 r { * : a á . t á b|.
inLorval ( a . bl m [x: a < x á b ) ,
inLerval [a. bj m [x: a á x < b ) .
inLorval (a. bj m [x: a < x < b ) .
inLeger [a. bl v ( * 6 / : a á r á b | .
inLeger ( a . bl t (*€/:a <
inLeger [a. bj r \x <. / : a á x < b |.
inLeger (a. bj * ( r d / : a < r < b |
where a and b are any arithmetic expressions, and / denotes the set o f integers. In the
declaraik>n phrases
in inürvol
w i t h i n inkrrvol
o r d e r o d b y / r e v e r s e d / inirruil
c i r c u l a r b y / r e v e r s o d / instruil
SEC7CN56 CFC€FED3ETS 87
to say lhai lhe pnxluction raies have to be greater than zero and noi more than some pre-
viously defined parameter r w i x r a t e : you could write the same thing more concisely as
or equivalenily ai
param r a L e ( PROD} in ( 0. I n í i n i Ly 1;
in Figure I - I a . In general, inwrrvals do not let you say anything new in s e t o r parameter
declaratk>ns: they just g i v e you ahernative w a y s to say things. (They have a more e*sen-
tial rofc in defining imponcd functions, asdiscussed inSection A 2 2 . )
T h e predcfined infinitc sets R e a i s and I n t e ^ e r a are the sets o f ali lloating-point
numbers and integers, respectively. in numeric order. The pie defined infinite sets
A S C I I , EBCDIC, and D i a p l a y ali represem the universal set o f strings and numbers
from which members o f any one-dimensional set are drawn. A S C I I and E B C D I C are
ordered by the ASCII and EBCDIC collating sequencx^s, respectively. D i a p l a y has the
ordering used in A M P L ' s d i a p l a y command (Section A . 16): numbers precede literais
and are ordered numerically: literais are soned by the ASCII collating sequence.
A s an example, you can declare
KCL PROD o r d e r e d by A S C I I j
to makc A M P L ' s ordering o f the members o f PROD alphabetical, regardlessof their order-
ing in the daia. This rcordcring o f the members o f PROD no elYect on the solutions o f
the nnxlel in Figure l - l a , but it causes A M P L l&tingsof most entities indexedover PROD
toappear in the same order (see A . 6 2 ) .
Excrcises
5-1. ( a ) Dstplsy th?
-5/3 . . B/3 by 1/3
0 . . 1 by .1
<b) Trv t h : following commancfc fam Sections 5.2 and 5 4 o n your computer:
5-2. Revise the model o f Exerci se 1 6 so thit it makcs use of ( w i different altribute set<: a set o f
altributes IhjU h a w l o w e r bniits. axxl A set o f altributes thit h i v e upper limito. Use t h : same
apprcuch as in Figure 5-1.
W e want Io xààvc the linear program that covexs only the wex-ks f r o m T b e g i n through T e n d . We
still want the p n m e t e n to w c the indexing 1 . . T . howx-ver. so that w ? don't need Io chinge the
d MA t abi es e\ery time w e try a difíerent value fer T b e g i n o r T o n d .
T o stul with. w e can chinge e v e r y occum.-IKX" o f 1 . . T in the varnblc, objective and cxirotraint
declarations lo T b e g i n . . T e n d . By m a l mg these and other n o » a i y c h a i ç e s . a c a t e a model
thit cornxtly co\crs only the d e â r c d wx-ks.
<b) N o w suppote that ux- define a different scalar parameter.
W e want Io " a g g r c g a t e " the model. so thu o n e " p e r i o d " in our L P bccomcK TAGG wex-ks kirçg.
rather thin one wx*x-k. TTirs woukl be appropmte if w e h i v e . « y , a year o f w e d l y dafcu which
would yíeld an I.P l o o Luge Io be conscnient f<r analysis.
T o aggregale properly. w e must define the avaiUbilily of hours in each period Io be the sum of the
availibilities in ali wx-ks o f the periad:
parair. x v ã i l _ A g ç { t í n 1 . b y
- aun f u í n t . . t • T a g g - 1 ) a v a i l T u ] ;
The pirameters m & r k e t and r e v e n u e must be smulirly summed. Make ali the necx-s*iry
chinges to the nuxlel of figun? 4 - 4 so that the rcsuking I-P k properly aggregited.
SEC7CN56 CFC€FED3ETS 89
(c> Re d o tfie modek o f ( a ) and ( b ) t o use an crdcred se* of string* f<* the p e r i c i d * , » in Figure 5-3.
5 - 5 . E&fcnd the tramportitkin model o f f i g u r e 3 la fc> a mukipcrkid serxíon, «n which the periad*
are monéis represei*ed by an ordrred se* of characler stnngs such as " M a n " , " 1 ' o b " and so forth.
lJ<e inventaries a l t h : <rigim link the periods.
fl*t WEDCSQ ú t r d * r * l ;
fl*t WEDCS - f i i n WEEXSQ: â » r d ( i ) > 1) ôtrdatr*d b y WEEKSQ;
Cojiy rçjht O 2003 by Robcrt Fourer. DfevkJ M . Qay aikJ B r i a n W . Kcrnigh.in
6
Compound Sets and Indexing
< - P I T T - . -STL-J
(-bandas". Sj
(3.101)
91
92 O O W F C X W D S E T S AND N C € X NQ CHífTÇRÔ
( < " P I T T " , " S T L " ) . < " P I T T " . "l'RK"J . < " P I T T - . - DKT"J . ( " C L K V " . " F R K " J }
( < 1 . 1 J . ( 1 . 2J . ( 1 . 3 J. ( 2 . l j . <2.2J . < 2 . 3 j . <3. l j . <3 .2 J. < 3. 3j }
Because setsof ordered pairs are often large and subject *> change, howxrver, they seldom
appear explichly in A M PI. nnxlek. instead they are described symbolically in a variety o f
ways.
T h e set o f aü ordered pairs from t w o given sets appears frcqucntly in our examples.
In the transponation nnxlel o f Figure 3- Ia, for instance, the set o f ali origin-destination
pairs is wrfctcn a* either o f
( O R I G . DKST}
( i i n ÜR1G. j in DKST}
depending on whether the oontext requires dummy Índices 1 and j . The multiperiod pro-
duction nxxlel o f Fjgure uses a set o f ali pairs from a set o f strings (representing prod-
ucts) and a set o f numbers (representing weeks):
(PROD. 1 . . T }
( p i n PROD. t i n 1..T}
The shipment costs and amounts can then be indexed over links:
param c o s L ( L I N K S } > = 0:
v a r T r a n s ( L I N K S ! >= 0 :
In the objeetive, the sum o f costsover ali shipments can be written like this:
minimize ToLal_Cost:
sum ( < i . j ) i n L I N K S } c o s t ( i . j | * Trans(i.j|:
Notice that when dummy Índices run over a set o f pairs like L I N K S . they must be defined
in a pair like < i . j >. It would be an error to sum over ( k i n L I N K S } . The complete
nnxlel is shown in Figure 6-1, and shoukl be com par ed with Figure 3 - I a . The specifica-
tion o f the data could be the same av in Fjgure 3-1 b.
SEC7 C N 6 2 3 J B S E T S AND S L CES OF C P C C R E D P A R S 93
m i n i mi zc To L a l _ C o s L :
sum ( < i . j ) i n L I N K S } oosLli.jl * Transli.jl:
subjocL Lo Supply ( i in ORlG}:
sum ( j i n DEST} T r a n s l i . j l = supplylil:
s u b j o c L L o Demand ( j i n DE571'} :
sum ( i i n O R I G } T r a n s l i . j l = demandl j l :
set L I N K S dimen 2:
to indicate that the data must consist o f members o f "dimension*' t w o — that is. pairs.
Better yet, w e can say that L I N K S is a subset o f the set o f ali pairs from O R I G and
DEST:
SOL L I N K S w i t h i n (ORlG.DESr}:
This has the advantage o f making the n n x l e f s intent clcarer: h a b o helps catch errors in
the data. The subsequent decbrations o f parameter c o s t , variable T r a n s , and the
objective funetion remain the same as they are in Figure 6-1. But the components
c o s t [ i , j 1 and T r a n s t i . j ] wfll now be defined only for those pairs given in the
data as members o f L I N K S , and the expression
I l o w are the constraints written? In the original transportation nnxlel, the supply limit
constraint was:
s u b j e c L Lo S u p p l y ( i inORlG}:
sum ( j i n D i í S r } T r a n s ( i . j ) = supplylil:
What w e want t o say is that for each origin i , the sum shoukl be over ali destinaiions j
such that { i . j > is an alknved link. This statement can be transcribed directly t o A M P L ,
by adding a condi!ion t o the indexing expressk>n afler sum:
s u b j e c L Lo S u p p l y ( i i n O R I G } :
sum ( j i n DüSV: < i . j j in LINKS} Transli.jl = supplylil:
Rather than requiring this somewhat awkward form, however, A M P L krts us d r o p the j
i n D E S T from the indexing expression t o produce the f o l l o w i n g more concise constraint:
s u b j e c t Lo S u p p l y ( i i n O R I G } :
sum ( < i . j J i n L I N K S } T r a n s i i . j | = supplylil:
(<i.j) in LINKS}
means something different in each o f the three p b c e s where h appears. Iti membership
can be undcrstood in terms o f a table like this:
T h e rows represem origins and the columns destinaiions. while each pair in the set is
marked by an x . A table f o r { O R I G , D E S T } w o u l d be complete )y filled in with x * s .
while the tabkr shown depicti { L I N K S } for the " s p a r s e " subset o f pairs defined by the
data in Figure 6-2b.
A t a point where i and j are not cunently defined. such ai in the o b j e c t i v e
minimize ToLal_CosL:
sum ( < i . j ) i n L I N K S } costli.jl * Trans[i.jJ;
SECT CN6.2 3JBSETS AND SL CCS OF CFC€FED P A R S 95
minimize ToLal_CosL:
sum ( < i . j ) in LINKS} cosLli.jl * Transli.jl:
s u b j o c L Lo S u p p l y ( i i n ORIG}:
sum ( ( i , jJ i n L I N K S } Transli.jl = supplylij:
s u b j o c L Lo Demand ( j i n DKSr}:
sum ( ( i , j J i n L I N K S } Transli.jl = demand[jl:
p a r a m : DBST: demarxi :=
FRA 900 OKT 12 00 LAN 600 WIN 400
SVL 17 00 FRK 1100 LAF 1000 ;
param: LINKS: cosL : =
OARY DKT 14 OARY LAN 1 1 OARY STL 16 GARY LAF 8
CLKV FRA 27 CLKV Dlíl' 9 CLKV LAN 12 CLKV WIN 9
CLKV SVL 26 CLKV LAF 17
the indexing expression { { i , j > i n L I N K S } represents ali the pairs in this table. But at
a point where i has already been defined. such ai in the S u p p l y constraint
s u b j o c L Lo S u p p l y ( i i n O R I G } :
sum ( < i . j ) i n L l N K g } T r a n s l i . j l = supplydl:
the expressk>n { { i . j > i n L I N K S > is associated with just the r o w o f the table oorre-
sponding t o i . Y o u can think o f it as taking a one-dimensional " s l i c e ' ' through the tabkr
in the r o w corrciponding to the already-defined first component. Although in this case
the first component fc a prevk>usly defined dummy index. the same convention applies
when the first component is any expression thai can be evaluaied t o a valid set object: w ?
could write
s u b j o c L Lo Dcmarxi ( j i n D E S T } :
sum ( ( i . j J i n L I N K S } T r a n s l i . j j = dcmandljl:
lhe expression { { i . j } i n L I N K S ) seleets pairs from lhe column o f lhe table corre-
sponding t o j . Pairs in the third column o f the table could be specified by { { i . • LAN •}
in LINKS).
In the objective, c o s t and T r a n s are written with three subscripts, and the total cost is
determined by summing over ali triples:
minimize Total_CosL:
sum ( i i n O R I G . j i n DEST. p i n PROD}
cosLli.j.pl * Transli.j.pl:
T h e indexing expressions are the same as before, except that they list three sets instead o f
two. A n indexing expression that listed k sets w\>uld similarly denote a set o f k-tuples.
I f instead w e d e f i n e L I N K S as w e did in Figure 6-2a. the multicommodhy declara-
tions c o m e out like this:
p a r a m c o s t ( L I N K S . PROD} > = 0 :
v a r T r a n s ( L I N K S . PROD} >= 0 :
minimize ToLal_CosL:
sum ( < i . j ) i n L I N K S , p in PROD} cosLli.j.pl * Transli. j.pl ;
Here we see h o w a set o f triples can be specified ai combinaiions from a set o f pairs
( L I N K S ) a n d a set o f s i n g l e members ( P R O D ) . Since c o s t and T r a n s are indexed o v e r
{ L I N K S . P R O D ) . their first t w o subscripts must c o m e from a pair in L I N K S , and their
third subscript from a m e m b e r o f PROD. S e t s o f longer tuples can be built up in an analo-
gous w a y .
SECT CN 6 3 S E T S O F LCW5ER TUPLES 97
s e t ROUTKS w i t h i n ( O R I G . DIÍST. P R O D } :
p a r a m c o s t (ROUTKS} >= 0:
v a r T r a n s (ROUTES} >• = 0:
and in the objective, the total cost is a sum o v e r ali triplos in this set:
minimize Total_Cost:
sum ( ( i . j . p j i n ROUTKS} costli.j.pl * Transi i. j . p l :
s u b j e c t t o S u p p l y ( i i n O R I G . p i n PROD} :
sum ( ( i . j . p j i n ROUTKS} T r a n s l i . j . p l = supplyli.pl:
s u b j e c t t o Mui t i ( i i n O R I G . j i n D E S T } :
sum ( ( i . j . p j i n ROUTES} T r a n s l i . j . p l <= limitli.jl:
s u b j e c t to Siipply_Al 1 ( i in ORIG}:
sum ( j i n D E S r . p i n PROD: < i . j . p j in ROírrES}
T r a n s l i . j . p l <= s u p p l y _ a l l l i | :
s u b j e c t Lo S u p p l y _ A l l ( i i n O R I G } :
sum ( ( i . j * p j i n ROUTSS} T r a n s l i . j . p l <= s u p p l y _ a l 1 l i 1:
In the first ease. A M P L explichly gencrates the set { j i n DEST. p i n PROD) and
eheeks for membership o f { i , j . p ) in R O U T E S , while in the second case it is able t o
use a more efficient approach t o finding ali { i , j , p ) f r o m R O U T E S that have a given i .
In our small examples this may not seem criticai, but f o r problems o f realistic size the
slk:e version may be the only one that can be processed in a re&onable ami>unt o f time
and space.
ORIG c r o s s DBST
s e t ROUTES d i m e n 3;
expressions for PROD and L I N K S give the sets o f ali objeets p and pairs { i . j J such
thai there is some member { i . j . p } in ROUTES.
A s with simple sets, membership in a compound set may be restricted by a k>gical
condition at the end of an indexing expression. For example. the multicommodky trans-
ponation modcl could define
so that DEMAND conta ins only those pairs { j . p ) with positive demand for pcoduct p at
destination j . As another example. suppose that we also wantcd to nnxlel transfers of the
pnxlucts from one origin to another. We could simply define
s e t TRANSI' = (ORlG.ORlG}:
to specify the set o f ali pairs o f members from ORIG. But this set would include pairs
like { ' P I T T ' . ' P I T T ' >: to specify the set of ali pairs o f difjtreni members from
ORIG. a condition must be added:
This is another case where t w o dilTerent dummy Índices, i l and i 2 , need k> be defined
to run over the same set: the condition selects those pairs where i 1 is not equal to i 2.
I f a set is ordered. the condition whhin an indexing expression can also refer to the
ordering. W e could declare
s e t ORlG o r d e r e d :
s e t TRANSI' = ( i l i n ORlG. i 2 i n ORIG: o r d < i l J < ord(i2j}:
t o define a "triangular" set o f pairs from O R I G that does not contain any pair and hs
reverse. For example, T R A N S F would contain ehher o f the pairs { • P I T T ' . 'CLEV'>
or { ' C L E V " . • P I T T ' ) , depending on which carne first in ORIG, but it would not con-
tain both.
Sets o f numbers can be treatcd in a similar way, since they are naturally ordered.
Suppose that w e want to accommixlate inventories o f ditíerent ages in the multiperiod
pnxluction nnxlel of Fjgure 4*4. by declaring:
s e t PttDD: * products
param T > 0; * number o£ w e e k s
param A > 0: i maximum a g e o£ i n v e n t o r y
var Inv (PROD. O . . T . O . . A } >= 0: * t o n s i n v e n t o r iod
IXrpending on how initial inventories are handlcd. we might have to include a constraint
that no inventory in period t can be more than t weeks old:
s u b j e c t t o Too_01d
( p i n PttDD. t i n 1. , T . a in 1..A: a > t}: Invlp. t.al = 0:
s u b j e c t t o Too_01d
( p i n PROD. t i n 1 . . T . a in t + l . . A } : Invlp.t.al = 0:
100 OOWFCXWD SETS AND NCCX NQ W T E R 6
M L PROü:
s e L ARKA (PROD} ;
This says that for each member p o f PROD, there is to be a set AREIA [ p ] : its members
will denote the market arcas in which product p is sold.
T h e market demands. expected sales revenues and amounts to be sokl should be
indexed over arcas as wxrll as products and wxreks:
In the declaraiions for r w i r k e t and x e v e n u e , wxr define only the dummy index p that is
needed to specify the set AREIA [ p ] , but for the S e l l variables wxr need to define ali the
dummy Índices, so that they can be used to specify the upper bound r i a r k e t [ p . a . t j .
This is another example in which an index defined by one phrase o f an indexing expres-
sion is used by a subsequent phrase: for each p from the set PROD, a runs over a dif ferem
set AREIA [ p ] .
In the objective, the expression r e v e n u e l p . t ) • Selltp. t] from Figure 4-4
must be repbced by a sum o f revenues over ali areas for pnxluct p :
maximize T o t a l . P r o í i t :
sum ( p i n PROD. t i n 1 . . T }
(sum ( a i n ARKAl pl } r e v e n u e l p . a . t j * S e l l l p . a . t l -
p r o d e o s t ( p l *Make l p . t l - i n v e o s t lp 1 4 I i r ; l p . t l J:
s u b j e c L t o B a l a n c e ( p i n PROD. t i n 1 . . T } :
Hakelp. t j + l n v l p . t - 1 1
= sum ( a i n A R I i A l p l } S e l l l p . a . t l + I n v l p . t J :
SECT CN 6 5 NC€XEDOCLLECTC**SOFSETS 101
subject t o Time ( t in 1 . . T } :
sum ( p i n PROD} <l/ratelpJJ * Makelp.tl <=availlt|:
4 T o t a l o í h o u r s usod b y a l i p r o d u c t s
< may n o t e x c o c d h o u r s a v a i l a b l e . i n e a c h woek
4 T o n s p r o d u c o d and t a k e n i r e m i n v e n t o r y
< must e q u a l t o n s s o l d and p u t i n t o i n v e n t o r y
s e t PttDD : = hands c o i l s :
s e t ARKA l b a n d s l : = e a s t n o r t h :
set ARKAlcoilsl := oast west export :
The parameters r e v e n u e and r n a r k e t are now indexed over three sets. so their data
values are specified in a series o f tables. Since the indexing is o v e r a different set
102 OOWFCXWD SETS AND N C € X NQ CHífTÇRÔ
pa ram T := 4:
s « t PttDD : = bands c o i l s :
s o t A RH A l b a n d s | : = « a s t n o r L h :
set ARKA[coilsl : = « a s t wcsL cxporL :
param r c / e n u c : =
[bands. * , * 1 : 1 2 3 4
oasL 25.0 26.0 27.0 27.0
norLh 26.S 27. S 2 8.0 28.5
l coils.*.*1: 1 2 3 4 :=
oasL 30 35 37 39
wcsL 29 32 33 35
cxporL 25 25 25 28 ;
,ram markoL :=
[bands. * . * 1 : 1 2 3 4 :
casL 2 000 2000 1500 2000
norLh 4 000 4000 2500 4500
l coils.*.*1: 1 2 3 4 :
casL 1000 800 1000 1100
wcsL 2 000 1200 2000 2300
cxporL 1000 500 500 800 :
Figure 6-4: Data for mui ti period produetion with indexed sets < s t e e l T 3 . d a t ) .
AREIA [ p ] for each pnxluct p . the values are most eonveniently arranged ai one table f o r
each product, ai shown in Fjgure 6-4. (Chapter 9 explains the general rukrs behind this
arrangement.)
W e could instcad have written this nnxlel with a set PRODÀREA o f pairs, such that
product p will be sold in area a if and only if { p . a } is a member o f PRODÀREA. Our
formulation in terms o f PROD and AREIA [ p l seems preferable. however, because it
cmphast/c% the hierarchical rebtk>nship betwaen produets and arcas. Although the nnxlel
must refer in many places *> the set o f ali areai selling one product. h never refers to the
set o f ali produets sokl inone area.
A s a contrasting example. can consider how the mukicommodity uansponation
nnxlel might use indexed coDections o f sets As shown in Figure 6-5, for each product
we define a set o f origins where that pnxluct is supplied, a set o f destinaiions where the
product is demanded. and a set o f links that represent possible shipments o f the product:
SECT CN 6 5 NC€XEDOCLLECTC**SOFSETS 103
p a r a m s u p p l y ( p i n PROD, o r i g l p l } >= 0 ; * a v a i l a b l e a t o r i g i n s
p a r a m demand ( p i n PROD, d e s t [pl } >= 0 ; * r e q u i r e d a t d e s t i n a t i o n s
c h o c k ( p i n P R O D } : sum ( i i n o r i g l p l } supplylp.il
= sum ( j i n d e s t l p l } demand l p . j j ;
minimize Total_Cost:
sum ( p i n PROD. < i . j ) in linkc(p|} costlp.i.jl * T r a n s l p . i . j| :
s u b j e c t t o S u p p l y ( p i n PROD. i i n origlpl}:
sum ( j i n d e s t l p l } T r a n s l p . i . j l = supplylp.il:
s u b j e c t t o Demand ( p i n PROD. j i n d e s t l p l } :
sum ( i i n o r i g l p l } T r a n s l p . i . j l = demand l p . j J •
s u b j e c t t o Mui t i ( i i n O R I G . j i n D E S T } :
sum ( p i n PROD: < i . j ) i n l i n k c ( p | } T r a n s l p . i . j l <= limitli.jj:
s e t o r i g (PROD} w i t h i n ORIG:
s e t d e s t (PROD} w i t h i n DESr:
s e t l i n k s ( p i n PttDD} = o r i g l p l cross destlpl:
represem the subset o f origins that supply at least one product, and the subset o f origins
that supply ali produets.
T h e hierarchical relationship based on produets that was observed in Figure 6-3 is
seen in most o f Figure 6 - 5 av w d l . The nnxlel repeaiedly deals with the sets o f ali ori-
gins, destinatk>ns. and links associated with a particular product. The only exception
comes in the lavt constraint, where the summatk>n must be over ali produetv shipped via a
particular link:
104 OOWFCXWD SETS AND NC€X NQ CHífTÇRÔ
s u b j o c L t o M u l t i ( i i n ORIG. j i n D l í S r } :
sum ( p i n PROD: < i . j ) i n l i n k s [ p | > T r a n s ( p . i . j l <= limit(i. j|;
Excrcises
6 - 1 . Rcturn to the produetian aixl Iransportelkin model of Figures «4-6 and 4-7. t>«ng the
d i s p l a y cemimand. Icigether with írxlcune expiesskins as dcmcmslraled in Scctian 6 4 . you can
determine th: mcmhershipof a variety of ccmipounJ sets; for exampk:. yau can use
t o diow the set o f ali comhíiulkins of products xixi destirulkins where th: demorei is greater thin
500.
(a) Use d i . c p l a y to determine the membership of the folkiwirç; *ets. which depend only on the
d*a:
- Ali cambinalianx of crigins and products fer which the produetian rate is gnrater (han 150 tone
per kiur.
- Ali comhíiulkins of origins, destmations and products fer which there is a shippirçg cxrsl o f £
$10 per (cm.
- Ali camhiiulkins of origins and deslinaticms for which the shippiiç ccrsl o f coils is £ $10 per
ton.
- Ali camhiiulkins o f origins and products fer which the produ^kin ccrst per hour is less ihin
$3(1000.
- Ali ccmihinaticms of origins. destmadcmsand products for which the Iransportelkin ccrst is more
than 15^ o f lhe produclkin ccrst
- Ali ccmihinaticms of origins. dcstmafccmsand products for which the Iransportelkin ccrsl is more
than 15^ but less than 25% o f lhe produetiem ccrst
<b) Use d i s o l a y Io determine lhe membership of lhe foDawing sets. which depend cm lhe apé
mal sohilicm as well ason the date:
- Ali comhiiulkins of origins and products fer which theie is produetiem of al basl 1000 Icins.
- Ali ccmíbinaticms of origins, deslinaticms anJ products for which then? is a nem/oro amciunt
shipped.
- Ali comhiiulkins of origins and products fer which mofe than 10 friurs an: usedin produetiem.
- Ali ccmíbinaticms o f origins aixJ products surh thai lhe product occaunts for more than 25?r o f
lhe haurs available al the origin.
SECT CN 6 5 NC€XEDOCLLECTC**SOFSETS 105
- Ali cambinaftians o f origins aixl produets surh that the tolal amount of the producl shipped
from the <rigin is at least 1000 lons.
6 - 2 . This exercise lesembles the previaus one. but asks about the ofdevcd juir version o f the
t£insp<rtation model i n f i g u r e ó - 2 .
(a) Use d i s p l a y aixl indexing expie^sk» ns to determine the memfaership of the folkiwirç; sets:
- Oricin destination links that hive a transportakm cost l e « thm 510 per tem.
- IXrstinilkins that can be serwd by G>\RY.
- Origins that can serve FRK.
- lánks that are used for transportUkinin the oplimal solution.
- lánks th A are used for transportation from CLKV in the optimal solution.
- IXrstinilkins (o which the fcitil cost o f shippirçg, from ali crigím.cxcccdt $20.000.
<b) Use tfic d i s p l a y command aixl the sscLof operator «o determine the membership o f the foi
lowirçg sets:
- IXrstinilkins that hive a shippmg cost o f more thin 20 from anv origin.
- Ali destination <rigin juirs ( j » i ) surh that the hnk from i Io j is used in the optimal sohi*
tion.
6 - 3 . Use d i r o l a y and appropmte set expressions lo determine the membership of the folkiwirç;
sds from the mui li periad produetion model o f Figures 6-3 arxl 6-4:
- Ali market are as servcdwâh any of the prodiKts.
- Ali combinjíkins of prodiKts. areas and ueeks sudi thit the amount actually sold m the optimal
solution cquals the maximum thit can be sold.
- Ali combinaiions of produets and weeks such thit the fctlil sold m ali anras is greater than or
equal fci 6000 tons.
d i a p l a y S;
diaplay { ( a , b , â , d , a , f ) í n Q: (a,b,e,d,«, f) inS);
The two expressions in these commands represent the a m e set. but do you get the same speed o f
response from AMPL? Hxplun the cause o f the diffciencc.
<b) Predict the resuk of the command d i s p l a y 0-
6 - 5 . This exercite asks you Io reformula*? the dict model of Figure 2-1 in a variety o f ways, usirçg
oompound sets.
(a) Reformula*; the dict model so that * uses adcclaraáon
Co define, f o r each nutrient i . C h e sei FM ( i ] o f ali foods ChaC can supplychic nuCrímt
Co define. for each food j . Che set NF [ j J of ali nutriente supplied by ChiC f o o d . livpUin why you
fmd Chi< formuljtian m a e <* lew natural anJ can\\.~nienC ChanChe o n e in<b>.
6-6. Re read the suggesCkiro in Scction 6 J , xixi complete Ch: folkiwirç; refcrmuLcktm of the
mukjcx«nmodiCy CranspcirtUkin mcdel:
( a ) Use a xubcet L I N K S o f ( r i g i n descmatian pairs.
6 - 7 . Carrv Chrough the fallawing twasuggestians finam Sectían 6 A h v cnhancemenfe t o the mui ti
cammodity CraiwpciriUkin problem of Figure 1.
<a> Ackl adecUratxin
anJ index the varnbles o v e r ( O R I G . DKM>\?JD}. so ChaC variables an: defined anly where they
might be nevded t o meet denuLixl. Make ali o f the nearctary chu^gcs in t h : ivst of t h : n u d e l Io use
this sei.
6-8. RefcrmubCe the model from Exercia? 3 3<b) s o ChaC ic uses a set L I N K l of alkiwable planl
miII shipmenl pairs. and a set L 1*1X2 o f alkiwable mil 1 farto ry shipmenl pairs.
6-9. As chiirman o f the program commiCIcc for a prestigious scientific confeience. you musc
assign submiCled papers lei valunfcvr referees. T o d o so in the mcnC ef f e d i se w a y . vou can fermu •
l * e an L P model along Che lines o f the x^ignmenC model discuwcd in CTiapCer buC w ü h a few
extra Cwists.
AfCer looking thKHÇhthe jupersand Che IwCof i v f e i e e s , y o u can cxmpile the fallawing dita:
oat Paparfl;
aat Raíaraao;
oat Categorias;
aat PapatrKinl w i t h i n { P a p * r f l , C a t a g o i : i * f l ) ;
oat Wi 11 i n q w i t h i n {Râ2*tr<aàfi,Catagoi:i<afl) ;
H i e conlerts of the first t w o set< an: self evidenl. while the third set coniains subject categories
inCo which jupers may b c c l a ^ i f i e d H i e set P a p c r X i n d c a n t i i m a pair ( p . c j if juper p tilh
SECT C N 6 5 NC€XEDOCLLECTC**SOFSETS 107
( d ) F n a l l y , you musldefine lhe folkiwirç; jurameters lha* inJicale how much w a f c i s t o be dane:
7
Parameters and Expressions
109
110 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
param T;
A l any point after this declaration. T c a n be used t o refer to a nume rica 1 value.
M o r e often. the name in a parameter declaration t% f o l l o w e d by an indexing expres-
sion:
param a v a i l ( 1 . , T > ;
param demand ( D E S T . P R O D } ;
p a r a m r c v e n u e ( p i n PROD. A R K A l p l , 1. . T } :
One parameter is defined f o f each member o f the set specified by the indexing expres-
sion. Thus a parameter ti uniquely determined by hs name and its associated set m e m -
ber: throughout the rest o f the nnxlel. you would refer to this parameter by wrhing the
name and brackcted " s u b s c r i p t s " :
availli 1
demandl j . p l
r o v c n u e lp. a. t l
seL ORIG:
s e t DEST:
param c o s t ( O R l O , DEST} :
s e t ORIG:
s e t DEST:
s e t L I W X S w i t h i n ( O R I G . DE5?r } :
param c o s L (LINKS};
then c o s t I i . j ) e x i s t i only for those i from O R I G and j from D E S T such that { i . j >
is a member o f L I N K S . In t h i s c a i e . y o u can t h i n k o f c o s t ai b e i n g a " s p a r s e " matrix.
Similar c o m m c n t i apply t o parameters indexed over triplcs and longer tuples. w h i c h
resemble arrays o f higher dimension in programming languages.
t o the right: you can mix them as you like, but your n n x l e k w i l l be easier t o read and
understand if you are consistem in yourchoices.
Another w a y t o buikl arithmetic expressions is by applying funetions t o other expres-
sions. A funetion refere nce consists o f a nanie followcxl by a parcnthcsi/ed argument or
comma-scparated list o f arguments: an arithmetic argument can be any arithmetic expres-
sion. Ilere are a f e w examples, which compute the minimum, absoluie value. and square
rix>t o f the ir arguments, respectively:
min<T.20j
abs(sum ( i i n ORIG} s u p p l y l i l - sum ( j in DEST} dcnvarxil j l J
sqrt<(Lanlj|-Lanlkjj
Tablc 7 - 2 lisfc the built-in arithmetic funetions that are typically found in nxxlels. Except
for m i n and n a x , the names o f any o f these funetions may be redefined. but their original
meanings will b e c o m e inaccessible. K>r example. a nxxlel may declare a parameter
named t a n av in the lavt e x a m p l e above, but then it cannot a b o refer t o the funetion
tan.
T h e set funetions cai d and o r d . which were described in Chapter 5, also produce an
arithmetic resuh. In addition. A M PI. provkles several " r o u n d i n g " funetions (Section
11.3) and a variety o f random-number funetions (Section 7/> below). A mechanism f o r
" i m p o r t i n g " funetions defined by your o w n programs is described in Appendix A 2 2 .
SECT-ON 7 2 A R T W E T C EXWESSO NS 1 13
Finally, lhe indexed operators such ai I and U from algebraic notaiion are gcncrali/cd
in A M P L by expressions for iterating operatk>ns over seis. In particular, m o s i brge-scale
linear programming nuxlels contain iteraied summations:
sum ( p i n PROD. t i n 1 . . T }
( s o n (a i n A R B A l p l } r e v o n u e lp . a . t | * S c l l l p . a . t l -
prodcostlpl*Mafce lp.t| - i n v e o s t [ p J * I n v l p . t i ) :
T h e outer sum applies t o lhe entire parenthesi/ed expression foDowing it, while the inner
sum a p p l i e s o n l y t o the term r e v e n u e l p . a . t J • S e l l t p . a . t J.
114 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
= equal k)
0 not equal ki
< than
<= LEW th JLJI equal t o
> gn.-afc.-T thin
>= grcjUcr thin or equal lei
T h e result o f a comparison is either " t r u e " o r 4 ' f a l s e " . Thus T > 1 is true if the parame-
ter T hai a vahie greaier than I, and is false olhe nvise: and
is only true if T lies in the interval |0,10), while the f o l l o w i n g from Section 5.5,
1 in MAXRKQ o r n. m i n l i j > 0
is interpretei] a*
is irue if and only if ai least one origin has a deroand greater lhan 10, while
s u b j e c t Lo B a l a n c e O ( p i n PttDD}:
Make l p . f i r s t (WIítLKSJ 1 «• i n v O l p l
= S e l l [ p . f i r s L (WEIÍXSJ 1 + i n v [ p . f i r s t (WBKKS) 1 :
s u b j e c L Lo B a l a n c e ( p i n PROD. t i n WKKKS} !
Hakelp. t| +
< i f t = f irst<WI£I£XSJ Lhen i n v O l p l c i s o i n v l p . p r e v <LJ | J
= Selllp.Ll + invlp. t|:
This forro oororounk-ates the inventory balance constraints more concisely and directly
than t w o separakr declarations.
T h e general form o f a conditional expression is
if a Lhen b e l s e c
116 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
where a isa logical expression. l f « evaluates *> tme. lhe oonditiomd expression takes the
value o f b: if it is false, lhe expression takes the value o f c. If c i&zero, the e l s e c pon
can be dxopped. Most o f t e n b and c arcarithmcticcxprcssions. but they can also be string
o f set expressions. so long a* both are cxpressions o f the same kind. Bccause t h e n and
e l s e have k>wer precedence than any other operators. a c\>nditional expressk>n nccds to
be parcnthesi/ed (as in the example above) unless it occurs at the end o f a statement
A M P L also h^v an i £ - t h e n - e l s e for use in programming: like the conditk>nal state-
ments in many programming languages. it executes one or another block o f statcmcnts
depending on the tmth o f some logical expression. W e describe it whh other A M P L pro-
gramming features in Chapter 13. The i £ - t h e n - e l s e that we have described here is
not a statement, but rather an expression whose value is conditionally determined. It
therefore belongs inside a declaration. in a pbce where an expression would normally be
evaluated.
you instmct A M P L *> reject your data if you inadvenently set T k> I:
error p r o c e s s i n g param T :
f a i 1 od c h o c k : param T = 1
i s n o t > 1:
or to 2.5:
error p r o c e s s i n g param T :
í a i 1 od c h o c k : param T = 2 . S
i s n o t an i n t e g e r :
A M P L will not send your problem instance to a solver as long as any errors o f this kind
remain.
In the dccbration o f an indexed colkrction o f parameters. a sim pie restriction such as
integer or > = 0 applies *> every paramekrr defined. Our examples often use this
option to specify that vectors and arrays are nonnegative:
If you include dummy índices in the indexing expression. however, you can use them to
specify a dilTerent resiriction for each para meter:
param c u m u l a t i v o m a r k e t ( p i n PROD. t i n 1 . . T }
>= c u m u l a t i v o market lp. t - U ; it BRROR
param c u m u l a t i v o m a r k e t ( p i n PROD. t i n 1 . . T }
>= i í t = 1 t h e n 0 e l s e cumulativo market lp. t-11:
p a r a m c u m u l a t i v o m a r k e t ( p i n PROD. t i n 1 . . T }
>= i f t > 1 then c u m u l a t i v e market lp. t - 1 | :
c h e c k ( p i n PROD} :
sum ( i i n O R l G } s u p p l y l i . p l = sum (j in Dl£Sr} demarxi l j . p l :
l l e r e the restriction is tested once f o r each member p o f PROD. I f the check f a i k for any
member. A M P L prints an error message and rejects ali o f the daia.
Y o u can think o f the c h e c k staiement as s p e c i f y i n g a kind o f constraint. but only on
the data. T h e restrictk>n clause is a logical exprcssion. which m a y use any previously
118 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
defined sets and parameters as wcll a s d u m m y índices defined in lhe st*tement's indexing
expression. After lhe data values have been read, lhe logical expression must evaluaie to
true: if an indexing expression has been specified, the k>gical expression isevaluaied sep-
araiely for each assignment o f set members k> the dummy Índices, and must be true for
each.
W e strongly recommend the use o f restriction phra*esand c h e c k statements to vali-
date a nnxlcl's data. These features will help you to catch daia errors at an early stage,
when they are easy to fix. Daia errors not caught will, at best, cause errors in the genera-
t i o n o f the variables and constraints. solhai you will gel some kind o f error message from
AMPL. I n other caies, data errors lead to the generation o f an incorrect linear program. 1 f
you are fortunate, the incorrect L P will have a meaningless optimal solutk>n, so that —
possibly after a good deal o f elTort — you will be able to work backward to find the error
in the data. A t \v\>rst. the incorrect L P will have a pbusible solutk>n, and the error will g o
undeiecied.
because pnxluction rates given in tons per hour, while the coelllcient o f J í a k e [ p ]
had to be in hours per k>n. A n y parameter expression may be used in the constraints and
objective. but the expressk>ns are best kept simple. When more complex expressions are
needed. the nnxlel is usually casier to understand if new, computed parameters are
defined in terms o f the daia parameters.
T h e dcclaratk>n o f a computed parameter an aüsignment phrase, which resembles
the restrictk>n phrase described in the previoussectk>n except for the use o f an = opor ator
to indicatc that the parameter is being set e^ual to a certain expression, rather than merely
being restricted by an inequalhy. As a first example, suppose that the data vahies pro-
vided to the multicommixlity transponation nnxlel o f Figure 4-1 consist o f the total
demand for each pnxluct, together with each dcstination's share o f demand. The destina-
tions' shares are percentages betwxren zero and 100, but their sum over ali destinations
might not exactly equal 100%, because o f rounding and approximation. Thus we declare
data parameters to represem the shares, and a computcd parameter equal to their sum:
W e can then declare a data parameter to represem total demands, and a computed param-
eter that equals demand at each destination:
SECT-ON 7 5 COWUTED P / « WETERS 1 19
The division by t o t _ s h acts ai a correction factor for a sum noi equal to 100%. Oncvr
d e m a n d h^i been defined in this w a y , the nxxlel can use it as in Figure 4-1:
This alternative makesthe nxxlel a liiile shorier, but the computalion o f the demand and
the strueture o f the constraint are both harder to f o l b w .
A s another example. consider a scenario for the multiperkxl pnxluction nnxlel < Figure
4-4) in which minimum inventories are computed. Specifically, suppose that the inven-
tory o f product p for week t must be ai least a certain fraction o f m a r k e t l p . t + 1 ] , the
maximum that can be sold in the following wxrek. W e thus use the following declaralions
for the data to be supplied:
param í r a c > 0:
m i n i n v was d o f i n o d i n Lhe m o d e l
contoxt: param » > mininv « < := bands 2 3 000
H o w e v e r , there isan alternative way in which you can define an initial value f o r a param-
eter but allow it to be changed laier.
l f y o u define a parameier using the d e f a u l t operator in place o f =, then the parame-
ter is inhialized ralher than defined. Its value is taken from the value o f the expressk>n to
the right o f the d e f a u l t operator, but does not change if the expression's value later
changes. Initial values can be overrklden by data statements. and they also may be
changed by subsequent assignment statements. Jht% feaiure is mixst useful for wrhing
A M P L scripts thai updaie certain vahies repeatedly, as shown in Sectk>n 132.
120 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
I f you define a parameter using the operator d e f a u l t in place o f =, then you can
specify values in daia statements to over ride the ones that would other wise be computed.
For instancc. by declaring
param m i n i n v ( p i n PttDD. t i n 0 . . T }
d e f a u l t f r a c * m a r k e t [ p . t*-l J:
you can allow a f e w cxceptk>nal minimum inventories to be specificd ai part o f the data
for the model. either in a list:
param m i n i n v :=
hands 2 3000
coils 2 2 000
coils 3 2 000
or in a table:
param market: 1 2 3 4
bands . 3000
coils . 2 000 2000
The values o f m i n i n v for wxrek 0 are set explicitly to the initial inventories. while the
values for each subsequent wxrek t are defined in terms o f the previous \v\rek's values.
A M P L permitsany " r e e u r s i v e " definitionof thiskind, but will signal an error if itdeiects
a circular reference that causes a paramctcr's value to depend directly or indirectly on
itself.
Y o u can use the phrases defined in this scction together with the restriction phrases o f
the prevk>us sectk>n. k> funher check the values that are computed. H>r example the dec-
laration
param a v a i l ( 5 T A Ú B } =
max(?tormal ( a v a i l m e a n . avai1_varia nce). Oj :
For each stage s , t h i s g i v e s a v a i l I s ] a dilTerent random value from the same random
distribution. T o s p e c i f y stage-dependent random distributions. you would add indexing
t o the mean and variancc parameters as w e l l :
param a v a i l ( s i n STAÚB} =
m a x ( ? t o r m a l ( a v a i l m e a n [ s l , a v a i l _ v a r i a n c e [ s 1J . Oj :
T h e rrnix {... , 0 } expression is included t o handle the rare c a i e in w h i c h the normal distri-
bution with a positive mean returns a negative value.
M o r e general w a y s o f randomly oomputing parameters arise naturally from the pre-
ceding section's examples. In the muhicommodity transportatk>n problem, you can
d e f i n e random shares o f demand:
p a r a m s h a r e ( D E S r } = U n i f o r m ( 0 .100J :
p a r a m t o t _ s h = sum ( j i n D E S r } s h a r e l j J ;
A recursive definition o f this kind providesa way o f generating simple random processe»
over time.
AII o f the A M P L random funetions are hascd on a uni form random number generator
with a very long perkxl. When you stan AMPI. o r g i v e a r e s e t command. however, the
generator is reset and the " r a n d o m " values are the same as before. You can request d i f -
ferent vahies by changing the A M P L optk>n r a n d s e e d to some integer other than hs
default value o f I: the command for this purpose is
option randseod n:
where n is some integer vahie. Nonzero values g i v e sequences that repeat each time
A M P L is reset. A value o f 0 requests AMPL to pick a seed bated on the current value o f
the system clock. resulting ( f o r practical purposes) in a different seed at each reset.
A M P L ' s r e s e t d a t a command, when applied t o a randomly oomputed parameter,
also causes a new sample o f random values to be deter mi ned. The use o f this command
isdiscussed in Section 11J.
param o r e m o t e ( PROD, 1. . T * 1} b i n a r y :
param m a r k c t (PWDD, 1 . . T * 1 } >= 0 ;
SECT-ON 7 8 SWEaCPWWETERS 123
The binary parameters p r o r > o t e [ p . t ) areO when there ti no promotion. and I when
there is a promotion. Thus \V>Í can define the minimum-inventory parameters by use o f
an i £ - t h e n - e 1 s e expression as foi lows:
param m i n i n v ( p i n PWDD. t i n 0 . . T } =
< i f p r o m o t o [ p . t | = 1 Lhen f r _ p r o e l s e fr_regj
* market(p. t«-lj;
param m i n i nv ( p i n PWDD. t i n 0 . . T } =
< i f p r o m o L e [ p . t l Lhen f r _ p r o e l s e f r _ r e g j * m a r k e t l p . L«-ll :
seL IWTKR:
s e L IWTKR : = a b c d e f g ;
param e n L r := a ;
param e x i L := g ;
These parameters are subsequently used in dctlning the objective and constraints: the
complete nnxlel & dcvek>ped in Section 15.2.
124 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
Another use o f symbolic parameters t% t o as&ociste descriptive strings with set mem-
bers. Consider f o r example the set o f " o r i g i n s " in the transponation nnxlel o f Figure
3 - l a . W h e n w e introduced this set at the b e g i n n i n g o f Chapter 3, w e d e s c r i b e d e a c h o r i g -
inating city by means o f a 4-character string and a longer descriptive string. T h e shoit
strings became the members o f the A M P L set O R I G . w h i l e the longer strings played n o
further role. T o make both available, w e could declare
s e t 0R1Q:
p a r a m o r i g name ( O R l G > symbolic:
p a r a m s u p p l y ( O R I G } >= 0:
Since the k>ng strings d o not have the form o f AMP1. names. they d o nced to be quoted.
T h e y still play n o role in the nnxlel or the resulting linear program, but they can be
retrieved f o r documcntary purposes by the d i s p l a y and p r i n t í c\>mmands described
in Chapter 12.
Just ai there are arithmetic and logical operators and functions, there are A M P L string
operators and functions for working with string values. These fcatures are mostly used in
A M P L command scripts rather than in model s, s o w e defer their description t o Section
13.7.
Excrcises
7*1. Show how the mukicommodily transp<Biatian model o f Figure «i 1 « w k l be modified so «hn
it applies the folktwing restrictons lo the dati. tJ<e either a restrictian phrase in A s e t or p a r a m
dtrljLTjLtiun. e r a c h e c k sOlemenl whichevcr K appropri*?.
- No city isa memherof both ORIG j i d DESY.
- T h : number o f cüies in DttST must be gnraler Ihin the number in ORIG.
- Demand does n o t e x a x d 1000 at any one city in DEST.
- T o a i supply each producl at ali origins must eqtflú total demand f<* thit prudirt at ali des-
linMbiK.
- ToUl supply f<» ali prodiKts at ali origins must equil total demand f<* ali produc* at ali desti
ntfiont.
- T o a i supply o f ali products at an crigin must not excecd total capacity f<» ali shipmenfe from
thit crigin.
- T o a i demand f<* ali products at adestinatien mwt not exceed letal capmcày for ali shipoiefltc
to that destination.
7 - 2 . Show how f i e muléperiod produetion model of Figuve «i-4 could be mcidined so thit *
applies the foüowingrcstriclions lo the doa.
SECT-ON 7 8 SWECL C P t & W E T t P S 125
7 - 3 . The solutkins to the following exerci ses m w l v c th: use of M\ i í L h c n c l .-xj opcrafcir fc»
fcroiuUtc a constraint
(a) In th- example of the constraint B a l a n c e in Section 7.3, we used an expression beginnirçg
where the additional kins can bc bought The relevant dita vahies and dccision vaxiibk-s coukJ be
indeied over this subset:
Revise th- objective functkin ki include the purchase costs. Revise the S u p p l y constraints to » y
thit f<r each crigin and each producl total tons shipped out must equal tons o f supply from pro
duetion phis (if applicabk-) fcins purchased.
(d) IVrmuUlc the « m e model as m (cX, but with BUY_0R1G being th- set of juirs ( i . p j sudi
thit product pcan be bought at crigin i .
7 - 4 . Th rs exercise is concerned with the following sets and parameters from 1'igure 4 1:
<a> Write param dcclarations. using the = operator. to compute parameters havirçg the folkiwirç;
defini tiems:
- p r o d _ s u p p l y [ p l is th- total supply o f product pat ali crigins.
126 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7
parasr. X;
A(J\0) = i + l
A(0,;+ 1> = A( 1, j )
A(i+ 1 , / + 1> = A ( A ( i \ ; + !>,/>
parair. odd f i i n 1. . X ) -
i f i - 1 tftan 3 « l o a
rr-n [ } i n o d d r i - U « 2 . . o d i r i - l l » 2 b y 2 :
n o t %»xíflCfl (X í n 1 . . i - 1 ) } OMd o 4 d [ X ] - 0)
Once y o u ' \ e figured it out. creste a simpler arxl m o t e efficient declaration that gives a set rather
thin an a m y o f these numbers.
SECT-ON 7 8 SWECL C PWWETERS 127
(c) A ' W constas af a calkxlkin of nades, onc af which w? dcsigiuCe as Ch: " l o d " . liich
nade exccpC ch: roa! has a unique pitdectssar nade in lhe Irce, surh ChaC if you wark backward*
fiam a nade to ás pitdecessac, then Ia its pradcccssor'* prtdects«r. jmd so f<*th. you ahvays
ewntuallv reach the IXKIC. A titvcan be drawn Elo? Chi*. with the «Kit 44 the leít anJ an MiaW from
each nade Io its succeman:
We can sCan? th: structurc of a Crec in AMH. set< and parametrrs as falbws:
fl*t KOEES;
p-Ararr. Jtoot flywiolíc i n XODES;
lf you enler such daU, whaC will tnppen whcti vou try to d rs play d o p L h ?
Coftyrçht O 2003 by Robcrt Fourer, DtvkJ M . Qay .inJ l i r i a n W . KCTTÚ&\JJ\
8
Linear Programs: Variables,
Objectives and Constraints
T h e bevt-known kind o f optimizatioit nnxlel, which has served f o r ali o f our examples
s o far, t% lhe linear program. T h e variables o f a linear program take values from some
continuou* range: the objective and constraints must use only linear funetions o f the vari-
ables. Previous chapters have described these require ments informally or implicitly: here
w e will be more specific.
Linear programs are panLularly imponant because they accarately represent many
practical applications o f optimi/ation. T h e simplicity o f linear funetions makcs linear
m o d e l s easy *> formulate. interpret, and analyze. They are a l s o c a s y t o solve: if you can
express your problem a* a linear program, even in thousandsof constraints and variables,
then you can be confident o f f i n d i n g an optimal sohitionaceurately and quickly.
T h i s chapter describes h o w variables are declared, defines the expressions that A M P L
recognizes a* being linear in the variables, and gives the m i e s f o r dcclaring linear o b j e c -
tives and constraints. Much o f the material on variables, objectives and constraints is
hasic t o other A M P L m o d e l s as weD, and will be used in later chapters.
Because A M P L ti fundamentally an algebraic modeling language, this chapter concen-
trateson features forexpressing linear programs in ternfc o f algebraic objectives and con-
straints. For linear programs that have certain special stmetures, such as networks, A M P L
oITers al terna tive notations that may make m o d e l s easier t o wrhe, read and s o l v e . Such
special stnicturc% are among the l o p i e s o f Chapters 15 through 17.
8.1 Variables
T h e variables o f a linear program have much in c o m m o n whh its numerical parame-
t e r s Both are s y m b o k that stand for numbers, and that m a y be used in arithmetic expres-
sions. I^arameter values are supplied by the modeler or c o m p u i e d f r o m other values.
129
130 LNEAR F T O 3 R W S V / « A f i l £ S . C e J E C T V E S A N D OOttSTRA NTS CHífTÇR3
while the values o f variables are dctermincd by an optimi/ing algorithm (a& implcmcnted
in one o f the packagcs that w e refer t o as s o l v e rs).
Syntactically, variable declaraiions are the same as the parameter declarations defined
in Chapter 7, except thai they begin with the k e y w o r d v a r rather than p a r a m . The
meaning o f qualifying phrases within the declaration may be diíTerent, howxrver, when
these phrases are applied t o variables rather than t o parameters.
Phrases beginning with > = or < = are by far the mo&t c o m m o n in declarations o f vari-
ables f o r linear programs. T h e y have appeared in ali o f our examples, beginning with the
productk>n nnxlel o f Fjgure 1-4:
T h e values f o D o w i n g > = and < = are l o w e r and upper bounds on the variables. Because
these bounds represem a kind o f constraint, they could just as w e l l be imposed by the
constraint declaraik>ns described laier in this chapter. By placing bounds in the v a r dec-
laration instead, you may be able t o make the nnxlel shorter or d e v e r . although you will
not make the optimal solution any different or easier t o find. S o m e solvers d o treat
bounds specially in order t o speed up their algorkhms, but with A M P L ali bounds are
identified automatically, n o matter h o w they are expressed in your model.
Variable declarations may not use the compartion opera k>rs < , > or < > in qualifying
phrases. K>r linear programming h makcs n o s e n s e ii> constrain a variable t o be, say, < 3,
since it could always be chosen as 2.99999... or as close t o 3 as you like.
A n = phraie in a variable declaration g i v e s rise to a definitk>n, as in a parameter dec-
laration. Bccause a variable is being d e c b r e d , howxrver, the expression t o the right o f the
= operator may c\>ntain prevk>usly declarcd variables as w e l l a s s e t i and parameters. For
example, insteaJ o f writing the complicated objective from the multi-period pnxluction
nnxlel o f Figure 6-3 < s t e e l T 3 . m c d ) ai
SECT-0N&1 VAR/etES 131
maximize Total. P r o í i L í
sum ( p i n PROD. t i n 1 . . T }
(sum ( a i n A R B A [ p J > r e v e n u e l p . a . t j * S e l l l p . a . t ] -
p r o d r o s L Ipl "Makc l p . L| - i n v c o s L l p 1 * I n v l p . t ] J :
you c o u l d instcad define variables t o represem the total revenues. pnxluction costs. and
inventory costs:
v a r T o L a l Revenue =
sum ( p i n PROD. t i n 1 . . T }
sum ( a i n AKKA IpJ } r e v e n u e l p . a . Ll * S e l l l p . a . t l :
var ToLal_Prod_CosL =
sum ( p i n PROD. t i n 1 . . T } p r o d c o s L l p l * Makelo.Ll:
var ToLal_lnv_CosL =
sum ( p i n PROD. t i n 1 . . T } i n v c o s L [ p J * I n v l p . L l :
maximize ToLal. P r o í i L :
ToLal_Revenue - ToLal_Prod_CosL - ToLal_Inv_CosL:
I . M o d e l s that contain any such variables are integer programs. which are the topic o f
Chapter 20.
contiMle.xpj-
wvkiNtrtf
(.conskini rxpr) * wukible rtf
avail[t|
Makelp.t| + lnvlp.t-11
r=um ( p i n PROD} < 1 / r a L c l p | J * M a k e l p , t j
RUBI ( a i n A R E A [ p ] > S e l l l p . a . T J «• I n v l p . t l
T h e m o d e l ' s objeetive.
is also linear because subiraction o f a term K the addhion o f its negative. and a sum o f
sums is i t s e l f a s u m .
Various kinds o f expressk>ns are eqüivalem t o a sum o f terms o f the f o r m s a b o v e , and
are also recognized as linear by A M P L . Div&ion by an arithmetic expression is eqüiva-
lem k> muhiplication by its inverse. s o
(1/raLelpJJ * Makelp.tJ
Makelp.tJ / raLelpI
revenue l p . a , t | * Selllp.a.tl
SECT C N 8 . 2 LNEAREXWESSOUS 133
is eqüivalem to
Selllp.a.tJ * r e v e n u e l p . a . 11
then both
oras
sum ( p i n PROD. t i n 1 . . T }
(sum ( a i n A R B A l p J } r e v e n u e lp . a . t | * S e l l l p . a . t l -
p r o d c o s t l p l * Makelp.tJ - i n v c o s t l p l * X n v l p . t j j / Ljnt
Multiplication and division d&tributc over any summation to yield an eqüivalem linear
sum o f ternfc. Notice that in the fkst form, m t _ t muhiplies the entire surn { p i n
P R O D . t i n l . . T } . while in the sccond t_snt divides only the summand that follows
sum { p i n P R O D . t i n 1 . . T > , beeause the / operator has higher precedence than the
sum operator. In these exampkrs the effeet is the same. however.
Finally, an i £ - t h e n - e l s e operator produces a linear result if the expressions f o l -
lowing t h e n and e l s e are both linear and no variables appear in the logical expression
between i í and e l s e . The followmg exampkr appeared in a constraint in Scction 7 3 :
Makelj.t) •
( i í t = f irst(WKHXSJ then invOl j | e l s e I n v l j . p r c ; < t j 1J
The variables in a linear expression may not appear as the operands ii> any other opera-
tors. or in the argumente to any functions. This rukr applies to iterated operators like
max. m i n . ã b s , f o r a l l . and e x i s t s . as wvll ai * and standard numérica! functions
like s q r t , l c g . a n d c o s .
Tosummari/e. a linear expression may be any sum o f te mis in the forms
134 LNEAR F T O 3 R W S V / « A f i l £ S . C e J E C T V E S A N D OOttSTRA NTS CHífTÇR3
conaani-rxpr
var-rcf
(conxkini-expr) * (/inmr-exprj
(/inmr-r.tpr) * (rcaflci/if-exprj
(linrw txpr) / (constato r.rpr)
i f logical-rxpr Lhen Untar-rxpr e l . e e tintar- « p r
where comãuni-expr isany arithmetic expression thai conta ins no references t o variables,
and linear-expr is any other (simpler) linear expressk>n. Karcnthcses may be omhted if
the result is the same by the rules of operator precedcncvr in Table A-1. AMPL automati-
cally performs the transformations that conven any such expression to a simple sum of
linear ter nu.
8.3 Objectives
T h e declaratk>n o f an objective funetion consistsof one of the keywords m i n i m i z e
or m a x i m i z e , a name. a colon. and a linear expression in prevk>usly defined sefc,
parameters and variables. W e have seen examples such as
maximize ToLal. P r o f i L :
sum ( p i n PROD. L i n 1 . . T }
(sum ( a i n AR1£A[ pl } r e v e n u e l p . a . L| * S e l l l p . a . L j -
p r o d c o s L l p l * Make lp. Ll - i n v c o s L l p l * I n v I p . L l J :
The name of the objective plays no funher role in the m o d e l with the exceptk>n of certain
" c o l u m n w i s e " declaraiions *> be introduced in Chapters 15 and 16. Within AMPL com-
mands. the o b j e c t i v e n a m e refers to its vahie. Thus for example after solving a feasible
instance of the Figure 2-1 diet ntxlcl we couk! issue the c\>mmand
indexing expression after the objective name. In these cases, you may issue an
o b j e c t i v e command. before typing s o l v e , to indkaic which objective & to be opti-
mized.
A s a n example. recall that when trying to solve the model o f Figure 2-1 with the data
o f Fjgure 2-2. w e found that no solution could satisfy ali o f the constraints: subse-
quently increaved the sodium ( N A ) limit k> 50000 to make a fea&ible solution possible. It
is reasonable to ask: H o w much o f an increa&e in the sodium limit isreally necessary to
permh a feasible solution? H>r this purpose can introducc a new objective equal to
the total sodium in the diet:
< W e create this objective only for sodium. because w e have no rcau>n to minimize most
o f the other nutriente) W e can solve the linear program for total cost ai before. since
A M P L chooses the m o d e l ' s first objective by default:
The solver tells us the minimum c o s t and wxr can also use d i s p l a y to Kx>k ai the total
sodium. even though it's not cunently being minimi/ed:
Next wvr can use the o b j e c t i v e c\>mmand to switch the objective *> minimi/ation o f
total sodium. T h e s o l v e command then re-optimi/es with this ahernaiive objective. and
display T o t a l _ C o s t to determine the resulting cost:
ampl: aolvo;
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
1 i t o r a t i o n s . o b j o c t i v o 4BI86
W e see that sodium can be brought down by about 1800. though the cost is foreed up by
about $5.50 as a result. (llealthier diets are in general mi>re expensive. because they
force the sohition away from the one that minimizes costs.)
A s another example. here's how could experiment with different optimal solutions
for the o f l i c e aisignment problem o f Figure 3-2. First wxr solve the original problem:
136 LNEAR F T O 3 R W S V / « A f i l £ S . C e J E C T V E S A N D OOttSTRA NTS CHífTÇR3
T o keep lhe objective value ai this optimal levei w h i l e \v>í cxperimcnt. w e add a c o n -
straint that fixes the expression for the objective equal t o t h e current value. 28:
N e x t recall that c o s t t i . j J is the ranking that person i has given k> o f f i c e j , while
T r a n s I i . j J is set t o I if it's optimal t o put person i in o f f i c e j . or 0 othenvise. Thus
always equals the ranking o f person i for the o f f i c e t o which i is assigned. W e use this
expression t o declare a new objective funetion:
L o o k i n g at the new assignment. w e see that the original o b j e c t i v e is unchanged. and that
the selected individual'* siftiation is in faet improved. ahhough o f course at the expense
o f others:
SECT CN8.4 OOUSTRfcNTS 137
cosLli.jpTrans(i,j| :=
Coullard D2 41 3
Oaskin D2 3? 1
llazcn C2 4G 1
Itopp C2 S I S
iravani C l 38 2
LinoLsky C2S0 3
MchroLra D2 39 2
?Jelson C l 40 4
a n i l o w i t z M2 33 1
Tamhano C11B S
WhiLo M2 39 1
We were abkr to make this d u n g e because there a r e i e ver al optimal solutk>ns tothe origi-
nal total-ranking objective. A sol ver arbitrarily returns one of these, but by use o f a sec-
ond objective we can force it toward others.
8.4 Constfaints
Thesimplest kind of constraint declaraiion begins with the keywxwds s u b j e c t t o . a
nanie, anda colon. Even the s u b j e c t t o & optional: A M PI. assumes thai any decbra-
tion not begiiwing with a keyword is a constraint. Following the colon is an a|gebraic
descriptk>n o f the constraint. in terms o f previously defined sefc, parameters and vari-
ables. Thus in the production mixlel introduccd in Figure 1-4, have the following
constraint imposed by limited processing time:
s u b j o c L Lo T i m e :
sum ( p i n PROD} (1/raLclpjJ * Make [ p ] <= a v a i l ;
The nanie o f a constraint. like the nanie of an objective, t* not used any where else in an
algebraic nnxlel, though it figurei in alternative "columnwise" focmulations (Chapter
16) and is used in the AMPL command environment U»specify the constraint'sdual value
and other aisoc atedquanthies (Chapter 14).
Most o f the constraints in large linear programming nuxlels are defined as indexed
collectk>ns, by giving an indexing expression after the constraint namc. The constraint
T i m e , for example, isgenerali/ed in subsequent examples k> say that the production time
may not exceed the tinie avaibble in each processing stage s < Figure I -6a):
s u b j o c L Lo Time ( s i n 5TAGB}:
sum ( p i n PROD} < 1 / r a L o [ p . s 1J * Make[pl <= availlsl;
s u b j e c L Lo T i m e ( L i n l . . T } s
sum ( p i n PROD} < 1/ r a t e i p ) J * M a k e l p . t j <= a v a i l [ L ] ;
Another constraint from the latter example says that production. sales and invenxwies
must balance for each pnxluct p in each week L:
s u b j e c L Lo B a l a n c e ( p i n PROD. L i n 1 . . T } :
Makelp.t| • lnvlp.t-11 = S e l l l p . L j + I n v l p . L j :
A constraint declaration can specify any valid indexing expressk>n. which defines a set
(as expbined in Chapters 5 and 6): there is one constraint f o r each member o f this s e t
The constraint name can be subscriptcd. so that T i m e [ 1 ) or B a l a n c e [ p . t * l ] refers
t o a panicular constraint from an indexed collection.
T h e indexing expressk>n in a constraint declaration should specify a dummy index
(like s , t and p in the preceding examplcs) for each dimensionof the indexing set. Then
when the constraint corresponding to a particular indexing-set member is processed by
A M P L the dummy Índices take their values from that member. T h i i use o f dummy
Índices fc what permiti a single constraint expression to represem many constraints; the
indexing expression is A M P L ' s translation o f a phrase such ai " f o r ali produets p and
wxreks / = I to 7 " that might be seen in an algebraic statement o f the nnxlel.
By using more oomplex indexing expressk>ns. you can specify more pree&ely the
constraints to be ineluded in a model. Consider, for example. the f o l l o w h g variation on
the pnxluction time constraint:
s u b j e c L Lo T i m e ( L i n 1 . . T : a v a i l I L J >0}:
num ( p i n PROD} < l / r a L e l p l J * M a k e l p . L j <= availlLj:
s u b j e c L Lo T i m e ( i £ a v a i l > 0 } :
num ( p i n PROD} < l / r a L e l p l J * M a k e l p ] <= avail:
Conveniente and readability should determine whatterms you place on each side o f the
operator. A M P L takes care o f canonicalizing constraints. such as by combining linear
terms involving the same variable and mt>ving variables from one side of a constraint to
the other. The e x p a n d command described in Scction I.4 sho\vs the canonical forms of
the constraints.
A M P L also alio ws double-inequality constraints such as the foDowing from the diet
nnxlel of Figure 2-1:
s u b j c c L Lo DioL ( i i n IHTTR} :
r x m i n [ i l <= sum ( j i n FOOD} a m t . l i . j l * Buyljl <= nmaxlil:
This says that the middle expression. the amount o f nutrient i supplied by ali foods. must
be greater than or equal to n _ m i n [ i ] and also less than or equal to n_rnax [ i ] . T h e
permissible forms f o r a constraint of this kind are
where each canst-expr must c\>ntain no variables. The effect is to give upper and lower
bounds on the value of the lineur-expr. If your nnxlel requires variables in the left-hand
or right-hand eonsbexpr, you must define two diíTerent constraints in separate declara-
tions.
For most appücations of linear programming. you need not worry about the form o f
the constraints. I f you simply write the constraints in the most convenicnt way. they will
be recognizcd ai pcoper linear constraints according to the rules in this chapter. There do
exist situatk>ns. howvrver. in which your choicc o f formulation will determine whether
AMPL recognizes your mixlel ai linear. Imagine that w\r want to further constrain the
pnxluctk>n nnxlel so that no pnxluct p may represem more than a certain fraction o f total
produetion. W e define a parameter r n a x _ £ r a c to represem the limiting fraction: the
constraint then says that pr ixluction of p divide d by k>tal produetion must be less than or
equal t o m a x _ £ r a c :
s u b j c c L Lo L i m i L ( p i n PROD}:
Make [p| / sum ( q i n PROD} M a k c [ q ] <= m a x _ £ r a c :
This is not a linear constraint to AMPL, because its left-hand expression contains a divi-
sion by a sum o f variables. But if we rewrite it as
s u b j c c L Lo L i m i L ( p i n PROD}:
Make [p| < = n â x . i r a c * sum ( q i n PROD} Make[q|:
Excrcises
8-1. In éie dk-t model of Figure 5 1. add a : = phrase Io t h : v a r dccliralxin (as expiuned in S o e
IkinS.l ) t o írabab/e each variablc l o a value midway betuecn it* kiuvr aixl upper bounds.
Read lhr< rncidel into A M H . akirçg with the dali fam Figure 5 2 . Uxing d i . c p i a y oammaficfc.
determine which c<m-4raints ( i f a n y ) l h e iniíul sohitian fails l o s a t i s f y . a n d what total ocut this sohi
Ikingives. Is lhe lotai C X K ! m o r e o r k-ss lhan lhe optimal fcttil CXKÍ?
8 - 2 . Thrs exercwe asks vou Io refcrmuLUe various kiixls of conslraints fc> make lhem linear,
( a ) T h e folkiwirç; conslraint says lhal lhe i n v e n k r y l n v [ p , L l f<r product o i n anv period t mini
not cjtoeed lhe smaDcsl one perkidprodiKtkin M a k o [ p . L l of producl p :
flufcjacc t o I n v _ L i m i C f p i n PROD, c I n 1 . . T ) :
X n v r p , c ) < - min f c c í n 1. . T ) iCaXaíp, c c ) ;
Thrs constraint is ncil xeoognúzd as linear by A M H - , hecause * applies lhe m i n operafcir lo vari
ables. Formula*? a i n r conslraint lhal has lhe « m e e f l e c t
<b) The folkiwirç; constraint says lhal lhe chinge in lotai inventeries f r o m o n e period l o lhe next
may ncil exceed a cerlain pirameter m a x changc:
flufcjact t o ííax.CAanga f t I n 1 . . T ) :
a&fl ifluir, f p í n PROD) I n v r p , c - 1 ] - flum f p í n PROD) I n v r p , C l )
<- max-^hanga;
( c ) T h e folktwing consirainl saysthil lhe r a t i o o f total produetion lo fctlil invertory in a period may
not exceed m a x inv_raLio:
flufcjacc to tex_Znv_Raclo fc ín 1 . . T ) :
(surr. f p í n PRCD) - r r v i p , C ] ) / (num f p í n PRCD) Xa3c*rp,c])
<- m a x _ í n v _ r a c í o ;
Th rs constraint is not linear hecause * divides one s u m o f varábles by another. Tormulate a linear
conslrainl lhal his lhe same e f l e c t
( d ) Whal can you say ab<iul fcrmuLilkin of an a l i e m ali w linear co mirai nt f<* lhe folkrw mg cases?
- In (a), m i n K replaced by max.
- In (by. < = max . c h a n ç c i s r e p h c e d by > = m i n _ c h a n ç c .
8 - 3 . Th rs exerci se deah with some more possfcilities f<r usmg m o r e than one objective funetion
i n a diet model. Ilere we oonsider lhe model o f Figure 5- l.togcther with the d i l a from Figure 5-2.
Suppose lhal lhe c«<ts are iixlexed o w r sk*es as xwllas foods:
aac STOIE:
l>sing the o b j o c L i v e c o m m n d . fmd #ic k i w s t cost dk-t f<r each stoie. Which ÍKCK offers the
lemes! totil cosi?
C o m i d a now an additonal objective that represem s fcial juckages purchased. regardless of cxrst:
rr.inLtr.Lza T o c a l . J t a t i b a r :
flurr. [} ín FCOD) Buyrjl;
Whal K the minimum vahie o f this objecliw? W h i l an: the costs at the three slores when this
objective K minimi/rd? lixplam why you woukl expect these costs to be tolher thin the costs
ccmipulcd in (a).
a n p l : dlmplãy TotAl_Comt,
anpl? (i In ORZO, J in DBST) cost (i, JJ Tr*n*(l, JJ/
T o t a l _ 0 > f l t - 30
eofltri,J]*T»n*ri,J]
Coullard X239 1
DMXin D241 4
Hazan C246 1
Hc&> C2bl 2. 5
Hc&> D237 0. S
Iravani C138 2
L i n a t f l X y C250 3
Kaíurotra D239 2
Kolfion C140 4
S o d l o w l t z X23 3 1
TjrrJvana C11B 5
Whit« C2bl 2.
Whita D23 7 1. B
Coullird rs now assigned her first choice, bul whit is the difficulCv wieh the overall solution? Why
doexn'l ü give a useful resolulx»n to the assignmenl problem as we have stitcd il?
8 - 5 . Rcturn fc» the assignment version of the t£insp<fflafcon model. in IHgures 3 la and 3 2.
(a> Ackl pranetefx - ^ o r s H i l for each i in ORlG. arxl colistrainls siying that T r a n s f i . j 1
must equal 0 kw every combinai ion of i in O R l G M\d j in DKST sudi thit c o s t l i . j 1 K g n t f e r
142 LNEAR F T O 3 R W S V / « A f i l £ S . C e J E C T V E S A N D O O t t S T R A NTS CHífTÇR3
9
Specifying Data
143
144 3=ECFYNGDATA CHífTÇRO
ampl:
A M P L leaves daia mode when it sees any statement < like d i s p l a y ) that does not begin
with a Iceyword (like s e L or pararn) thai begins a d a L a statement. T h e r>cdel c o m -
mand. w i t h o r without filename. a b o causes a return to nnxlel nnxle.
S E C T GN 0 2 DATA N L S T S 145
Model componcnts may be assigncd values from any number o f data files, by using
multiple d a t a commands. Rcgardless o f the number o f fites. A M PI. cheeks that no c o m -
ponent is assigned a value more than onee. and duplicate assignment^ are f b g g e d as
errors. In some situations, hovwrver, it is convcnient to be able k> change the data by issu-
ing new d a t a statc me nts; for example. after solving for one scenario o f a model. you
may want to nuxlify some of the data by reading a new data file that oorresponds k> a sec-
ond scenario. The data values in the new file would norma D y be treatcd as erronoous
duplicates, but you can tell A M P L to accept them by first giving a r e s e t d a t a or
u p d a t e d a t a oommand. These alternatives are describod in Sectk>n 113, along with
the use o f r e s e t d a t a to resample randomly-computcd parameters. and o f l e t to
dircctly assign new set or parameter values.
param a v a i l : = 40:
M o U of a ty picai model's parameters are indexed over sets. however. and their values are
specified in a variety of lists and tables that are introduced in this sectk>n and the next
respectively.
W e stan with sets ofsimple one-dimensional objects. and the one-dimensional collec-
tions o f parameters indexed over them. We then turn to two-dimensional sets and param-
eters. for which w e have the addhional option of organi/ing the data into " s l i c e s 0 . The
options for two dimen&ions are then shown togcncrali/e readily to higher dimensk>ns. for
which present some three-dimensional examples. Final ly, wxr show how data state-
ments for a set and the parameters indexed over it can be combincd to provklc a more
conciseand convenient repr esentation.
c o t PROD:
s e t PROD : = bands c o i l s p l a t e :
and the parameier's specification may be vinually the same except for the additk>n of a
value after each set member:
param r a t e : =
bands 200
coils 140
plaLc 160 :
A l s o a parameter may not be given more than one value for each member o f the set o v e r
which it is indexed. A violaiion o f \ht% m i e provokes a similar message:
The coniext brackctcd by » > and < « isn't the exact point o f the error, but the message
makes the shuation clear.
A set may be specified as empty by giving an empty list o f members: simply put the
scmicolon right al ter the : = operator. A parameter indexed over an empty set has no data
aisociatcd with i t
T h e extension o f data liits k> the two-dimensional caie ti largely straightforward, but
with each set member denoted by a pair o f objects. A s an example, consider the f o l k n v -
ing se ti from Figure 6-2a:
Then the membership o f L I N K S may be specified as a liit o f tuples such ai you would
11 nd in a imxlcl's indexing expressions,
s o L L1WKS : =
(GARY, D Kl') (OARY, LAM) <GARY.STLJ (GARV. LAFJ ( C L K V . FRA)
(CLKV.DKl*) ( C L K V . LAM) (CLEV.WINJ <CLKV. SVL\ ( C L K V . LAFJ
(PITT,FRA) (PITT.WIN) <prrr.STLJ ( P I T T , FRKJ ;
SECT GN 0 2 DATA N L S T S 147
ML LINKS : =
OARY DKT GARY LAN GARY STL GARY L A F
CLKV FRA CLKV DKi' CLKV LAN CLKV WIN
CLKV SVL CLKV LAF P I T T FRA P I T r WIN
p i r r svL PITT FRK ;
T h e order o f members within each pair is significam — the first must be f r o m O R I G , and
the second f r o m D E S T — but the pairs themselves m a y appear in any order.
A n ahernative. more concise way t o d e s e r t e this set o f pairs is t o list ali second com-
ponents t h a t g o with each first component:
c o t LINKS : =
( O A R Y , * ) Dar LAN SVL LAF
( C L K V , * ) FRA DKV LAN WIN SVL LAF
( P I T T , * ) FRA W I N SVL FRK :
It is a l s o e a s y *> list ali first components that g o with each second component:
c o t LINKS : =
( * ,FRAJ CLKV P I T r (*,DKrj OARY CLKV <*.LAN) OARY CLKV
< * . W 1 N ) CLKV P i r r ( * , LAFJ GARY CLKV (*,FRKJ PITT
( * ,STLJ GARY CLKV P I T r ;
c o t LINKS : =
GARY DKT GARY LAN GARY SVL GARY LAF
CLKV FRA CLKV D Kl* CLKV LAN CLKV WIN
CLKV SVL CLKV LAF P I T T FRA P I T r WIN
P I T r 5?rL PITT FRK ;
param c o s L : =
GARY DKT 14 GARY LAN 11 GARY STL 16 GARY LAF 8
CLKV FRA 27 CLKV D Kl* 9 CLKV LA?J 12 CLKV WIÍJ 9
CLKV 5?RL 26 CLKV L A F 17 P I T T FRA 24 P I T T WIÍJ 13
P I T r SVL 28 prrr FRK 99 :
148 3=ECFYNGDATA OWFTCR 9
L HNXS : =
<GARY. * ) Dar LAN SVL L A P
(CLEV, * ) KRA DtfT LAN W I N STL LAK
(PITT, *) KRA WIN STL KRK ;
param c o s L : =
(GARY, * ] DOT 14 LAN 1 1 5>FL 16 LAP B
ICLHV. * 1 KRA 2 7 DET 9 LAN 12 WIN 9 STL 26 LAF 17
[PITT, * 1 KRA 24 WIN 13 5>FL 2B KRE 99 :
T h e tempbtes are given in brackets t o distingu&h them from the set templates in parcn-
theses. but they work in lhe same way. Thus a template such as [ G A R Y , • ) indicates
that the ensuing entries w i l l be for values o f c o s t that have a first indcx o f G A R Y , and an
e n t r y s u c h a i DET 14 gives c o s t [ • G A R Y ' . ' D E T ' ) a value o f 14.
A l i o f the above applies just as w e l l t o the use o f templates that slice on the first
dimension. sothat f o r instance y o u c o u k l also specify parameter c o s t by:
param c o s t : =
l * , KRA] CLEV 27 P I T T 24
l*.Dirrl GARY 14 CLEV 9
[*.LAN] GARY 1 1 CLIÍV 12
[ * «WIN) CLEV 9 P I T T 13
l*.STLl GARY 16 CLIÍV 26 PITT 2B
[ * , FREI P I T T 99
l*.LAKl GARY B CLIÍV 17
param c o s t : =
GARY DBT 14 GARY LAN 11 GARY STL 16 GARY LAF B
T h e concepts underlying data lists for two-dimensional sets and parameters extend
straightforwardly t o higher-dimensional cases. T h e only diíTerence o f any note is that
nontrivial slices m a y be made through more than one dimension. Hence w e c o n f i n e the
presentation here ii> s o m e ilhistrative examples in three dimensions, f o l l o w e d by a sketch
o f the general rules for the A M P L data list formai that are given in Scction A . 12.
W e take our example from Scction 6.3, where w e suggest a version o f the multicom-
modity transportatk>n nnxlel that defines a set o f triples and costs indexed o v e r them:
Suppose ihat O R I G and D E S T are ai above, thai PROD only has members b a n d s and
c o i l s . and that R O U T E S hai as members cenain triples from { O R I G , D E S T . P R O D ) .
T h e n the membership o f R O U T E S can be given most simply by a list o f triples» either
i t ROUTES : :
(GARY. L AM, c o i l s j (ÚARY.STL. coilsJ (GARY. LAF coilsj
( C L B V . F R A , handsj ( C L K V . FRA. coilsj (CLKV.DKT bandsJ
( C L K V . DKÍ*, c o i l s j (CLKV. LAN. bandsJ (CLKV.LAN coilsj
( C L E V . W I N , c o i l s j (CLKV. STL. bandsJ (CLKV.STL coilsj
( C L B V . L A F , bandsJ (PITT.FRA. bands) ( P I T T .WIN bandsJ
( P I T T . S T L , bandsJ ( P I T T .FRH. bands) ( P I T T . FRB coilsj
or
i t ROUTKS : =
GARY L A N coils GARY SVL coils GARY LAF c o i l s
CLKV FRA bands CLKV FRA coils CLKV DKT b a n d s
CLKV DKT coils CLKV LAN bands CLKV LAN c o i l s
CLKV WIN coils CLKV SVL bands CLKV SVL c o i l s
CLKV LAF bands PITT FRA bands PITT WIN b a n d s
P I T T STL bands PITT FRK bands PITT FRK c o i l s
Using l e m p b t e s ai before, but with three henfc in each templaie, \v>í can break the speci-
fication into slice* through one dimensk>n by placing one * in each templaie. In the fol-
l o w i n g cxamplc, w e slice through the second dimension:
s « L ROUTKS : =
(CLKV.* .bandsj FRA DKl' LAN SVL L A F
( P I T T , * . bandsJ FRA WIN STL FRK
Because the set contains n o members with origin G A R Y and product b a n d s , the l e m p b t e
(GARY, • . b a n d s ) is omhted.
W h e n the set's dimension is more than two, the slices can also be through more than
one dimension. A slice through t w o dimensions, in particular, naturally involves placing
two in each templaie. I lere \V>Í slice through both the first and third dimensions:
s e t ROUTKS : =
( * . F R A . *J CLKV b a n d s CLKV coils PITT bands
( * . D Kl*. *J CLKV b a n d s CLKV coils
(*.LAN.*J GARY c o i l s CLKV bands CLKV coils
( * . W I N . *J CLKV c o i l s PITT bands
( * . S T L . *J GARY c o i l s CLKV bands CLKV c o i l s PITT bands
( * .FRK. *J PITT bands PITT coils
( * . L A F . *J GARY c o i l s CLKV bands
param c o s t : =
[ C L K V , * . b a n d s 1 F R A 27 D Kl* 9 LAN 12 STL 2 G LAF 17
I P 1 T T . » . b a n d s J F R A 24 W I N 13 STL 2B FRK 99
[GAR Y, * , c o i l s 1 L A N 11 S T L 1G LAF B
[ C L K V , * , c o i l s 1 K R A 23 D Kl* B LAN 10 WIN 9 SVL 21
I P 1 T T . » , c o i l s l FRK B I J
Ot
param c o s t : =
[* .bandsl CLKV FRA 27 CLKV D Kl* 9 CLKV LAN 12
CLKV STL 2G CLKV LAF 17 P I T T FRA 24
P I T T WIN 13 P I T T STL 2B P I T T FRK 99
Ot
param c o s t : =
CLKV DKT bands 9 CLKV OKI' c o i l s B CLKV FRA bands 27
CLKV FRA coils 23 CLKV LAF b a n d s 17 CLKV LAN bands 12
CLKV L»\N coils 10 CLKV SVL b a n d s 2G CLKV STL coils 21
CLKV WIN coils 9 GARY LAF c o i l s B GARY LAN coils 11
GARY SVL coils 1G PITT FRA b a n d s 24 PITT FRK bands 99
P I T T FRK coils BI PITT SVL b a n d s 2B PITT WIN bands 13 :
By placing the in difíerent positk>ns within the templates. w e can slk:e one-
dimensionally in any o f three diíferent ways. o r two-dimensionally in any o f three d i f l e r -
ent ways. ( T h e template w o u l d s p e c i f y a three-dimensional ltit like
param c o s t : =
CLKV DET b a n d s 9 CLKV DKl* c o i l s B CLKV FRA b a r x i s 27
same data statement, so long a* each parameter is assigned a vahie only once. Where no
template appear s. a template of ali *s isassumcd.
When give ilaia statement* for a set and a parameter indexed over it, like
s e t PWDD : = bands c o i l s : p i a Lo ;
param r a L e : = b a n d s 200 c o i l s 140 plaLc 1G0 :
we are specifying the set's members twice. AMPL krts us avoid thii duplication by
including the sef s nanie in the p a r a m data statement:
AMPL uses this statement to determine both the membership o f PROD and the values of
rate.
Another oommon redunda ncy oocurs when need to supply data for several param-
eters indexed over the same set, such as r a t e , p r o f i L and m a r k e t ali indexed over
PROD in Figure l--la. Rather than write a separavr dato statement for each parameter.
we can combine these statements into one by listing ali three parameter names after the
keyword p a r a m :
param: r a L c p r o í i t m a r k e t : =
bands 200 25 G000 c o i l s 140 3 0 4 000 plaLc 1G0 29 3500 ;
Since A M P L ignores extra spacesand line breaks, w e have the option of rearranging this
information into aneaiicr -to-rcad table:
Either way, \v\r still have the option o f adding the indexing set's name to the statement,
so that the specificaiions of the set and ali three parameters are combined.
T h e same mies apply to lists o f any higher-dimensional sets and the parameters
indexed over them. Thus for our two-dimensional example L I N K S could write
152 3=ECFYNGDATA OWFTCR 0
param: LINKS: c o s t : =
GARY DKT 14 OARY LAM 11 OARY STL 16 OARY LAF B
CLKV F R A 27 CLKV DKl* 9 CLKV LAN 12 CLKV WIN 9
CLKV CTL 26 CLKV L A F 17 P I T T FRA 24 P I T T WIN 13
P I T T STL 2B PlTr FRK 99 :
param: LINKS: c o s t : =
(OARY, * ] Dar 14 LAM 1 1 S r L 16 LAF B
[ C L K V . * 1 FRA 27 DKT 9 LAN 12 WIN 9 STL 26 LAF 17
[ P I T T , * 1 FRA 24 WIN 13 S r L 2B FRK 99 :
l i e r e the membership o f the indexing set is specified along with the t w o parameters: f o r
example, t h e t e m p l a i e [GARY. * ] f o l l o w e d by the set member D E T a n d the values 14
SECT Cti 9 2 DATA N L S T S 1 53
and 1000 indicates that {GARY, DET) is k> be ttkfed to the set LINKS, thai
cost(GARY.DET) h*> the value 14. and thai l i m i t I G A R Y . D E T ] has the value
1000.
A s our Dlustrations suggea. the key k> the interpretai k>n o f a p a r a m statement thai
providos values for several paramcters or for a set and paramcters is in the first line,
which consisti o f p a r a m folknved by a c o l o n . then optk>nally the name o f an indexing
set followxrd by a cok>n. then by a list o f parameter names tcrminaied by the : = assign-
ment operator. Each subsequent item in the list consias o f a number o f set members
equal to the number o f •s in the most recent template and then a number o f parameter
values equal to the number o f paramcters lisied in the first line.
Normally the paramcters listed in the first line o f a p a r a m statcmcnt are ali indexed
over the same s e t T h ti need not be the caie. howxrver, as seen in the case o f Figure 5-1.
For this variaiion on the dict nuxlel. the nutriem restrictions are given by
ML MI.NREQ:
ML MAXRKQ:
so that n _ m i n and n _ m a x are indexed over sets o f nutrients that may overlap but that are
not likely *> be the same.
Oursampkr data for this nuxlel speeifkrs:
M L Ml.NRISQ : = A Bl B2 C CAL ;
M L MAXRKQ : = A NA CAL ;
Each periixl or dot < . ) indicaics to A M P l . thai no value is being given for the correspond-
ing parameter and index. H>r example. since X I N R E Q d<xs noi contain a member NA,
the parameter n _ m i n I N A ] is noi defined: coAsequently a . is given as the entry for N A
and n _ m i n in the data statemem. W e cannot simply leave a space for this entry, because
A M P l . w i l l take it ii> be 5 0 0 0 0 : daia nuxle processing ignores ali extra spaces. Nor
should we put a z e r o in this entry: in that case will get a message like
d i e L u . d a L . l i n e 16 ( o £ Í ! x » t 366 J :
NUTR w a s d e i i n o d i n L h e n o d e l
conLexL: p a r a m : NUTR > » : « < n_min n nvax :=
Two-dimensional tables
Data values for a parameter indexed over t w o sets. such ai the shipping cost data from
the transponation model o f Figure 3 - I a :
r-eL O R I G :
KCL DEST:
T h e IÜW labels g i v e the first index and the column labels the second index, s o that f o r
example c o s t I ' G A R Y ' , ' F R A - ) is set t o 39. T o enable A M P L *> r e e o g n i z e this ai a
table. a c o l o n must f o D o w the parameter namc. while the : = operator f o l i ow s the list o f
column labels.
For larger index sets, the columns o f tables become impossible t o v i e w within the
w i d t h o f a single s c r e e n o r page. T o deal with this shuation. A M P L oHers several altcrna-
tives, which \v>í illustrate on the small table above.
W h e n only one o f the index sets is uncomfonably large, the table m a y be transposed
s o t h a t the column labek correspond *> the smaller set:
param c o s L (LrJ :
GARY CLKV pitt : =
FRA 39 2? 24
DKT 14 9 14
LAN 11 12 17
MIN 14 9 13
SVL 16 26 2B
FRK 02 95 99
LAF e 17 20 ;
T h e notation { t r ) after the parameter name indicates a transposed table, in which the
column labels g i v e the first index and the r o w labels the second index. When both o f the
index sets are large, either the table or its transpose m a y be divided up in some way.
Since line breaks are ignored. each r o w may be divided across several lines:
A colou indicates the start o f each n e w sub-table: in this example, each ha* the same r o w
labek. but a different subset o f the cohimn labels.
In the alternative formulation o f this nnxlel presented in Figure 6-2a, c o s t is not
indexed o v e r ali combinations o f members o f O R I G and D E S T . but o v e r a subset o f pairs
f r o m these sets:
156 3=ECFYNGDATA CHífTÇRO
N t L I N K S w i t h i n (OR IG . Cli SY } :
p a r a m c o s t ( L I N K S } > = 0:
ML LINKS : =
(GARY, * ) DOT LAN SVL L A F
( C L E V , * ) KRA DOT LAN WIN STL LAF
( P I T T . * J KRA WIN STL KRK ;
Rather than being given in a similar list the values o f c o s t can be given in a table like
this:
A cost vahie is given for ali pairs that exist in L I N K S , while a dot ( . ) serve* as a
place-holder f o r pairs that are not in L I N K S . T h e dot can appear in any A M P L table t o
indicate " n o v a l u e specified h e r e " .
T h e set L I N K S may itself be given by a table that is analogous t o the one for c o s t :
A • indicates a pair that tv a member o f the set, and a - indicaies a pair that is not a mem-
ber. Any o f A M P I . ' s table formats f o r s p e c i f y i n g parameters can be used for sets in this
way.
c o t ROUTES w i t h i n ( O R I G . DEST. P R O D } :
p a r a m c o s t (ROUTES} >= 0 ;
T h e values for this parameter that w e specified in l&t formai in the previous scction as
param c o s t : =
(•.•.harxisl CLEV KRA 27 CLEV DET 9 CLEV LAN 12
CLEV STL 26 CLEV L A F 17 P I T T KRA 24
P I T T WIN 13 P I T T STL 28 P I T T KRE 9 9
param c o s L : =
vSince w e are working with two-dimensional tables, there must be t w o * ' s in the lem-
plates. A table value's r o w label is substitutcd f o r the first and hs column label for the
sccond, unless the oppo&ke iü specified by { t r } right after the l e m p k t e . Y o u can omit
any r o w s or columns that woukl have n o significam entries, such as the r o w for G A R Y in
the I • . • , b a n d s ] table above.
A s b e f o r e , a dot in the table for any slice indicaies a tuple that is not a member o f the
table.
A n anak>gous table t o s p e c i f y the set R O U T E S can be constmctcd by putiing a •
where each numberappears:
s e t ROUTKS : =
vSince the templates are n o w set templates rather than parameier templates, they are
enclosed in parentheses raiher than brackets.
Higher-dimensional tables
By putting more than one index t o the left o f each r o w or ai the top o f each column.
you can describe multidimensional daia in a single table rather than a seriei o f slices.
We'11 continue with the three-dimensional cost data t o ilhistrate some o f the wide variety
o f possibilities.
By putting the first t w o índices, from sets O R I G and DEST, t o the left, with the third
index from set PROD ai the top, w e produce the f o Q o w i n g three-dimensional table o f the
costs:
158 3=ECFYNGDATA CHífTÇRO
param c o s L : bands c o i l s : =
CLKV FRA 27 23
CLKV Dar 8 8
CLKV LAN 12 10
CLKV WIN . 9
CLKV S1'L 26 21
CLKV LAF 17 .
P I T T FRA 24
P I T T WIN 13
P I T T S1'L 28 .
P I T T FRK 99 81
GARY LAN . 11
GARY srL 16
GARY LAF 8
Putting only lhe f i r a index *> the left. and lhe second and third ai the top. \v>í arrive
inste ad ai the following table. which for convenience w e break intotwopicces:
In general a colon must precede each o f the table hcading lines. while a : = is placed only
after the last hcading line.
T h e Índices are taken in the order that they appear. first ai the left and then at the top.
if no indicatk>n ti given to the contrary. As with other tables. you can add the indicator
{ t r > to transpose the table. so thai the Índices are still taken in order but first from the
top and then from the left:
Templatescan also be used to specify more precisely whai goes where. K>r multidimen-
sional tables the templaie has t w o symbols in it, * k> indicaie those Índices that appear at
the left and : to i n d i c a i those that appear at the top. For example the templaie
l * . : . * ] gives a reprcsentation in which the first and third índices are at the left and the
second is at the top:
SECT-ON 9 3 D A T A N 1/BLES 1 59
param c o s t : =
l : FRA O ITT LAN WIN STL FRB LAF :=
CLKV bands 27 9 12 . 26 17
CLKV c o i l s 23 8 10 9 21
P I T T bands 24 . . 13 28 99
PITT c o i l s . . . . . 81 .
G>\RY c o i l s . . 1 1 . 1 6 . 8 ;
The ordering of lhe indiccs is ai ways preserved in tables of th& kind. The thirtl index is
never correctly placed before the first for example. no matter what transpositk>n or tem-
plates are empk>yed.
For parameters o f four t>r more dimensions, the ideas of slicing and muhidimensional
tables can be applied together provide an especially broad choice of table formato. If
c o s t \vx*e indexed over ORIG, DEST, PROD, and 1 . . T , for instance, then the tempbtes
[ * . : . b a n d s . * ) and 1 * . : , c o i l s , • ] could be used to specify two slices through
the third index. each specified by a multidimensional table whh two Índices at the krft and
one at the top.
Choice of format
s o t PWDD; * products
s o t ARKA ( P R O D } ; i m a r k o t arcar. í o r oach product
param T > 0; * number o£ weeks
Because the index set J\REÁ. [ p ] is potentiaDy dilTerent for each pnxluct p, slice» through
the first ( P R O D ) dimension are most attractive. In the sample data from Figure 6-1, they
look like this:
param T : = 4 ;
s e t PttDD : = bands c o i l s ;
s e t ARKA ( b a n d s ] : = e a s t n o r Lh ;
set ARKA[coils] := east wcst export :
param r e v e n u c : =
[bands, * j * 1 : 1 2 3 4
east 2S.0 26.0 27.0 27.0
nor th 26.S 27. S 28.0 28.5
l c o i l s . * 1 : 1 2 3 4
east 30 3S 37 39
wcst 29 32 33 35
expart 2S 25 25 28 ;
160 3=ECFYNGDATA CHífTÇRO
We have a separai: revenue table for each product p, with market arcas from AREA [ p ]
labeling the rows, and wveks from 1 . . T labeling the columns.
Default values
Data statements must provide values for exactly the parameters in your model. You
will receive an error messagc if you give a value for a nonexistent parameter:
error p r o c e s s i n g param c o c L :
i n v a l i d s u b s c r i p L c o s L [ ' P 1 T T ' . 'DEI* • c o i l s • 1 discarded.
The error messagc appears the first time that AMPL tries to use the olYending parameter,
usually after you type s o l v e .
I f the same value would appear many times in a data statement, you can avoid speei-
fying it repeatedly by including a d e f a u l t phrase that provides the value to be used
when no explicit value is given. H>r example, suppose that the parameter c o s t above is
indexed over ali possible triples:
s e t O Kl Cl:
s e t DEST:
seL PROD;
but that a very high cost is assigned to routes that should not be used. This can be
expressed ai
param c o s L d e f a u l L 9999 :=
l * , * ,barxisl : FRA DEI* LAN WIN STL FRE LAF :
CLEV 27 9 12 . 26 . 17
pirr 24 . . 13 28 99 .
l * . * . c o i l s l : FRA D ET LAN WIN STL FRE LAF :
ÚARY . . 11 . 16 . 8
CLEV 23 8 10 9 21 . .
PXTT . . . 81 •
S E C T tON 9 4 O T H S * F E A T U R E S CF O A T A S T A T C V S V T S t 61
Mi&sing parameters like c o s t I ' G À R Y ' . ' F R A * . ' b a n d a • J, as well ai those explic-
itly marked " o m i t t e d " by use o f a dot (like c o s t I ' G A R Y " , ' F R A * . ' c o i l s * ) ) , are
given the value 9999. In total, 24 values o f 9999 are « s i g n o d .
The d e f a u l t feature is especially useful when you want ali parameters o f an
indexed colkection *> be assigned the same value. For instance, in Figure 3-2, we apply a
transponation mixlel to an aüsignment problem by setting ali supplies and demandsto I.
The nnxlel declarei
param s u p p l y d e f a u l t 1 ;
param demand d e f a u l t 1 ;
Since no other vahies are specified, the default o f I is au*>matically assigned to every ele-
ment o f s u p p l y and d e r i a n d .
A s explained in Chapter 7, a parameter dcclaraiion in the nnxlel may include a
d e f a u l t expression. ThisolYers an alternative way to specify a single default value:
If you just want to avoid storing a lot of 9999's in a data file, however, it is better to put
the d e f a u l t phraie in the data statement. The d e f a u l t phrase shoukl g o in the
nnxlel when you want the default value k> depend in some way on other data. For
instance, a different arbitrarily large cost could be given for each pnxluct by specifying:
For an indexed coDection of sets, separate data statements specify the members of
each set in the collection. In the example of Figure 6-3, for example, the sets named
J\REÀ are indexed by the set PROD:
s e t PWDD; * products
Any o f the data statement for ma ts for a set may be used with indexed collectk>ns of se ti.
The only diíYerence is that the set nanie following the key word s e t is subscripted.
162 3=ECFYNGDATA CHífTÇRO
A s for other sets. you may specify one or more members o f an indexed colleetion t o
be empty. by g i v i n g an empty list o f elements. if you want t o provide a data statement
only for those members o f an indexed colleetion that are not empty, define the empty set
ai thedefauh value in the model:
Other wise you w i l l be warncd about any set whose data statement is not provided.
Y o u may optionally assign inhial values *> the variables o f a nnxlel, using any o f the
options f o r aisigning values t o parameters. A variable's name stands for hs value, and a
constraint's name stands for the associated dual variable's value. ( S e e Section 12.5 for a
shonexplanation o! dual variables.)
A n y p a r a m data statement may s p e c i f y initial values for variables. T h e variable or
constraint name is simply used in p b c e o f a parameter name, in any o f the formais
described by the previousseetk>ns o f \ht% chapier. T o h e l p c l a r i f y the intent, the k e y w o r d
v a r may be substhutoJ for p a r a m at the start o f a data statement For example. the f o l -
lowing data table gives inhial values for the variable T r a n s o f Figure 3 - l a :
A s another example, in the nnxlel o f Figure 1-4. a single table can g i v e values f o r the
parameters r a t e . p r o f i t and m a r k e t . and initial vahies f o r the variables J í a k e :
param T > 0:
4
40 40 3 2 40
Or you can use an indexing exprcssion t o say the same thing more concisely and gener-
ally:
T h e notation < f i l t m u n e specifies the name o f a file for reading. < Analogously, > indi-
catei writing t o a file: see A . 15.)
In general, the r e a d command h a i t h e focm
with the iit/n hsi being a comma-scparatcd list o f items that may each be any o f the f o l -
lowing:
ptimnvler
( intirxinx } pamnvity
( intif.xinii } < ütn\ lis: )
T h e first t w o are used in our example above, while the third allows f o r the same indexing
t o be applied t o several items. Using the same pnxluction example, t o read in vahies for
p a r a m p r o d c o s L (PKOD} >= 0:
p a r a m i n v e o s t (PROD} > = 0 ;
param r e v e n u e ( P R O D . 1 . . T } > = 0:
reading from file c o s t _ d a t a first ali the produetion costs. then ali the inventory costs.
and then ali the revenues.
I f the data weie organi/ed by product instcad. you coukl say
r o a d ( p i n PttDD}
( p r o d o o s t Ipl , i n v c o s t l p l , (t in 1. .T> r c v e n u c l p . 11J
<cos t _ d a t a :
to read the produetion and inventory costs and the revenues for the first product. then for
the second product. and so fotfth.
A parenthesi/ed iíem-list may itself contain parenthesi/ed ilem-Esls» so that if you
also \vant to read
from the same fileat the same time, you could say
r o a d ( p i n PROD} ( p r o d c o s t l p j . i n v c o s t l p l .
( t i n 1 . . T } < r c v e n u © l p . 11 . m a r k e t l p . 11J J < o o s t _ d a t a :
in which case for each product you would read the two costs as before. and then for each
week the product's revenue and market dcmand.
A s our dcscriptions suggest. the form of a r e a d statement *s ttm-lisí dependson how
the data values are ordered in the file. When you are reading data indexed over sets of
strings that, like PROD, are not inherently ordered, then the order in which values are read
is the order in which A M P L is internally representing them. I f the members of the set
carne direetly from a s e t data statement, then the ordering will be the same as in the data
statement. Otherwise, it is best to put an o r d e r e d or o r d e r e d b y phrase in the
model's s e t declaration k> ensure that the ordering is always what you expeet: see Sec-
tion 5.6 for more about ordered sets.
A n aliernative that avoids knowing the order o f the members in a set is to speeify
them explicitly in the file that is read. As an example, consider how you might use a
r e a d statement rather than a data statement to get the values from the c o s t parameter
of Section 9.-1 that was defined as
road n t r i p l o s . ( 1 . . n t r i p l o s }
< i c . j c . kc. c o s t ( i c . j c . k c l ) <cost_data:
The cor respondi ng file cost_dat<i must begin something like this:
SEC7CN9 5 FEAD N 3 Uf^CFWATTHD DATA. THE *LXD OOWW/*© 165
18
CLKV FRA b a n d s 27
P I T T FRA b a n d s 24
CLKV FRA c o i l s 23
with 15 more entries necdcd k> g i v e ali 18 ilata values shown in the Section 9.4 example.
Strings in a file for the r e a d c o m m a n d that include any eharacter other than letters,
digita. undcrsci>res. period. • and - must be quoted. just ai for data mode. H o w ver, the
r e a d statement itself is interpreied in nnxlel mode, s o if the statement refers any par-
ticular string, ai in, say,
that string must be quoied. T h e filename f o l l o w i n g < need not be quoted unless it c o n -
tai ns spaces. semicok>ns, or nonprinting characters.
I f a r e a d statement conta ins n o < file nume. values are read from the current input
stream. Thus if you have typed the r e a d command ai an A M P L prompt. you can type
the values at subsequent prompts until ali o f the listed items have been assigned values.
For example:
a m p l : r o a d T, ( t in 1. .T) avail[t)/
ampl? 4
a m p l ? 40 40 32 40
a m p l : diaplay avail/
a v a i l 1*1 : =
1 40 2 40 3 32 4 40
T h e prompt changes from a m p l ? hack t o ampl: when ali the needed input has been
read.
T h e filename <a literal mi nus s i g n ) is taken as the standard input o f the A M P L
proccis: this is useful f o r providing input inieractively.
Funher uses o f r e a d wkhin A M P L scripts. t o read values directly from script f i l e s or
t o prompt users for values at the c o m m a n d line, are described in Chapier 13.
A l i o f our examples assume that underlying sets such as O R I G and PROD have
already been assigned values. through data statements as described earlier in this chapter,
or through other means such ai database access or assignment t o be described in later
chapters. Thus the r e a d statement would normally supplement rather than r e p b c e other
input c o m m a n d * . It is particularly useful in handling long files o f data that are generated
for cenain parameters by progranti outside o f A M P L .
Excrcises
9 - 1 . Sectian 92 ga\r A variety cif dita stjLfcnicnfe for A tfirce chmcnsxnul s e i ROUTKS. Con-
strui same alhev altrrnsliwx for thrs sei as folkiws:
166 3=ECFYNGDATA CHífTÇRO
9-2. Rewrite the produetion model dita of Figure 5-4 so that it coroists of just three dati stite
menls arrarçged AS follows:
The set PWDD *id jurameters r a t e , invO. p r o d c o s t .nd i n v c o s t aie given in one «atile.
Tlie set WEEKS anJ parameter a v a i l an: given in ene table.
Th: parameters r c v e n i x s and tnarkoL an: gi\en in one table.
9-3. For the a^ignmenl problem whose dati k depxled «n 1'igure 3 2, suppose that the only infor
mation you nxeise about people'spiefeieiKes foroffices K as folkiws:
"DIK me aro that for example. Coullird's first chcice is M239. her second choice is M233. anJ so
onthrotçh her fifth choice, D239. but she lusn't given any pn-feience for the other offices.
To u « thw infermation with the t raro pcixtitkin model ofTiguie 3- la as expluned «n Chapter 3. you
must set c o c t l - C o u l l a r d - . -M239-1 to 1. c o s t l - C o u l l a r d - . -M233-1 to 2. and so
f<rth. For an office noi ranked, surh as C246. you can set c o s 11 - C o u l l a r d - . -C24 6-1 to 99,
toinJicate Ihit il isa hichh unJesirable a\*sicnment.
(a) l><ing the Iwt formal anJ a d e f a u l t phrase. convert the «nfcrmatkin above to an appropriitc
A.VUt. dita statement k t lhe pirameter c o s t .
<b) Do lhe same. bul wâhatible f<rmat.
9-4. Sections 9 2 anJ 9 J ga\e a variety of dila stitemenls for a thiee dimeroxinil pirameter,
c o s t . indexed over the set W3UTES of triples. Corotruct some olher akenutivcs kw thw parame
Icr as foikiws:
(a) Use templitesthit looi like ICLEV. KRA. * 1.
<b) tJ<e templates that ki<il bke [ * . * . har>±: 1. empkijing the hst formal
(c) Use tempUtesthit k w i l i k e ICLEV. l.empki>mg the table f<miat.
(d) Specify some of the paramrter values using fcmpUtcs with one and some usmg templates
with two * x.
9-5. For the three dimcfisional pirameter r e v e n u e of Figure 6 A «MistnKl altema*i\e dita
sti«ements as foQows:
SEC7CN9 5 FEAD N 3 U f ^ C F W A T T H D DATA. THE *LXD O O W W / * © 167
fl*t OR2C;
fl*t DES?;
10
Database Access
169
170 OAT/eASE ACCESS CHVTER10
M L FOOD:
param c o s L (FOOD} > 0 :
param £._min (FOOD} > = 0:
param £ max ( j i n FOOD} > = £._minljl :
A rtlaSkftutl kibit giving vahies for these components has four cotumns:
The column headed FOOD liststhe members o f the A M P L set also named FOOD. Thii is
the table's key column; entries in a key column must be unique. like a sef s members. so
that each key value identifies exactly one row. The column headed c o s t gives the val-
ues of the like-namcd parameter indexed over set FOOD: here the vahie of
costpBEEF'] is specified ai 3.I9. c o s t p C H K ' ) as 2.59. and so forth. The
remaining twocolumns g i v e values for the other t w o parameters indexed over FOOD.
T h e table has ejght tuws o f data. one for each set member. Thus eaeh row contains ali
o f the table's data oorresponding to one member — o n e food. in this example.
In the coniext o f datahase software, the table rows are often viewed as data rtcurds,
and the columnsas fitlds within each record. Thus a data entry form has one entry field
for each column. A form for the diet example ( f r o m Microsoft A c c e s s ) might look like
Figure IO-1. Data records, one for each table row, can be eniered or v i e w e d one at a time
by using the controls at the bottom o f the form.
63 f o o d t H H H
F000 [8EÊT
cozi 3.13
f_mn
í mex 10
Parameters are not the only entities indexed o v e r the set FOOD in this example. There
are also the variables:
ampl: oolvo;
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
13 i t c r a t i o n s . o b j o c t i v e 1 1 B . 0 5 9 4 0 3 2
A l i o f these can be included in the relational table for vahies indexed o v e r FOOD:
Where the first four columns would typically be read i n t o A M P L from a datahase. the lait
three are resulfc that would be written back from A M P L *> the databaie. We have
invented t h e c o l u m n headings B u y R C and B u y F r a c , because the A M P L expressions f o r
the quantities in those columns are typically not valid cohimn headings in database man-
agement systems. T h e t a b l e declaratk>n provkles for input/output and naming distinc-
tions such ai these. as subsequent sections will show.
Other entities o f d i e t . r > c d are indexed over the set N U T R o f nutrients: parameters
n _ m i n and n _ r n a x . dual price* and other values aisociatcd whh constraint D i e t , and
expressions involving these. Since nutrients are entirely d&tinct from f o o d s . howvrver.
the values indexed o v e r nutrients g o into a separate relational table from the one f o r
foods. It might look like this:
172 OAT/eASE A C C E S S C H V 7 E R 10
A s ihis example suggests, any ntxlcl having m o i e than one indexing set will rcquirc more
than one relational table t o hold its data and results. Databaies thai consist o f multiple
tables are a standard feaiure o f relalional daia management, t o be found in ali but the sim-
p l e t f 4 'llat f i l e " datahave packages.
Entities indexed over the same higher-dimensional set have a similar correspondcncv
t o a relational table, but whh one k e y column for each dimensk>n. In the c a i e o f Chapter
4*s s t e e l T . s x x l , f o r example, the f o l l o w i n g parameters and variables are indexed o v e r
the same two-dimcnsional set o f pnxluct-time pairs:
p a r a m m a r k e L (PWDD. 1 . . T } >= 0:
p a r a m r c / c n u c (PROD. 1. ,T> > = 0 :
v a r M a k e (PROD. 1. ,T> >• = 0 :
v a r S e i 1 ( p i n PROD. t i n 1 . . T } >= 0. <= m a r k e L l p . t j ;
A corresponding relalional table thus ha* t w o key columns, one containing members o f
PROD and the other members o f 1 . . T , and then a column o f values for each parameter
and variable. I i e r e ' s a n example, corre sponding t o the data in s t e e l T . d a t :
Each ordercd pair o f items in the t w o key columns is unique in this table, just ai these
pairs are unique in the set { P R O D , 1 . . T ) . T h e r a a r k e t cohimn o f the table implies.
f<* e x a m p l e , t h a t m a r k e t f " b a n d s 1 .1) is 6000 and that r i a r k e t t • c o i l s ' . 3 ] is
3500. F r o m the first r o w , w e can also see thai revenue['bands'.1) is 23,
>£ake [ • b a n d s ' . 1 ) is 5990, and S e i 1 1 ' b a n d s ' . 1 ] is 6000. Again various names
from the A M P I . nnxlel are used as column headings, except for T I M E , which must be
invented tostand for the expression 1 . . T . A s in the prevk>us example, the column head-
ings can be any identifiers acceptable t o the daiabase software, and the t a b l e declara-
tion will take care o f the correspondentes k> A M P I . names < ai expiained b e l o w ) .
SECT C N 10.1 G M R f t L m N C P L E S O F DATA O C F F E S P O f C C N ^ 1 73
A M P l . cnthies that have sufficiently similar indexing gcnerally fit into the same rela-
tional table. W e could extend the s t e e l T . m o d table, for instance, by adding a c o l u m n
for vahies o f
W e use l i . n here ii> mark table entries thai correspond t o values noi defined by the
nuxlel and daia. There is n o rrwarket I • b a n d s ' . 0 ] in the data f o r this model, f o r
example, although there dtxrs exist a value for I n v [ • b a n d s ' . 0 ] in the results. Daia-
bcae packagcs vary in their h a n d l i n g o f " m i s s i n g " entries o f this sort.
Paramcters and variables may a b o be indexed over a set o f pairs that is read ai data
rather than being constructcd from one-dimensional sets. K>r instance, in the example o f
t r a n a p 3 . r > c d from Chapter 3, w e have:
s e t L I N K S w i t h i n ( O R l G . DESY > :
The stmcture here is the same ai in the prevk>us example. There is a row in the table
only for each origin--destination pair that is actually in the set L I N K S . however. rather
than for every possible origin-destination pair.
t a b l e F o o d s I N 'ODBC' 'diet.xis':
FOOD < - [ F O O D ] , c o s t . tjxiin. í_aax;
• For an ASCII text table in file F o < x l s . t a b :
Each t a b l e declaration hai t w o paris. Before the colon, the declaration provides gen-
eral information. First comes the table name — F o o d s in the examples above — which
will be the name by which the table ti known whhin A M P L . The keyword I N states that
the default for ali non-key table oolumns will be read-only: A M P L will read values i/t
from these oolumns and will not write out to them.
Details for locating the table in an externai databaie file are provided by the character
stringssuchas ' O D B C ' and ' d i e t . r r ^ i b ' , with the AMPL table name < F o o d s ) provid-
ing a default where needed:
• Where no details are given. the table is read by default from the ASCII text
file F o o d s , t a b using A M P L ' s built-in text table handler.
SEC7 CN 10 2 EXAVF^ES CF T/ETE K 4 M X N 3 STATEVSVTS 175
In general the formai o f the characier strings in the t a b l e declaraiion depends upon the
table handler being used. The strings required by the handlers used in our cxamples are
described brielly in Sectk>n 10.7, and in detail in online documentaiion for specific table
handlers.
After the cok>n. the t a b l e declaratk>n gives the details o f the corvespondencc
betwxren AMPL entities and relacionai table columns. The four comma-scparated entries
corrcspond to four columns in the table, staning with the key cohimn distinguished by
sunounding brackets (...]. In this example. the namcs o f the table columns (FOOD.
c o s t , t j x i i x u £ _ m a x ) are the same ai the namcs o f the corresponding A M P L compo-
ncnts. The expression FOOD < - ( F O O D ] indicates thai the entries in the key column
FOOD are to be copied into AMPL to define the members o f the set FOOD.
T h e t a b l e dcclaraiion only defines a correspondence. T o read values from columns
o f a relational table ink> AMPL sets and parameters. h ti necessary to g i v e an explicit
read table
command.
Thus. if the data values \vx*e in an Access relatk>nal table like Figure 10-2. the
t a b l e dcclaraiion for Access could be used together with the r e a d t a b l e c\>mmand
to read the members o f FOOD and values o f c o s t , £_snin and f _ j n a x into the corre-
sponding A M P L set and parameters:
1 7 6 OftT/eASE ACCESS CHAPTER 10
G B » cj •
Afi.l - ic * B / 2 » . A tf
f wJs ZI s l r^00
A H C I) 1 F F G *
1
> rrw> ^Hrv^TTV^n^TTH^^VT^rl
3 3CCF 2 1C 113 _
•i CHK 2 1C 2.5?
"ISH 2 10 12?
iAN 2 10 2.8C
/
r •IÍU <1 1 VI J
& 1 V " V
8 MIL 2 10 1 %
SPCi ? tfi 1 9Ê
1fl TUR 2 1C 2 4Í
11
z.
tf I • H:\nwi / 1 Hl
RM2}' sum -115.32 m • l - l - l i
_
Figure 10-3: Excel worksheet range.
And if lhe values wene in a file F o o d s . t a b containing a text table like this:
ampl. t a b 1 3
FOOD cost £_min £ max
BKKF 3.19 2 10
CiJX 2.S9 2 10
FlSil 2.29 2 10
J1AM 2 . B9 2 10
MCU 1. 89 2 10
XV L 1.99 2 10
SPG 1.99 2 10
TUR 2.49 2 10
Because the A M PI. table nante F o o d s is the same in ali three o f these examples, the
r e a d t a b l e command is the same for ali three: r e a d t a b l e F o o d s . In g e n e r a l the
r e a d t a b l e c o m m a n d only s p e e i f i e » the A M PI. name o f the table t o be read. A l i infor-
mation about what is t o be read. and h o w it is t o be handled. is taken from the named
table's definhion in the t a b l e declaration.
T o create the second ( 7 - c o h i m n ) relational table example o f the previous section. w »
oould usea pair o f table declaratk>ns:
or a single table declaratk>n com bi ning the input and output information:
ali might loofc using separatc t a b l e declarations t o reaJ and write the Access table
Foods:
and here ti an alternative using a single declaraiion to both read and write F o o d s :
Either way, the Access table F o o d s woukl end up having three additional columns, ai
seenin Figure 10-4.
T h e same operations are handled similarly for other types o f datahase files. In gen-
eral, the actk>ns o f a w r i t e t a b l e command are determined by the pr eviously dcclarcd
A M P L table named in the command, and by the status o f the externai file associatcd w ith
the A M P L table through hs t a b l e declaration. Depending on the circumstances, the
w r i t e t a b l e command may create a new externai file or table, overwritean extsting
table, over write certain columns within an existing table, or append columns to an exist-
ing table.
T h e t a b l e decbration is the same for multidimensional A M P L entities, except that
there must be more than one key cohimn specified between bracketo I and ) . For the
steel productk>n example discussed previously, the cor responde nce to a rclatk>nal table
oould be set up like this:
SEC7 CN 10 2 E X A V F ^ E S CF T / e t E K 4 M X N 3 S T A T E V S V T S 179
1 9 F o o d * : Tòble H B E 3
FOOD cost f min f max Buy BiiyRC BuyFrac
• [3FFF 319 10 5 3 * 6 1 3 3 1 ' 3 05311F 1f 0 533361381
CHK 2 59 10 2 1 18É&1CSÉ 02
FISH 223 10 2 1 14MJ7SE 02
HAK' 283 Á 10 10 -0 3C265132 1
MCH 1.89 2 10 10 -0.C511CCS I
hfTL 1.93 2 10 10 -1.32ESCG2E I
SPG 1.93 2 10 9 3 X 0 5 2 3 5 5 -2 0123E-1* 0.933505285 I
IUH 2À-J t 1U 1 2731619?78 0.2
¥
• I
| Neccrd:
jr
»< 1 ~ ± 1n ! • • » ! cf g
L a b l e S L o e l P r o d -ODBC- " s t e e l . m d b - :
(PROD. T I H B l . m a r k e t I N . r e v e n u e l?J.
Make OUT, Se 11 OUT. I n v CTJV:
Ilere the key columns PROD and TIME are not specified ai IN. This is because the
parameters t o be read in. rrwarket and r e v e n u e . are indexed in the A M P I . nnxlel o v e r
the set { P R O D . 1 . . T > , whose membership would be specified by use o f other, simpler
tables. The r e a d t a b l e S t e e l P r c d command merely uses the PROD and TIME
entries o f each daiaba*c r o w t o determine the pair o f Índices (subscripts) that are t o be
aisoe ia ted with the r i a r k e t and r e v e n u e entries in the r o w .
Our transponaiion example also i n v o l v e » a relational table for two-dimcnsional enti-
ties, and theassociatcd t a b l e declaraiion is similar:
T h e dilTerence here is thai LINKS, the A M P L set o f pairs over which c o s t and T r a n s
are indexed, is part o f the daia rather than being determined from simpler setsor parame-
ters. Thus \V>Í write LINKS <- (ORIG. DEST], K> request thai pairs f r o m the key
columns be read ink> LINKS ai the same time thai the corresponding values are read into
cost. Thfe distinetion is d&cusscd further in the next section.
A s you can see from even our simple examples so far, t a b l e statements tend t o be
cumbersome t o type interactively. Inste ad they are usually placed in A M P L progranu, or
scripts, which are execuied as described in Chapier 13. T h e r e a d t a b l e and w r i t e
t a b l e statements may be ineluded in the scripts as w e l l . Y o u can define a table and
1 80 OftT/eASE ACCESS CHAPTER 10
then immcdiately read or write it, as seen in some o f our examples, but a seripi is ofien
more readable if the complex t a b l e statements are segregaied from the statements thai
read and write the tables.
T h e rest of this chapier will concentraie on t a b l e statements. Complete sample
scripts and Access or Excel files for the dict, produetion. and transponation examples can
be obtaincd from the A M P l . websile.
t a b l e labltnanxe I N slring-list^ :
key spre. daSasptc. dala-spec, ... ;
where the optional $trlng~!ist i> specific to the daiahase type and acce^s method being
used. (In the interest of brevity, most subsequent examples do not show a string-liss.)
The key-spec names the kcy columns. and the daki-spec give* the data columns. Data
values are subsequently read from the table into AMPl. entities by the command
r e a d t a b l e inhlt--nome :
which determines the values to be read by referring to the t a b l e dcclaration that defined
íablt-fuimt.
This indicates thai the relational table lua four columns. compriiing a key column FOOD
and data columns c o s t , íjxiín and £_rnax. The data cohimns are associated with
paramcters c o s t , £_snin and £_rr*ax in the curtem AMPl. model. Since there is only
one key column, ali of these paramcters must be indexed over one-dimensional sets.
When the command
read t a b l e Foods
is executed. the relational table is read one row at a time. A i o w ' s entry in the key c o l -
umn is interpreted a subscript to each of the paramcters, and these subscripted parame-
ters are assigned the row'sentries from the associatcd data columns. For example, if the
relational table is
S E C T C N 10.3 R E A D N 3 DATA FTOW R E l A T O N A L T / C t E S 1 81
proceising lhe first r o w aisigns the values 3.19 k> parameter c o s t I ' B E E F ' J, 2 t o
tjxiLnl' B E E F ' ) , and 10 t o £ _ r n a x [ ' B E E F ' ] ; proccssing the second r o w assigns
2.59 t o c o t t f C H K ' ) , 2 t o tjxíixi t ' C H K ' J, and 10 k> £ _ m a x [ ' C H K ' ) ; and s o
for th through the six remaining r o w s .
A t the time thai the r e a d t a b l e command executed. A M P L makes n o aisump-
tions about h o w the parameters are declarcd: they need not be indexed over a sei named
FOOD, and indeed the members o f their indexing sefc may not y e t even be known. O n l y
latcr. when AMF1. first uses each parameter in some computatk>n. does it check the
entries read from key cohimn FOOD *> be sure thai each i* a valkl subscript for thai
parameter.
T h e situalion is analogous for multidimensional parameters. T h e name o f each data
column must also be the name o f an A M P l . parameter. and the dimension o f the
parameier's indexing set must equal the number o f key columns. For example. when t w o
key columns are l&ted within the brackeis:
nnxlel from which this e x a m p l e is taken. the parameters are indexed by { P R O D . 1. .T)
where T is a previousty defined parameter.)
Since a relational table has only one collection o f k e y columns. A M P L applies the
same subscripting t o each o f the parameters named by the data oolumns. T h e s e parame-
ters are thus usually indexed o v e r the same A M P L set. Parameters indexed over similar
sets may also be accomnnxlated in one datahase table. h o w e v e r , by leaving blank any
entries in rows corresponding t o invalid subscripts. T h e way in which a blank entry is
indicatcd is specific t o the datahase software being used.
Values o f u n indexed (scalar) parameters may be supplied by a relational table that has
one r o w and no key cohimns. s o that each data column contains precisely one value. T h e
corresponding t a b l e declaration hai an empty b y - s p e i \ IJ. H>r example. to read a
value f o r the parameter T that g i v e s t h e number o f perkxls in s t e e l T . r > c d . the t a b l e
dcclaratk>n is
table St o e i P e r i o d s IN: [1 . T:
and the corresponding relational table has one column, a b o named T . whose one entry is
a positive integer.
T h e < - symbol is intended ai an arrow pointing in the direetion that the information is
m o v e d . from the key oolumns t o the A M P L set.
T h e simplest case involves reading a one-dimensional set and the parameters indexed
over it, ai in this example for d i e t .sncd:
In this special case only, the kty-spec can a k o be written in the abbreviated form
[FOOD] IN.
A n analogous syntax ti e m p l o y e d f o r reading a multidimensional set along with
parameters indexed over it. In the case o f t r a n s p 3 .rr>cd. for instance. the t a b l e dec-
laration could be:
S E C T C N 10.3 R E A D N 3 DATA FTOW R E L A T O M A L T / C t E S 1 83
c o t ORiQ:
s o t DEST:
.cot L I N K S w i t h i n ( O R l G . D E S r } :
param c o s t ( L I N K S } > = 0:
s e t ORiQ:
s e t DEST:
s e t LINKS = ( O R l G . D E S r } :
param c o s t ( L I N K S } > = 0:
s e t ORIG:
s e t DEST:
param c o s t ( O R I G . DEST} >= 0:
In these latter cases, a t a b l e dcclaration would still be needed for rcading parameter
c o s t , but it would not specify the rcading o f any associatcd set:
Separate relational tables would instcad be used to provide members for the one-
dimensional sets O R I G and DEST and values for the parameters indexed over them.
When a t a b l e dcclaration specifies an A M P L set to be assigned members, its list o f
iluiii-sptcs may be empty. In that case only the key columns are read. and the only action
o f r e a d t a b l e is to assign the key column values ai members o f the specificd A M P L
set. K>r instance, with the statement
a subscquent r e a d t a b l e statement would cause just the values for the set L I N K S to be
read, from the t w o k e y columns in the corrcsponding daiahaic table.
1 84 OftT/eASE A C C E S S CHAPTER 10
Establishing correspondenc es
t a b l e Foods IN:
[FOOD]. c o s t , £_min "" l o w e r l i m . f nvax "" upporlim;
the A M P l . parameters £ _ s n i n and £_rr*ax would be read from data columns loverlin
and u p p e r l i n in the relational table. (Parameter c o s t woukl be read from column
c o s t asbefore.)
A similar ly generali/ed form, index " key-t o!-mime, can be used t o associate a kind o f
dummy index with a k e y column. This index may then be used in a subscript t o the
optional param-mime in one or more duia-speis. Such an arrangement is useful in a
number o f situatk>ns where the key column entries d o not cxactly correspond t o the sub-
scripts o f the parameters that are t o r e c e i v e table values. I lereare three c o m m o n cases.
W h e r e a numbering o f s o m e kind in the relational table is systematically different
f r o m the corresponding numbering in the A M P l . nnxlel, a simple expression involving a
key column index can translate from the one numbering scheme t o the other. For e x a m -
ple, if time periods ware counied from 0 in the relational table data rather than f r o m 1 ai
in the nnxlel, an adjustment coukl be made in the t a b l e declaration as f o l l o w s :
t a b l e S t o e l P r o d I N : l p ~ PROD. t ~ T1MI£| .
m a r k o L l p , t - f l 1 ~ m a r k e t . r e v e n u e [ p . t « - l 1 "" r e v e n u e :
In the second caie, where A M P l . parameters have subscripts from the same sets but in
diíTerent orders. key column vide.tes must be employed t o provide a c o r r e c t index order.
If r i a r k e t & indexed over {PROD. 1. .T) but r e v e n u e ii indexed o v e r ( 1 . . T ,
P R O D } , for example, a t a b l e declaration k> read values f o r these t w o parameters should
be written ai follows:
t a b l e S L e e l P r o d I N : l p ~ PROD. t ~ T1MK| .
market. r c / o n u c l t ,p | ~ rc/cnuc;
Final ly, where the values for an A M P L parameter are divided amt>ng several datahase
columns, k e y column indexes can be employed t o describe the values k> be found in each
column. K>r instance. if the r e v e n u e values are given in one cohimn for • b a n d s " and
in another column for ' c o i l s ' , the corresponding t a b l e declaration could be written
like this:
S E C T C N 10.3 R E A D N 3 DATA FTOW F E L A T O N A L T / € i _ E S 1 85
t a b l e S t e e l P r o d I N : [ t ~ TIMlíJ .
rcvcnuc ("bands", t j ~ revbands.
revenue l " c o i l s " . t l " revcoils:
where the optional $trlng~!ist i> specific to the database type and acce%s method being
used. <Again, most subsequent examplesdo not includea string-Ust.) AMP1.expression
values are subsequently w r i l e n to the table by the command
write t a b l e òtihlename ;
which uses the t a b l e declaration that defined table-nome to determine the informalion
t o b e wrhten.
A t a b l e declaration for writing specifies an externai file and possibty a relational
table within that file, ehher explicitly in the string-iist or implicitly by default mies. Nor-
mally the named externai file or table is created if h does not exist. or is overwritten oth-
er wise. T o specify that instead ccrtain columns are to be repbced or are to be added toa
table, the t a b l e declaration must incorporai? one or more daia-spec& that have
read/write staius I N or IKOUT, as discussed in Section 10.5. A specific table handler
may also have ifc own more detailed rules for determining when files and tables are mod-
ified or overwritten, ai expiained in itsdocumentation.
T h e key-spec* and data-sptez o f t a b l e declaraiions for writing externai tables super-
ficially resemble those for reading. The range o f A M P L expressions aQowed when writ-
ing ti much broader, however, inchiding esáentially ali set-valued and numeric-vahied
expressions. Moreover, whereas the table rows to be read are those of some extsting
table, the rows t o be wrhten must be determined from A M P L expressions in some pan of
a t a b l e declaration. Specificaily, rows to be written can be inferred either from the
daia-spet s, using the same oonventions ai in d i s p l a y c\>mmands, i>r from the key-spec.
Each of these ahernatives employs a characteristic t a b l e syntax a* described below.
Tables corrcsponding to higher dimensional sets are handkrd analogously, with the num-
bcr of bracketcd key-column names listed in the key-sptc being equal to the dimension o f
the items in the data-spec. Thus a table containing the results from s t e e l T . r > c d could
be defined as
T w o rows are empty in the columns for Jíake and S e l l , because { " b a n d s • . 0 } and
{"coils'.Oí are not members of the index sets o f >Cake and S e l l . Weusea"."
here to indicaie the empty table entries. but the actual appearance and handling of empty
entries will vary depending on the datahasesoftware being used.
l f this form is applied k> writing sufllxed variable or constraint names, such as the
dual and slack values relaied to the constraint D i e t :
t a b l e N u t r s CTJV: [ N u t r i e n t l .
Diet . I s l a c k . D i e t . l d u a l . D i e t . uslack. Diet.udual: 4 KRROR
188 OftT/eASE ACCESS CHAPTER 10
a m p l : i f r i t o tablo NUtra;
l i r r o r CXKTULing " w r i t e t a b l o " conmand:
lirror w r i t i n g Uiblc Nutrs with t a b l e handler ampl.odbc:
C o l u m n 2 ' s name " D i e t . l s l a c k " c o n t a i n s n a n - a l n h a n u m e r i c
character
This situation requires that each A M P l . exprcssion bc f o l l o w e d by the opor ator " and a
corresponding valid column name for use in the relational table:
t a b l e N u t r s CTJV: [ N u t r i e n t l ,
D i e t . l s l a c k ~ lb_slack. Diet. ldual ~ lb_dual.
Diet.uslack ~ ub_slack. Diet.udual ~ ub_dual:
La b l e P u r c ha s e s O l/r: l FoDdHame 1 .
Buy *" s e r v i n g s . ( j i n FOOD} 100* B u y l j 1 / l max l j 1 ~ percent:
Either w a y , since both liuitt-spus g i v e expressions indexed o v e r the A M P l . set FOOD, the
rcsuhing table has one r o w for each member o f that s e t
SECT ON 10.4 V « T N 3 D A T A TO R E I A T O N Í L T/CLES 189
The expression in a dtila-spec may also use operaiors üke s u n lhai define their own
dummy Índices. Thus a table o f lotai pr cxluction and sales by period for s t e e l T . r > c d
oould be specified by
L a b l e S t o o l T o t a l CTJV : [TIMKl.
( t i n 1 . . T } (sum ( p i n PROD} M a k e l p . t 1 ~ Made.
sum ( p i n PR0D> S e l l l p . t l ~ SoldJ:
As a two-dimcnsional example. a table of the amounts sokl and the fractions of demand
met could be specified by
The resulting externai table would have key columns PROD and T I M E . and data columns
S e l l and F r a c D e r w i n d .
In contrait to the ar row < - that points from a key-column list lo an AMPL set, indicating
values to be read into the set, this form uses an arrow - > that points from an AMPL set to
a key column list, indicating information t o b e written from the set into the key columns.
A n c x p l i c h expressk>n for the row index set is given by the \ei-sptc, which can be the
name o f an A M P L set or any AMPL set-expression enckxsed in braees { } . The tey-col-
spees give the namcs o f the corresponding key columns in the datahasc. Dummy Índices,
if nccded, can appear ehher whh the sel-spec or the -*•«>/-.y** rs. as we will show.
T h e simplest caie of this form involves wrhing databaic columns for nnxlel compo-
ncnts indexed over the same one-dimensional set, as in this example for d i e t .r>cd:
the like-named data columns. <K>r the data used in our diet example. the resulting table
\vould be the same ai for the F c c d K a m e table given prevk>usly in this scction.) If the
key column has the same name, FOOD, as the AMPL set. the appropriate t a b l e declara-
tion becomes
In this speeial case only, the kty-spec can a b o be written in the abbreviated form
[FOOD] OUT.
T h e use of " whh AMPL name* and suHlxed names is governed by the consideraiions
previously described. sothat theexample o f diet slack and dual values would be written
These two forrni are eqüivalem. Either way, ai each row is written, the index j takcs the
key column vahie, which & used in interpreting the expressions that give the values for
the data columns. K>r our example. the resulting table, having key column F c c d K a m e
and data columns a e r v i n g s and p e r c e n t , is the same ai previously shown. Simi-
lar ly, the prevk>us example of the table S t e e l T o t a i could be written as either
t a b l e S t e e l T o t a i CTJV: ( t i n 1. . T } ITIMKJ.
sum ( p i n PROD} Make [ p . t l ~ Made.
sum ( p i n PROD} S e l l l p . t l ~ S o l d :
The resuh will have a key column T I M E containing the iniegers 1 through T , and data
columns Síade and S o l d containing the values of the two summations. (Notice that
SECTCN 10.5 F E A D N 3 A f © V « 7 N 3 T H E S A I « 1ABLE 191
This resuh is not quite the same as the table produced by the previous S t e e l P r c d
example. because the r o w s ii> be w r i t e n here correspond explicitly t o the members o f the
set { P R O D , 1 . . T ) , rather than being inferred from the indexing sets o f J í a k e , Sell,
and I n v . In particular, the vahics o f I n v [ ' b a n d s ' . 0 ] and I n v [ ' c o i l s ' . 0 ] d o
not appear in this table.
T h e options for d u m m y Índices in higher dimensions are the same as in one dimen-
sion. Thus our e x a m p l e S t e e l S a l e s could be wrhten either using dummy Índices
defined in the sét-spee:
t a b l e S t o e l S a l c s CTJV:
( p i n PROD. t i n 1. .T> - > l PROD, T I M K j .
S o l l lp. t ] ~ s o l d . S c l l l p . t | / m a r k e t l p . t l v mel.:
t a b l e S t o e l S a l c s CTJV:
(PROD. 1 . . T } l p ~ PROD. t ~ T l M I í J .
Selllp.tl ~ s o l d . S o l l l p . t | / m a r k o t lp. t j v mel.:
If dummy Índices happcn t o appear in both the stí-spee and the key-cal-speih ones in the
kf y - c a l - s p e i * take precedence.
and others n> bc written. This sectk>n gives examples and instructions for both o f these
possibilitas.
A single externai table can be read by one t a b l e declaration and later written by
another. T h e t w o t a b l e declarations f o D o w the m i e s for reading and writing given
above.
In this shuation. h o w » ver. one usually wants v r i t e t a b l e t o add or rewrite
selected columns, ralher than ovar writing the entire table. This preference can b e c o m -
municated t o the A M P L table handler by including input as w d l ai output columns in the
t a b l e declaration that t% to be used f o r writing. Columns intended for input t o A M P L
can be distingutihed from those intended for output t o the externai table by specifying a
read/wrhe statuscohimn by cohimn <rather than f o r the table ai a whole).
A s an example. an externai table for d i e t . r > o d might consist o f columns cost,
tjxiixi and f _ r n a x containing input for the nnxlel. and a cohimn B u y containing the
resuhs. If this ti maintained ai a Microsoft A c c e s s table named D i e t within a file
d i e t . m d b , the t a b l e declaration for reading data into A M P L coukl be
then ali o f the data cohimns in Access table D i e t would have been deleted by v r i t e
t a b l e F o o d O u t p u t , but the a 1 terna tive
would have only overwritten lhe column Buy, a* in the example \V>Í original ly gave, since
there is a daia column < naniely Buy itselí) lhat does not have readAvrile status OUT. (The
default, when nostaius is given, is I K O U T . )
In many cases, ali of the informaiion for both reading and writing an externai table
can be specified in the same t a b l e declaration. The key-spee may use the ar row < - to
read contento of the key columns into an AMPI. set. - > k> wrhe members o f an AMPI. set
into the key columns, or < - > to do both. A dukt-.yjec may specify read/write staius I N
for a column that will only be read ink> A M P L OUT for a column that will only be writien
out from A M P L i>r IKOUT for a column thai will be both read and writien.
A r e a d t a b l e kiMe-mune command reads only the key or daia columns thai are
specified in the declaration o f table-ntime as being I N or IKOUT. A write table
table-name command analogously wrhes to only the columns thai are specified as OUT or
IKOUT.
A s an example, the declaralions defining F c c d l n p u t and F o c d O u t p u t above
could be replaced by
AMPI. table dcclaratk>ns can be indexed in much the same way as sets. parameters,
and other nnxlel components. An optk>nal (indexing-expr) follows the table-mune:
im DietScn* : Datnfcasii H 0 E3
E SSensBECF!
• ... ... '
••
5w i>PÍ5íi Kl
E SsmHAM
SmMCH
• SensMTl
• ScrwSPC
One table is defined for each member o f the set specified by the indexing-txpr. Individ-
ual tables in this collection are dcnoted in the usual way, by appcnding a bracketed sub-
script or subscriptstothe Uible-numt.
A s an example, the following declaration defines a coDectionof AMPl. tables indexed
over the set o f foods in d i e t .rr»cd, each table corresponding t o a ditVcrcni database table
in the Access file D i e t S e n a .rr^ib:
t a b l e D i e t S e n s ( j i n FOOD}
OUT "ODOLT" - D i e t S e n s . m d b " ( " S c n s - & j J:
[ F o o d l . £ _ m i n , Buy. £ nvax;
Following the mies for the standard (MDBC table handler, the Access table names are
given by the third item in the string-Üst* thestring expressk>n { " S e n a • & j ) . Thus
the A M P l . table D i e t S e n s [ ' BEEF• ] is associated with the Access table S e n s B E E F ,
the AMPl. table D i e t S e n s [ • C H K i ] is associated whh the Access table SensClOC, and
so focth. T h e following A M P l . script uses these tables to rccord the optimal diet when
there is a two- for-the-price-of-one sale on each o f the foods:
for ( j i n FOOD} (
l e t c o s t l j l : = c o s t l j 1 / 2:
solve;
write table DietSensljl:
l e t c o s t l j l : = c o s t l j1 * 2:
>
SEC7 CN 10 6 N C É X H } CCLLECT CT*S CF TABLES M ) OOLUWttS 195
m DidScna
•
RuvWTI | riiiyS
3EEF 10 " =681492 6.967774? 5 3906110 5.360613= 5.3t0B138 5 77!
•JHK 2 b J/JBm 2 2 X
2 2 1D : 2 ">
-.AM 7.0164474 10 13 tu IC 1U
VICH in 10 n -n IC 10 =5=8?
• VÍTL 10 10 13 í0 IC 10
SPG G6557D1B 2 7 7EQ5584 9. 20605/9 9 3060525 9
Tur. 2 2 2 2 L 2
F o r the data in d i e t 2 a . d a t . the set FOOD ha* cight members. so eight tables are writ-
ten in the Access database. as seen in Figure 10-5. I f instead the t a b l e dcclaration w e r e
t o g i v e a string exprcssion f o r the second string in the \tring-li>ãn which specifies the
Access filename:
t a b l e D i e t S o n s ( j i n FOOD}
OUT -ODBC- ( " D i e t S e n s " U j U " . m d b " J :
[ F o o d l j £ _ m i n , Buy. £ nvax:
then AMPl. would write eight diíTerent Access databaie files, named
D i e t S e n a B E E F . r r * i b . D i e t S e n â C H K . n d b , and so forth, each cx>ntaining a single
table named (by d e f a u l t ) D i e t S e n s . ( T h e s e files must have been created before the
w r i t e t a b l e com mands are exccuted.)
A string exprcssion can be used in a similar way to make every member o f an indexed
collectk>n o f A M P l . tables corrcspond t o the same Access table, but with a different duhi-
col-nuntt for the optimal amounts:
T h e n running the script shown above will result in the A c c e s s table o f Figure 10-6. T h e
A M P l . tables in this case were deliberately left with the default read/wrhe status, I K O U T .
I l a d the read/write status been specified as OUT, then each w r i t e t a b l e would have
overwritten the cohimns created by the prevk>us one.
1 9 6 OftT/eASE ACCESS C H A P T E R 10
X Microsoft E x c d - D K * 2 D . I U H H •
j^J &ft VÍÍH Vcuit Fnnnçt Tccfe Mito." tt® Hrfp -ÍSl *l
G H 1 j K L M N 0 P
—
—
J j
y NUTR nrrF chk FISH MAfJ MCH àin SPG TIIR
3 A tu a 8 4J 1t> ;u 2: bJ
01 10 20 IC 15 15 —
5 Ml 'ô JJ 1Q 1J 15 16 1D
6 C :o 0 IC •13 !6 30 50 2D
7 MA 9.-8 21 ao 273 1152 ase 1322 1397
8 CAL 2SS 4C 3íS •100 27Q 45J
9 v I
• Nftjfet/ M M T
The key-spec (i " N U T R ] associates the first table cohimn with the set NUTR. The
dtiio-spêc { j i n FOOD) <...> causes A M P L to generate an individual dtiht-spee for each
member o f set FOOD. SpecificaDy, for each j i n FOOD, AMPL generaies the dutii-spec
amt [ i . j 1 " { j } , where { j > is the AMPL string expression for the heading o f the
externai table column for food j , and a m t [ i . j ] denotes the parameter to which the vai-
S E C T C N 10.7 Sltt&AFG A N D E U L T N 1ABLB K f t M X E R S 197
ues in that column are to be written. < According ii> the convention used here and in other
A M P L declarations and commands. the parentheses around { j > cause it to be interpretcd
av an expression for a string: without the parentheses it would denote a column name con-
sisti ng of the single character j . )
A similar approach works for writing two-dimensional tables k> spreadsheets. As an
example. after s t e e l T . r > c d is solved. the results could be written to a spreaJsheet
using the following t a b l e declaration:
t a b l e R c s s u l t s l OUT -0DBC" - s s t e c l l o u t . x l s - :
( p i n PROD} [Productl .
I n v l p . 01 ~ InvO,
( t i n 1 . . T } < M a k e l p . t l ~ < ' M a k e ' Sc t ) .
S e l l l p . t l ~ < ' S o l 1 ' Sc t ) .
invlp.tl ~ <• i n v • Sc t j > :
t a b l e R c i = u l t s 2 OUT -ODBL- - s s t e c l 2 o u t . x l s - :
iProductl .
( p i n PROD} i n v l p . 0 1 ~ I n v O .
( t i n 1 . . T } < ( p i n PROD} ( M a k e l p . t l ~ (• Mako* Sc t j .
S e l l l p . t l ~ <' S o l 1 ' Sc t j .
invlp.tl ~ <• i n v • Sc t j J > :
The key column labels the rows with product names. The data columns include one for
the initial inventories. and then three representing produetion. sales, and inventories.
respectively, for each period. as in Fjgure 10-8. Conceptually, there is a symmetry
between the row and column indexing of a two-dimensional table. But because the tables
in these examples are being treatcd asrelational tables. the t a b l e declaration must treat
the row indexing and the column indexing in diíTerent ways. As a resuh. the expressions
dcscribing row indexing are substantially diíTerent from thosc describing column index-
ing.
A s these examples suggest. the general form for specifying an indexed oollectioit o f
table columns is
where each tkiht-spêc has any o f the forms previously given. H>r each member of the set
specified by the mdexing-txpr. AM PI. gener ates one copy of each dusu-spec within the
angle brackefc <...>. The indêxing-tx/>r a k o defines one or more dummy índices that mn
over the index set: these Índices are used in expressions within the dnki-spet% and also
appear in string expressk>ns that give the names of columns in the externai databa^e.
|
H:4 • H\RC»U*»I Á R*gJts2 / M l >jr
AMPL isdistributed with a "standard*' table handler that mas under Microsoft Windows
and oommunicates via the Open Databaie Connectivity (ODBC) application programming
interface: it recognizes relational tables in the formais used by Access. Excel, and any
other applicaiion for which an ODBC driver extsts on your computar. Additk>nal handlers
may be supplied by vendors o f A M P L or ofdataba&e software.
In addition to any supplied handlers, minimal ASCII and binary relalional table file
handlers are built into A M PI. for testing. Vendors may inchidc other built-in handlers. I f
you are not sure which handlers are currently seen by your copy o f AMPL. the features
described in A . 13 can get you a list o f active handlers and brief instmctions for using
them.
A s the introductory examples o f this chapter have shown, AMPL communicates with
handlers through the tiring-list in the t a b l e declaration. The form and interpretalion of
the string-ti\t are specific to each handler. The remainder o f this section describes the
string-listo that are recognized by A M P L ' s standard ODBC handler. Following a general
introduction, specific instmctk>ns are provided for the two applicaiions. Access and
Excel, that are used in many of the examples in preceding sections. A final subsection
describes the string-lists recognized by the built-in binary and ASCII table handlers.
In the context of a declaration that begins t a b l e tablt-name ..., the general form of
the string-list for the standard ODBC table handler is
The first string tells AM PI. that data transfers using this table declaration should cmploy
the standard ODBC handler. Subsequent strings then provkfte directions to that handler.
Theseoond string identifies the externai databccie file that is to be read or wrhtcn upon
execution of r e a d t a b l e U t M e - m u n e or v r i t e t a b l e lable-mune commands. There
are several pcxssibiliiies. depending on the form o f the conntillon-sptc and the configura-
t i o n o f OOBCon your oomputer.
I f the conntetían->pec is a filename o f the form mune.eü. where exs is a 3-letter
extensk>n associaied with an insta D ed ODBC driver, then the named file is thedatahase
file. This form can be seen in a number o f our examples. where filenames of the forms
mune . TV.ib and mime . x i s refer to Access and Excel files, respectively.
Other forms of cunnecSum-spec are more specific to ODBC, and are explained in
online documentation. Information about your oomputer's configuration o f ODBC
drivers, data source names. file data sources. and rebtcd entities can be examined and
changed through the Windows ODBCcontiol panei.
T h e third string normally gives the name o f the rebtk>nal table, whhin the specified
file. that is to be read or written upon execution o f r e a d t a b l e or v r i t e t a b l e com-
mands. If the third string is omitted. the name of the relational table is taken to be the
same as the kihle-mime o f the containing t a b l e dcclaration. For wrhing. if the indi-
cated table does not exist, h is crcated: if the table exists but ali o f the table
declaration*s iluki-.yecs have read/write status OUT. then it is ovcrwrittcn. Othenvise,
wrhing causes the existing table to be modificd: each column written ehher ovcrwritesan
existing column of the same name, or becomes a new column appended to the table.
Ahernatively. if the third string h ^ thespecial form
the table declaratk>n applies to the relatk>nal table that is (temporarily) created by a state-
ment in theStructurcd Query Language, commonly abbreviated SQL. Specifically. a rela-
tional table tv first constmcted by cxccuting the SQL statement given by sql-query, with
respect to the datahatc file given by the second string in the t a b l e dacI ara tion'sstrlng-
lia. Then the usual interpretaiions o f the t a b l e declaration are applied lo the con-
stmcted table. AH columns specified in the declaration should have readAvrite status I N .
since h would make no sense to write to a temporary table. Normally the sql-query is a
SELBCT statement which is SQL's primary devkre for operating on tables tocreate new
ones.
A s an example. if you wanted to read ai data for d i e t . m o d o n l y those foods having
a cost of S2.-J9 or leis. you could use an SQL query to extract the relevant reootds from
the F o o d s table of your database:
Then to read the relevant data for parameter arnt. which is indexed over nutrients and
fcxxls. you would want to read only thosc recocds that penaincd toa food having a cost o f
200 OAT/eASE A C C E S S C H í f T Ç R 10
S2.-I9 or less. Ilere is one way that an SQL query could be used to extract the desired
records:
Ilere \v\r have used an AMPL option to store the string containing the SQL query. Then
the table dec!aration's third string can be given by the relatively short string expression
•SOL=' &SselectAmts.
T h e string v e r b o s e after the first three strings requests diagnostic messagcs — such
ai the DSN= string that ODBC repor ts using — whenever the containing table declaration
isused bya r e a d t a b l e or v r i t e t a b l e command.
Using the standard ODBC table handler with Access and Excel
The file named by the second string must exist. though for writing it may be adatahase
that does not yet conta in any tables.
T o set up a relatk>nal table cor responde ncv for reading or writing Microsoft Excel
spreadshcets. specify the exi in the sec\>nd string o f lhe string-lití ai x i s :
In this case, the sec\>nd string identifies the externai Excel \w>rklxx>k file that i s t o be read
or written. For writing. the file specified by the second string is created if h does not
existalready.
T h e external-tabk-spec specified by the third string identifies a spreadsheet range,
within the specified file, that is t o b e read or written: if this string is absent. it istaken to
be the tuble-nnme given at the start o f the t a b l e declaration. R>t reading. the specified
range must ex&t in the Excel file. For writing. if the range does not exist, it is created, at
the upper left of a new workshect having the same name. If the range exists but ali o f the
table declaration's diitit-$>ecz have read/write status OUT, it is overwritten. Otherwise.
writing causes the existing range to be modified. Each cohimn written either overwrites
an existing column o f the same name. or beeomes a new column appended to the table:
each row written either overwrites entries in an existing row having the same key column
entries. or beeomes a new row appended k> the table.
When writing causes an existing range to be extended. rows or columns are addcd at
the bottom or right of the range, respectively. The cells of addcd rows or columns must
be empty: otherwise, the attempt to write the table fails and the v r i t e t a b l e command
S E C T C N 10.7 S T A N D EULT N 1ABLB K f t M X E R S 201
elicits an error message. After a table is successfully written. the cor respondi ng range is
created or adjusted t o contain exactly the c e l b o f that table.
For debugging and demonstra ti on pur poses. A M P L ha* built-in handlers f o r t w o very
simple relational table formate. These formais store one table per file and c o n v e y eqüiva-
lem informaiion. O n e produces A S C I I f i l e s that can be examined in any text editor, while
the other creates binary files that are much faster t o read and write.
For these handlers, the t a b l e declaration's string-lisi contains at most one string.
identifying the externai file that contains the relational table. If the string ha> the f o r m
-fUrnamt. Lab -
-fútnt\n\r. b i t **
ampl: c o d o l diot.xaod;
ampl: data diot2a.dat;
ampl: aolvo;
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
13 i t c r a t i o n s . o b j o c t i v c 1 1 B . 0 5 9 4 0 3 2
a m p l : tablo RoaultLiat OUT "DiotOpt .tab"1
ampl? [FOOD], Buy, Buy.rc, { j in FOOD) Buy[j)/f xaax[j);
a m p l : i f r i t o tablo RoaultLiat;
ampl. t a b 1 3
FOOD Buy B u y . r c • Buy l j 1 ti m a x [ j | •
BKKF 5 . 3G0G13B107 417 01 B . B B 1 7 B 4 1 9 7 0 0 1 2 5 2 c - 1 G 0 . 5 3 G 0 G 1 3 B 1 0 7 4 1 7 0 1
CiJX 2 1 . 1 B B B 4 0 5 7 9 7 1 0 1 4 0 2 0 . 2
F1S11 2 1 . 1 4 4 4 0 7 5 0 2 1 3 1 2 B 5 G 0 . 2
11AM 10 - 0 . 3D2G5132139B12223 1
MCU 10 - 0 . 5 5 1 1 5 0 B 9 5 1 4 0 G G 5 B 1
>TI'L 10 - 1 . 32B9002 557 54 474 5 1
SPG 9 . 3 0 G 0 5 2 B 5 5 9 2 4 9 7 3 - B . B B 1 7 B 4 1 9 7 0 0 1 2 5 2 c - 1 G 0 . 9 3 0 G O 5 2 B 5 5 9 2 4 9 7 3
TUR 1 . 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 B 2 . 7 3 1 G 1 9 7 7 B 3 4 G 1 1 7 G 0 . 1 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 B
202 OAT/eASE A C C E S S C H í f T Ç R 10
In the first line. a m p l . t a b identifiesthisasan AMPI. relalional table lext file, and is fol-
lowxxl by the numbers o f key and non-key columns, respeetively. The second line gives
the names o f the table's columns, which may be any strings. (Use o f the " operak>r to
specify valid column-names is not necessary in \ht% case.) Each subsequent line gives the
values in one table row: numbers are wrhten in full precision, with no special formaning
or alignment.
Copyrisht O O T by Robcrt Fourcx, David XLGayand B r i » W . K o n ç l a n
11
Modeling Commands
203
204 MOC€LN3 COUVA!*y$ CHOTERI1
Commands
I f you are using a tcxt-b&icd interface, after staning AMPL. the first thing you should
see is A M P L ' s prompt:
ampl:
Whenever you see thfc prompt AMPI. is ready to read and inierprct what you type. As
with must command inierpreters. AMPI. waits until you press the " e n t e r " or "return"
key, then processes everyihing you typed on the line.
A n AMPI. command ends with a scmicolon. lf you enicr one or more complete c o m -
mands on a line. AMPI. processei them. prints any appropriate messages in response, and
issues the a m p l : prompt again. lf you end a line in the middle of a command. you are
promptcd to continue it on the next line: you can tell that AMPI. is prompting you tocon-
tinue a command. because the prompt ends with a qucstion mark rather than a colon:
You can type any number ofcharactcrson a line <up to whatever limh youroperating sys-
tem might impose), and can continue a command on any number of lines.
Several commands use filcnames for reading or writing informal ion. A filenamecan
be any sequence of printing characters <except for scmicolon ; and quotes • or ' ) or any
sequence of any characters enclosed in maiching quotes. The mies for correct filenames
are deter mine d by the operaiing system. howvrver. not by AMPI.. R>r the examples in this
lxx>k wvr have used filenames like d i e t .r>cd that are acceptable k> almost any operaling
system.
Toconcludcan AMPI. session, type e n d o r q u i t .
I f you are running AMPI. from a graphical interface, the details of your interaction
will be different, but the command interface is likely to be accessiblc. and in fact is being
used behind the scenes ai w d l , so it's well worth understanding how k> use h elYectively.
Options
T h e behavior of AMPI. commands dependi not only on what you type directly, but on
a variety o f options forchoosing alternative solvers, controlling the display of results. and
the like.
Each option hai a name. and a value that may be a number or a eharacier string. For
example. the options prornpt 1 and prornpt2 are strings thai specify the prompts. The
option d i s p l a y _ w i d t h hai a numerk.* value. which says how many characters wkle
the output pnxlucvrd by the d i s p l a y command may be.
T h e o p t i o n command d&playsand sets option values. lf o p t i o n is foDowed by a
list of option names, AMPI. replies with the currcnt values:
S E C T C N 11.1 G E N 9 V U . P R N C R ^ S CF O O V V / * C < S A f O C P T O U S 205
a m p l : optlon prcts*;
opLion promptl 'ampl:
o p L i o n prompt2 'ampl? ';
ampl:
The command o p t i o n or just o p t i o n alone. lists ali current options and values.
When o p t i o n t> followed by a nanie and a value. it resets the named option k> the
specified vahie. In the foDowing example w e c h a n g e the promptand the d&play width.
and then verify that the latter ha* been changed:
You can specify any string vahie by surrounding the string in matching quotes or
' . . . ' av above: the quotes may be omhted if the string loolcs like a name or number.
T w o consecutivo quotes </ ' or • ' ) denote an empty string. which isa meaningful vahie
for some options. At the other extreme, if you want k> spreaJ a long string over severa!
lines. place the backsbshcharacter \ at the e n d o f each intermediate line.
When A M P L starts, it sets many options to initial, or default, values. The p r o r n p t l
option is initialized to ' â n p l : ' . for instance. so prompts appcar in the standard way.
The d i s p l a y — w i d t h option has a default value o f 79. Other options. espeeially ones
that penain *> particular solve rs, are initially unset:
The o p t i o n state ment a b o doesn't check to see if you have assigned a meaningful value
to an optk>n. You will be informed o f a vahie error only when an option is used by some
subsequent command. In these respects. AMPL options are much like operating system or
shell "environmcnt variables." In fact you can use the senings o f environment variables
toovenride A M P L ' s option defaults: see your system-speeific documentation for detaib.
206 MOC€LN3 COUVA!*y$ CHOTERI1
A M P L maintains a ''current" nnxlel. which isthe one that will be sent to the solver if
you type s o l v e . At the beginning of an interactive session. the current nnxlel isempty.
A m c d e l command reads declarations from a file and adds them to the current mixlel: a
d a t a command reads data statementv from a file to supply values for components
already in the current nnxlel. Thus you may use several m c d e l or d a t a commands to
build up the descriptk>n of an optimi/ation problem. reading different parts of the nnxlel
and data from dilTerent files.
Y o u can also type parts of a nnxlel and its data directly at an A M P L prompt. Mixlel
declarai kxns such as p a r a r á v a r and s u b j e c t t o act as commands that add compo-
nents to the current nnxlel. The data statements o f Chapter 9 a b o act as oommands,
which supply data values for already defined components such ai sets and parameters.
Because nnxlel and data statements kx>k much alike, howxrver. you need to tell AMPL
which you will be typing. A M P L always starts out in "nnxlel n n x l e " ; the statement
d a t a (without a filename) switches the interpreter to "data mode'\ and the statement
m c d e l (without a filename) switches it hack. Any command < like o p t i o n . s o l v e or
s u b j e c t t o ) that does not begin like a data statement also has the efTect of switching
data nnxle hack to nnxlel nnxle.
I f a nnxlel declares more than one objective funetion. AMPL by default passes ali of
them tothe sol ver. Mt>st solvers deal only with one objective functk>n and usually select
the first by default. The o b j e c t i v e command lets you select a single objective fune-
tion to pass to the solver: it consias o f the keyword o b j e c t i v e followed by a name
from a m i n i m i z e or m a x i m i z e declaration:
ob j o c t i v e To t a l Linbcr :
If a nnxlel ha* an indexed collection of objectives. you must supply a subscr ipt to indicate
which one is to be chosen:
o b j o c t i v c To t a l _ C o s t l - A&P * 1 :
S E C T C N 112 S E T T N 3 U F A N D S C L V P*3 W O C & S A N D D A T A 207
The uses o f multiple objectives are ilhistrated by two examples in Section 8.3.
Solving a model
ampl: c o d o l Btoolá.aod/
a m p l : data ataal4.dat;
ampl: lot avail ['rahoat') i - 10;
ampl: aolvo;
p r e s o l v e : c o n s t r a i n t Time [ • r c h o a L * l cannoL h s l d :
bDdy < = 1 0 c a n not b e > = 1 1 . 2 5 ; d i f f c r e n c e = -1.2S
For these cases you should cônsul t the detailed description of presolve in Section 14.1.
T h e generated optimi/ation problem. ai possibly modifiod by presolve. is finally sent
by A M P L to the solver o f your choice. Every version o f AMPL is distributed with some
default solver that will be used automaticaDy if you give no other instmctk>ns: type
o p t i o n s o l v e r t o s e e its name:
a m p l : option aolvar;
o p t i o n s o l v e r minos:
If you have more than one solver, you can switch among them by changing the s o l v e r
option:
ampl: raaot;
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e S1S033
1G d u a l s i m p l e x i t e r a t i o n s ( 0 i n p h a s e 1J
ampl: raaot;
ampl: aolvo;
SNOPT 6 . 1 - 1 : O p t i m a l s o l u t i o n í o u n d .
I S i t e r a t i o n s . o b j e c t i v e S15033
In this example w e reset the problem between solves. s o thai the solvers are invokcd with
the same initial condi tk>as and their performance can be compared. Without reset, infor-
mation about the solutk>n found by one sol ver w\>uld be passcd along t o the next one.
possibly g i v i n g the latter a substantial advantagc. Passing informai ion from one solve
t o the next is most use fui when a series o f similar L P s are t o be sent t o the same solver:
we discuss this c a i e in more detail in Section 142.
A l m o s t any solver can handk- a linear program, although those speeifically designed
for linear programming generally g i v e the best performance. Other k i n d s o f optimi/ation
problems. such as nonlinear (Chapter 18) and integer (Chapter 2 0 ) , can be handled only
by solvers designed f o r them. A message such as " i g n o r i n g integrality'' or " c a n ' t han-
dle nonlinearhies' * is an indication that you have not chosen a solver appropriate f o r your
nuxlel.
I f your optimization problems are not t o o difllcuh. you should be ablc t o use A M P l .
without referring t o instmetions for a speeific solver: set the s o l v e r option appropri-
ately. type s o l v e , and wait for theresults.
I f your solver takes a very long time t o return whh a solution, or returns t o A M P l .
without any " o p t i m a l s o l u t i o n " message. then it's time t o read further. Each solver i s a
sophisticated coDection o f algorithms and algorhhmic strategies. from which many c o m -
binations o f c h o i c e » can be made. For most problems the solver makes gcxxl choices
automatically, but you can also pass along your o w n choices thxough A M P l . options. T h e
details may vary with each solver, s o f o r more information you must loolc t o the sol ver -
s p e c i f i c instmetions that accompany your A M P l . software.
I f your problem takes a k>ng time t o optimize, you will want some e v i d e n c e o f the
s o l v e r ' s progress t o appcar on your screen. Directives for this purpose are also dcscribed
in the sol ver-speeific instmetions.
S E C T O N 11.3 W C D F Y N 3 DATA 209
Resetting
T o delete the current data for several nxxlcl componcnts. whhout changing the current
nnxlel itself, use the r e s e t d a t a cx>mmand, as in:
Y o u may then use d a t a cx>mmands t o read in new values for these sets and parameters.
T o delete ali data, type r e s e t data.
T h e u p d a t e d a t a c o m m a n d works simílarly. but does not actually delete any data
until new values are assigned. Thus if you type
but you only read in n e w values for X I N R B Q , a m t and n _ m i n , the previous values f o r
X A X R B Q and n _ s i a x wfll remain. If instcad you used r e s e t d a t a , X A X R E Q and
n _ r n a x would be without values. and you would get an error message when you next
tried t o s o l v e .
Resampling
param a v a i l ( s i n 5>rAGK} =
Jtormal < a v a i l mean l e i . a v a i l _ v a r i a n c e [ c l ) ;
param a v a i l mean : = r e h e a t 35 r o l l 40 ;
param a v a i l _ v a r i a n c e : = r e h e a t 5 r o l l 2 :
then A M P L will take n e w samples from the K o r m a l distribution after each reset
data. Different samples result in dilTerent solutions, and hence in different optimal
objective values:
210 MOC€LN3 COUVA!*y$ CHOTERI1
a m p l : diaplay avail/
rchcaL 3 2 . 3 504
rol1 43.03B ;
a m p l : diaplay avail/
rchcaL 32.0306
rol1 32.6BSS ;
ampl: aolvo;
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
S i t c r a t i o n s . o b j o c t i v c 74.273B2022
Relaxing the bound k> 11 reduaü the cost somewhat but further relaxation apparently
hav nobenefit.
S E C T - O N 11.3 WCDFYN3QATA 211
ampl: l o t T *» 3j
ampl: aolvo;
lírror C X K T U L ii>g • s o l v e - cccnnvand:
error p r o c c r . s i n g param a v a i l :
i n v a l i d s u b s c r i p t a v a i l 141 d i s c a r d o d .
error p r o c e s s i n g param m a r k e t :
2 invalid subscripts discarded:
m a r k e t l ' b a n d s ' ,41
marketl'coils'.41
error p r o c e s s i n g param r e v e n u e :
2 invalid subscripts discarded:
r e v e n u e l ' bands ' . 4 1
revenue l' coi l s '. 4 1
error processing var S e l l [ ' c o i l s 1 J :
i n v a l i d s u b s c r i p t m a r k e t l ' b a n d s * .41
T h e problem here is that A M P L still ha* current data for 4 t h - w x k parameters such as
a v a i l [ 4 ] , which ha* beeome invalid with t h e c h a n g e o f T *> 3. I f y o u want t o p r o p e r l y
reduce the number o f w e e k s in the linear program while using the same data. you must
declare t w o parameters:
p a r a m T d a t a i n t e g e r > 0:
param T i n t e g e r < = T d a t a :
is what happens when we solve for lhe optimal diei ai above. then round lhe optimal
solution d o w n t o lhe next lowest integer number o f packagcs:
n m i n D i c t _ M i n . s latz k
A 700 231
Bl 0 seo
B2 0 47S
C 700 -40
CAL 1G000 -640
Beeause we have used l e t t o change the values o f the variables, the objective and the
slacks are automaiically computed from the n e w , rounded vahies. T h e cost has dropped
by about $ 3 3 0 , but the solution is n o w short o f the requirements for C by nearly 6 per-
cent and for C A L by 4 percent.
A M P I . provides a variety o f rounding funetions that can be used in this w a y . They are
summarízed in Table III.
Normally you cannot delete a set, parameter. or variable, beca use it & d e c b r e d f o r use
later in the nnxlel: but you can delete any objective or constraint. Y o u can also s p e c i f y a
c o m p o n e n t ' ' n a m e " o f the form c h e c k n t o delete the /ith c h e c k statement in the cur-
rent nnxlel.
T h e p u r g e command has the same form, but with the k e y w o r d p u r g e in place o f
delete. It removes not only the listed components. but also ali components that depend
on them either directly (by referring t o them) or indirectly (by referring t o their depen-
dents). Thus f o r e x a m p l e in d i e t : . m o d w e have
p a r a m í _ m i n (FOOD} > = 0:
p a r a m £ nvax ( j i n FOOD} > = £ _ m i n l j l :
v a r Buy ( j i n FOOD} >= £ _ m i n [ j l . <= £ _ j n a x ( j J ;
minimize Total_Cost: sum ( j i n FOOD} c o s t l j l * Buyljl:
a m p l : xrof f min;
i 4 ontitics d e p e r x i on £_min:
£_max
Buy
Total_Cost
Diot
changcs only the validity condi tions on £ _ s n i n . T h e declarations o f ali componcnts that
d e p e n d o n £ _ s n i n a r e left unchangcd, ai are any values previously reaJ f o r £ _ m i n .
A list o f aD component types to which d e l e t e . p u r g e , x r e £ , and redeclare
may be applied is given in A . I 8 . 5 .
T h e simple st <but nu>st drastic) way t o change the nnxlel is by issuing the command
r e s e t . which expunges ali o f the current model and data. R>llowing r e s e t , you can
issue n e w r > c d e l and d a t a c o m m a n d s t o set up a diíTerent optimi/ation problem: the
e f f e c t is like typing q u i t and then restaning A M P L . e x c e p t that options are not reset t o
their default values. If your operating system or your graphical environment for A M P L
allows you t o e d i t files while keeping A M P L active, r e s e t is valuable for debugging and
experimentation: you may make changes to the nnxlel or data files, type r e s e t , then
read in the m o d i f i c d files. <lf you need t o escape from A M P L t o mn a lext editor, you can
use the s h e l 1 command described in Scction A 2 1 . 1 . )
T h e d r o p command instruets A M P L lo ignore cenain constraints or objectives o f the
current model. A s an example, the constraints o f Figure 5-1 initially include
s u b j e c t t o D i e t Max ( i i n M A X R l * ) } :
num ( j i n KOOD} a m t [ i . j l * Buyljl <= nunaxlij;
or more simply:
Rather than setting and fixing the variables in separate statements, you can add an assign-
mcnt phrase t o the f i x c\>mmand:
T h e u n f i x command wurks in the same way, to reverse the e f l e c t o f fix and optionally
also reiet the value o f a variable.
Relaxing integrality
option reiax_integrality 1;
relaxes integra Ihy on ali B u y variables for f o o d s that have a mini muni purchase o f at
least some c u t o f f parameter a l l o v _ í r a c .
S o m e o f the solvers that work with A M P l . provide their o w n dircetives for relaxing
integrality, but these do not neeessarily have the same effect as AMPl.'s
r e l a x ^ i n t e ^ r a l i t y option or . r e l a x s u f f i x . T h e distinetion is due t o the e f f e c t s
o f A M P l . ' s problem simplification, or presolve, stage (Section 14.1). A M P l . drops inte-
gralhy restrictions In-fur? the presolve phase, s o that the solver receives a true continuous
relaxation o f the original integer p r o b l e m If the relaxation is performed by the solver.
however, then the integrality restrictions are still in eíYeetduring A M P L ' s presolve phase,
and A M P l . may perform some additional tjghtening and simplificatk>n as a result.
A s a simple example, suppose that diet nnxlel variable declarations are written t o
a l l o w the f o o d limits £_rr*ax t o be adjusted by setting an additk>nal parameter, s c a l e :
In our e x a m p l e o f Fjgure 2-3, ali o f the £ _ r n a x values are 10: suppose that also set
s c a l e *> 0.95. First, here are the results o f s o l v i n g the unrelaxed problem:
a m p l : l o t ocalo i* 0.93;
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p L i m a i i n L o g o r soluLion; objocLivc 122.B9
6 M1P n i m p l e x i L o r a L i o n s
0 branch-and-i>Dund noder.
W h e n no relaxation is specified in A M P l . . presolve sees that ali the variables have upper
limits o f 9.5, and since it knows that the variables must take integer values, it rounds
these limits d o w n t o 9. Then these limits are sent t o the solver. where they remain even if
s p e c i f y a s o l w r directive f o r integrality relaxation:
a m p l : diaplay Buy;
Buy 1*1 : =
BKKF B.39B9B
CHK 2
F1S11 2
MAM 9
MCM 9
MTL 9
SPG B.93436
TUR 2
SECT.ON 11 4 W C D F Y N 3 WCC€LS 217
a m p l : diaplay Buy;
Buy l *1 : =
BKKF 6 . . 87 98
C1IK 2
F1SJ1 2
UAM 9 . .S
MCll 9. .S
MTL 9. .S
SB3 9. .12 02
TUR 2
Variables that wxrre at upper bound 9 in the prevk>us solution are n o w at upper bound 9.5.
T h e same situation can arise in much less obvk>us circumstances. and can lead t o
unexpected resulfc. In general, the optimal value o f an integer program under A M P L ' s
r e l a x _ i n t e < j r a l i t y optk>n m a y be l o w e r ( f o r minimization) or higher ( f o r maxi-
mi/ation) than the optimal vahie reported by the solver *s relaxation direetive.
Copyright O 2KB by Robert Fourcr, David M.Gwy and B r i » W. Kernighin
12
Display Commands
A M P L o f f e r s a rich variety o f oommands and options to help you examine and repon
the results o f optimi/ation. Section 12.1 introduces d i s p l a y , the most convenient c o m -
mand for arranging set members and numérica! values into lists and tables: Sections I2.2
and I2.3 provide a dctailcd accounl o f d i s p l a y options that g i v e you more control over
how the lists and tables are arranged and how numbers appear in them. Section 12.4
describes p r i n t and p r i n t f , t w o related c\>mmands that are useful for prcparing data
t o b e sent to other programs. and for formatting simple repor ts.
Ahhough our examples are based on the display o f sets. parameters and variables —
and expressions involving them — you can use the same commands to inspect dual val-
ues, slacks, rcduced costs, and other quantities associated with an optimal solution: the
mies for doing so are explained in Section 12.5.
A M P L also provides ways to access nnxleling and solving information. Section 12.6
describes fetfures that can be useful when, f o r example, you want to view a parameter's
declaration at the command-line, d&play a particular constraint from a problem instance,
list the values and boundsof ali variables regardless o f their namcs, or record timings o f
A M P L and solver activities.
Finally, Section 12.7 addrcsses general facilities for manipubting output o f A M P L
c\>mmands. These include fcaturcs for redircction o f command output, k>gging of output
and suppression o f e n o r messages.
219
220 D3=LAYCOVVAfC<S C H í f T E R 12
A s we wiD dcscribe in more detail in Section 12.7. it is possiblc t o capture the output
o f d i s p l a y c o m m a n d s in a file, by adding >filênamt t o the end o f a d i s p l a y com-
mand: this rcdircction mechantvm applies a* well t o most other cx>mmands that pnxluce
output.
Displaying sets
T h e contents o f sefc are shown by typing d i s p l a y and a list o f set names. This
example is taken from the nuxlel o f Figure 6-2a:
If you s p e e i f y the name o f an indexed coDection o f sets. each set in the collcction is
shown ( f r o m Figure 6 - 3 ) :
or the set o f ali transponation links on which the shipping cost isgreater than 500:
a m p l : diaplay { ( i , j ) in LINKS: c o s t [ i , j ) • Trana[i,j) > 300);
s e t ( ( i . j ) i n LINKS: c o s t l i . j | » T r a n s [ i . j l > S 0 0 > :=
(GARY. S T L ) (CLKV.DKT) (CLKV. WIN) ( P I T T . FRA) (PITT.FRK)
(OARY.LAF) (CLKV.LAN) ( C L K V . LAFJ ( P I T T . 5?FL) :
Bccause the membership o f this set depends upon the current values o f the variables
T r a n s ( i , j ] , you coukl not refer t o it in a nuxlel. but it is legal in a d i s p l a y com-
mand. where variables are treated the same as paramcters.
ampl: d i a p l a y T/
T = 4
o f the values o f indi v idual componente from an indexed colleetion (Figure I -6b):
or an arbitrary expression:
a m p l : diaplay avail/
a v a i l 1*1 : =
reheaL 3S
rol1 40
a m p l : diaplay aupplyj
supply :=
CLKV b a n d s 7 00
CLKV c o i l s 1600
CLKV p l a L e 3 00
GARY b a n d s 4 00
GARY c o i l s 800
OARY p l a L e 2 00
P I T T bands 800
PITT c o i l s 1800
PITT plaLe 3 00
demand [ * . * 1
: bands c o i l s p l a L e :=
DKT 3 00 7S0 100
FRA 3 00 SOO 100
FRK 22S 8S0 100
LAF 2 S0 SOO 2S0
LAN 100 400 0
SVL 6S0 9S0 200
WIN 7S 2S0 SO
222 D3=LAYCOVVAfC<S C H í f T E R 12
You can control the choice between formais by setting option d i s p l a y _ l c o l , which is
described in the next section.
A parameteror variable (or any other nnxlel enthy) indexed over a set ofordered pairs
is a b o considcrcd to be a t w o dimensional objcct and is displayed in a similar manncr.
Ilere isthe dispby for a parameter indexed over the set L I N K S that was displayed earlier
in this sectk>n (from Figure 6-2a):
This. too.can be made toappear ina tabkr formai, as the next sectk>n will show.
T o dispby values indexed in thxee or more dimensions. AMPI. again forms lists for
small amounts o f data. Muhi-dimensional entities mi>re often involve daia in large quan-
tities. howxrver. in which case A M P I . " s l i c e s " the vahies ink> two-dimcnsk>naI tables. as
in the case o f t h i s variable from Figure4-6:
a m p l : diaplay Trana;
Tranr. ICLKV, » . » l
: bands c o i l s p l a L o :=
DKT 0 750 0
FRA 0 0 0
FKK 0 0 0
LAF o SOO 0
LAN o 400 0
SVL o SO 0
WIN o 2S0 0
[GARY. 1
: bands c o i l s p l a L c
DKT 0 0 0
FRA 0 0 0
FRK 22S 8S0 100
LAF 2 SO 0 0
LAN 0 0 0
STL 6S0 900 200
WIN 0 0 0
SECT CN 12.1 B R 0 W 3 N G T > T O U G H R E S U L T S THE O I SS-LXT O C W W / N D 223
[PITT, *.* I
: bands c o i l s p l a L e
DBT 300 0 100
KRA 3 00 SOO 100
FRB 0 0 0
LAF 0 0 2S0
LAN 100 0 0
STL 0 0 0
WIN 75 0 SO
At the head o f the first table, the templaie [CLEV. * . • ) indicates that the slice is
through CLEV in the first component. so the entry in row L A F and column c o i l s says
that T r a n s [ ' C L E V ' . ' L A F ' . ' c o i l s ' ) is 500. Since the first indcx of T r a n s is
always CLEV, GARY or P I T T in this case, there are three slice tables in ali. But AMPL
does not always slice through the first componcnt: it picks the slices so that the display
will c\>ntain the fewest possible tables.
A display o f two or more componenfc of the same dimensionaüty is always presenteei
in a list formai whether the componcnts are one-dimensional (Figure 4-4):
or any higher dimension. The indiccs appear in a list to the left, with the bst one chang-
ing most rapidly.
A s you can see from these examples, d i s p l a y normally ar ranges row and column
labels in alphabetical or numerical order, regardless of the order in which they might have
been given in your data file. When the labels come from an ordered set, howxrver, the
original ordering ishonored(Figure 5-3):
224 D3=LAYCOVVAfC<S C H í f T E R 12
F o r ihiü rcau>n. itcan be worthwhile t o declare ccrtain sets o f your nnxlel t o be ordered.
even if their ordering plays n o e x p l i e h role in your formulation.
The d i s p l a y command can show the value o f any arhhmetic expression thai is
valid in an A M P L nnxlel. Single-valued expressions p*>se n o diHlcuhy. as in the case o f
these three profit componcnts from Figure 4 - 4 :
Suppose, howxrver, that you want to see ali the individual vahies o f r e v e n u e [ p . t ) *
S e l l [ p . t J. Since you can type d i s p l a y revenue. S e l l t o display the separate
values o f r e v e n u e [ p . t J and S e l l t p . t J, you might want to ask f o r the produets o f
these values by typing:
A M P L does not recognize this kind o f array arithmetic. T o d&play an indexed collection
o f expressions. you must s p e c i f y the indexing explicitly:
T o apply the same indexing t o t w o or more expressions, enclose a list o f them in paren-
theses alter the indexing expression:
S E C T C N 12.1 BROVtfS N 3 T>TOUGH R E S U L T S THE OISPIAT OCWW/ND 225
ampl: d i a p l a y {p in PROD, t i n 1 . . T J
ampl? ( r o v o n u o /p, t j 'Soll [p, t) , prodcoat [p) 'Kako [p, t) )/
: revenue I p . t J * S e l l I p . t l p r o d c o s t l p l " M a k e l p . t j :
harxis 1 ISO000 59900
harxis 2 156000 60000
bands 3 37 8 0 0 14 000
harxis 4 54 0 0 0 20000
coils 1 9210 15477
coils 2 87 5 0 0 15400
coils 3 129500 38500
coils 4 163 800 46200
ai shonhand for
In additk>n t o indexing individual display items. you can s p e e i f y a set over which the
whole d i s p l a y command is indexed — that is. you can avk that the c\>mmand be e x e -
cuted o n c e for each member o f an indexing s e t This feature is particularly useful f o r
rearranging slices o f muhidimensional tables. W h e n . earlier in this section. wxr d&playcd
the three-dimensional variable T r a n s indexed o v e r { O R I G , DEST. PROD). AMPL
chosc to slice the values through members o f O R I G t o produce a series o f two-
dimensional tables.
What if you want t o display slices through PROD? Rearranging the indexing expres-
sion. as in our prevk>us example. will not reliably have the desired efTect: the d i s p l a y
command always picks the smallest indexing set, and where there is more than one that is
smallest, it does not necessarily c h o o s c the first. Instcad. you can say explicitly that you
want a separate display f o r each p in PROD:
a m p l : diaplay (p in PROD) i
«ampl? ( i in ORIG, j in DEST) Trano [ i , j , p) j
Transli,j, 'bands'] l*.*| <trj
: CLKV GARY P1TT : =
DKT 0 0 300
FRA 0 0 300
FRK 0 22S 0
LAF 0 2 SO 0
LAN 0 0 100
SVL 0 6S0 0
MIN 0 0 7S
each member o f the s e t the expressions f o l l o w i n g the cok>n are evaluated and d&playcd
separa tely.
a m p l : diaplay roquirodj
r o q u i r o d 1*1 :=
Kril 100
Kri2 ?B
Kri3 52
Jtonl 100
Won2 ?B
Won3 52
Satl 100
SaL2 7B
Thul 100
Tbu2 ?B
Tbu3 52
Tuel 100
Tuc2 ?B
Tuc3 52
Wedl 100
Wed2 78
Wod3 52
228 D3=LAY OOVMA*C«S CHVTÇR12
T h e one-column list format is used when the number o f values k> be d i s p b y c d is less than
or equal k» d i s p l a y _ l c o l , and the compact for nut is used otherwise. T h e default f o r
display_lcol & 20: set it t o z e r o t o f o r c e the compact f o r m a t or t o a very large num-
ber t o f o r c e the list f o r m a l
Mui ti-dimensional d i s p b y s are aflectcd by optk>n d i s p l a y _ l c o l in an analogous
w a y . T h e one-column list formai ti used when the number o f values is less than or equal
t o d i s p l a y _ l c o l , while the appropriate compact formai — in this caie, a table — is
used otherwise. NVe s h o w e d an e x a m p l e o f the difference in the previous section. where
the d i s p b y for s u p p l y appeared ai a list because it had only 9 vahies, while the d i s p b y
for d e m a n d appeared av a table because its 21 vahies e x c e e d the default setting o f 20 f o r
option d i s p l a y _ l c o l .
Since a parameter or variable indexed over a set o f ordered pairs & also considercd t o
be two-dimcnsional, the value o f d i s p l a y _ l c o l affeets iti d i s p b y as wxrll. Ilere i* the
table format f o r the parameter c o s t indexed over the set L I N K S ( f r o m Figure 6 - 2 a ) that
was d i s p b y e d inthe preceding section:
7 members and then PROD with 3 members. By contrast the table f o r c o s t has columns
labeled by the first coordinate and rows by the second, because it is indexed over O R I G
with 3 members and then D E S T with 7 members. A transposed table is indicatcd by a
{ t r > in its first line.
The transpositk>n status of a table can be reversed by changing the
d i s p l a y _ t r a n s p o a e option. I\>sitive values tend t o force transposhion:
r e q u i r e d 1*1 : =
F r i l 100 Mon3 52 Thu3 52 Wed2 78
Fr i 2 78 S a L l 100 Tuol 100 Wed3 52
Fr i 3 52 5at2 78 Tuo2 78
Jtonl 100 T b u l 100 Tuo3 52
>ton2 78 Tbu2 78 Wcdl 100
D2 41 >12 33 M2 39 .=
Co u l l a r d 3 2 1
lia s k i n 4 2 3
11a z e n 3 4
Itopp 4 2 3
Iravani 4 6 7
Linetsky 8 1 2
MehroLra S 4 3
Ne l s o n 10 2 3
ânilowitz 4 1 2
Tamhane 11 2 1
WhiLe 7 2 1
I f a table's cohimn headings are much wider than the values. d i a p l a y introduccs
abbreviaiions t o kcep ali columns logether (Figure l - l ) :
On the other hand. where the headings are narrowv* than the vahies, you m a y be abkr t o
squcc/c more on a line by rcducing the optk>n g u t t e r — w i d t h — t h e number o f spaces
between columns — from hs defauh value o f 3 t o 2 or I .
SECT CN 12.2 FORWATTN3 OPTONS FOR DZSPIAY 231
Suppression o f zeros
In some kinds o f linear program* thai have many more variable* than constraint*.
most o f the variables have an optimal value o f zero. K>r instance in the assignment prob-
lem o f Figure 3-2, the optimal value* o f ali the variable* form thi* table, in w h i c h there is
a single I in cach r o w and each column:
T r a n s l * . *1
: C l 18 C l 3 8 C l 4 0 C24G C2S0 C 2 S 1 D237 D239 D241 M233 M239 :=
Coullard 1 0 0 0 0 0 0 0 0 0 0
Ca sk i n 0 0 0 0 0 0 0 0 1 0 0
11a M n 0 0 0 1 0 0 0 0 0 0 0
Itopp 0 0 0 0 0 0 1 0 0 0 0
Iravani 0 1 0 0 0 0 0 0 0 0 0
LinoLsky 0 0 0 0 1 0 0 0 0 0 0
MchroLra 0 0 0 0 0 0 0 1 0 0 0
JJelson 0 0 1 0 0 0 0 0 0 0 0
SnilcwiLz 0 0 0 0 0 0 0 0 0 1 0
Tamhanc 0 0 0 0 0 1 0 0 0 0 0
WhiLc 0 0 0 0 0 0 0 0 0 0 1
By setting o m i t _ z e r o _ r o v s t o I, ali the zero values are suppressed, and the list
c o m e s down to the entries o f interest:
Trans : =
Coullard Cl18 1
Oaskin D2 41 1
llazcn C2 4G 1
Itopp D2 37 1
iravani C l 38 1
LinoLsky C2S0 1
MchroLra D2 39 1
?Jelson C l 40 1
StailowiLz M2 33 1
Tamhane C2S1 1
WhiLc M2 39 1
If the number o f non/ero entries is less than the vahie o f d i s p l a y _ l c o l , the data is
printcd ai a list as it is hcre. I f the number o f n o i u c r os isgreater than d i s p l a y _ l c o l ,
a table formai would be used, and the o : n i t _ z e r o < _ r o v s option would only suppress
table rows that conta in ali A Í o entries.
For example, the display o f the three-dimensional variable T r a n s from earlier in this
chapter would be condenscd t o t h e f o l l o w i n g :
232 D3=LAYCOVVAfC<S C H í f T E R 12
a m p l : diaplay Trazia;
Trans ICLKV.*.*]
: bands c o i l s p l a L c
DBT 0 750 0
LAF 0 500 0
LAN 0 400 0
STL 0 50 0
WIN 0 250 0
IGARY, 1
: bands c o i l s p l a L c
FRB 225 850 100
LAF 2 50 0 0
STL 650 900 200
[PITT. 1
: bands c o i l s p l a t c
DKT 3 00 0 100
FRA 3 00 500 100
LAF 0 0 250
LAN 100 0 0
WIN 75 0 50
In ali o f our examples s o far, lhe d i s p l a y command shows each numérica) value t o
the same number o f significam digits:
(see Figures 6 - 3 and 6 - 4 ) . T h e default is t o use six significam digits. whether the result
c o m e s out ai 7-85714 or 64285.7. S o m e numbers seem k> have fewer digits. but only
because trailing zeros have been dropped: 29.95 represents the number that is exactly
29.9500 t o six digits. for example. and 59900 represents 59900/).
By changing the option d i s p i a y _ p r e c i s i o n t o a value other than six. you can
vary the number o f significam digits reponed:
A negative value indicates rounding before the decimal point. For example. when
d i s p l a y _ r o u n d is - 2 . ali numbers are rounded tohundrcds:
Any value whose magnitude is less than lhe value o f d i s p l a y _ e p s & treatcd as an
exact zero in ali output o f d i s p l a y .
ampl: aolvo;
M1NQS S . S : o p L i m a l s o l u L i o n f o u n d .
19 i t o r a L i o n s . o b j o c L i v e 2GS.G
S E C T - G N 12.3 N U W S ^ C OPTCNS FOR dispiat 237
lf \V>Í copy the numbers from the preceding table and round them up by hand, bowever,
\v\rfind thai they only sum k> 271. The source o f the difficulty can be seen by displaying
the numbers k> full precision:
a m p l : diaplay Work;
Work 1*1 : =
10 28.799999999999997 73 28.000000000000018
18 7.S99999999999998 87 14.39999999999999S
24 G.79999999999999 95 -5.87GG71973951407e-15
30 14.40000000000001 10G 23.20000000000000G
3S G.799999999999995 108 4.G85288280240G83«-1G
SS - 4 . 9 3 9 G 1 4 3 1 3 8 5 7 G 7 7 c - l 5 109 14.4
GG 3 S . G 113 14.4
71 35.599999999999994 123 35.59999999999999
llalf the problem is duc to the minuscule positive value of W o r k [ 1 0 8 ] , which was
rounded up k> I. T h e other half is due to W o r k ( 7 3 ) ; ahhough it is 28 in an exact solu-
tion, it comes back from the sol ver with a slightly larger value of 28.000000000000018,
so it gets rounded up to 29.
T h e eaiiest way *> ensure thai our arithmetic works correctly in this case is again to
set s o l u t i o n _ r o u n d b e f o r e s o l v e :
or. if follovrcd by an indexing expression and a colon. a line of output for each member of
the indexset:
a m p l : print PROD/
syntax error
context: print » > PttDD: « <
T h e format string contains t w o types o f objects: ordinary characters. which are copicd t o
the output, and conversion specificatk>ns, w h i c h govern the appearance o f successive
remaining print ilems. Each conversion specifk-ation begins with the character % and
ends with a conversion character. For example. % 6 . 2 £ speeifies conversion t o a decimal
representai ion at least six characters wide with t w o digits after the decimal point. T h e
complete rukrs are much the same as f o r the p r i n t £ functk>n in the C programming lan-
guage: a summary appears in Section A . 16 o f t h e Appendix.
T h e output from p r i n t £ & not automatically broken into lines. A line break must
be indicaiedexplicitly by the combinatk>n \ n . representing a " n e w l i n c " character, in the
format string. T o producc a seriei o f lines. use the indexed versk>n o f p r i n t £:
240 D3=LAY OOVMA*C«S CHVTÇR12
This p r i n t £ is executod once for each member o f lhe indexing sei preccding lhe c o l o n ;
for each t in 1 . . T the formal is applicd again. and the \ n character g e n e r a i s another
linebreak.
T h e p r i n t £ command is mainly useful, in conjunction with redirectk>n o f ouiput t o
a file, f o r printing shoit summary reports in a readable formai. Because the number o f
convcrsion specifications in the formai string must match lhe number o f values being
printed. p r i n t £ cannot convcniently produce tables in which the number o f keire on a
line may vary from run t o run. such as a table o f ali J í a k e [ p . t 1 values.
Objective funetions
If the current nnxlel declares severa] o b j e c t i v e funetions, you can refer t o any o f them.
even though only one ha* been optimized.
SECT CN 12.5 RRATCD SCLUTON VALUES 241
T h e reponed bounds are those that w e i c sent t o the sol ver. Thus they inchidc not only the
bounds specified in > = and < = phraies o f v a r dcclaraiions. but also cenain bounds that
WMÍC deducvrd from the oonstraints by A M P L ' s presolve phase. Other sufilxes lei you
look at the original bounds and at additional bounds deduced by presolve: see the dfecus-
sion o f presolve in Section 14.1 for detaik.
T w o equal bounds denote a fixod variable. which is nor mal ly eliminated by presolve.
Thus in the planning nnxlel o f Fjgure 4-4, the constraint I n v [ p . 0 ] = i n v O [ p ] fixes
the inhial inventories:
leads presolve t o fix three variables at zero, because d e r w - m d l • L A N ' . ' p l a t e ' ] is
zero:
a m p l : diaplay ( i in ORIG)
ampl? (Trona l i , "LAN", "plato ") .lb,Trona [ i , "LAN", "plato").ub)j
i Transli,'LAN', ' plaLo'1.lb Transii.'LAN'.'plaLc'1.ub :=
CLKV 0 0
GARY o O
PITT 0 0
A s this example suggests. presolve*s adjustments *> the bounds may depend on the data
av well as the stmeture o f the oonstraints.
T h e concepts o f bounds and slacks have an anak>gous interpretaiion f o r the c o n -
straints o f a nnxlel. A n y A M P L constraint can be put into the standard f o r m
242 D3=LAY OOVMA*C«S CHVTÇR12
where lhe W v is a sum o f ali terms i n v o l v i n g variables. while lhe lawer bound and
upper ix/und depend only on the data. T h e s u f f i x e s . l b , . b c d y and . u b give the cur-
rent values o f these three pans o f the constraint. For example. in the diet nnxlel o f Figutc
5-1 we have the declarations
s u b j e c L Lo D i e L _ M i n ( i i n M I N R E Q } :
sum ( j i n K 0 0 D } a m L l i . j l * Buyljl >= n_Minli|:
s u b j e c L Lo D i e L Max ( i i n MAXRBOJs
sum ( j i n K 0 0 D } a m L l i . j l * Buyljl <= n MaxliJ:
Naturally, < = constraints have n o l o w e r bounds, and > = constraints have n o upper
bounds: A M P L uses - I n f i n i t y and I n f i n i t y in p l a c e o f a number to denote these
cases. Both the l o w e r and the upper bound can be finite, if the constraint is s p e c i f i e d with
t w o < = or > = operator s: see Section 8.4. For an = constraint the t w o bounds are the
same.
T h e s u f f i x . s l a c k refers t o the difference between the Ixxly and the nearer bound:
For constraints that have a single < = or > = operator, the slack is always the difference
between the expressions t o the left and right o f the operator, even if there are variables on
both sides. T h e constraints that have a slack o f zero are the ones that are tnily constrain-
ing at the optimal solution.
SECT CN 12.5 R R A 7 E D S C L U T O N VALUES 243
and a table o f t h e dual values associatcd whh these constraints can be vicwad by
a m p l : diaplay Daxzand;
Demand [ * . * l
: barxis coils pia te
DET 2 01 190.714 199
FRA 2 09 2 04 211
FRK 2 GG. 2 273.714 2 85
LAF 201.2 198.714 2 05
LAM 2 02 193.714 0
SVL 20G.2 207.714 21G
WIN 2 00 190.714 198
Solvers return optimal dual values t o A M P I . along with the optimal values o f the " p r i -
m a i " variables. W e have space here only t o summari/e the most c o m m o n interpretaiion
o f dual vahies: the cxtcnsive theory o f duality and applications o f dual variables can be
found inany t c x t b o o k o n linear programming.
T o stan with an cxampkr, consider the constraint D e m a n d [ • D E T ' , 'banda']
above. lf w e change the value o f the paramekrr d e m a n d [ • D E T ' , ' b a n d a • ] in this
constraint the optimal value o f t h e objective functk>n T o t a l _ C o s t changes accord-
ingly. lf w e ware *> plot the optimal value o f T o t a l _ C o a t versus ali possible values o f
d e m a n d [ B D E T ' . • b a n d a ' ) , t h e result would be a cost " c u r v e " that s h o w s h o w o v e r -
all cost variei whh demand for bands ai Detroit.
Addhional computation would be necessary t o determine the entire cost c u r v e , but
you can learn somcthing a bout it from the optimal dual values. A f t e r you solve the linear
program using a particular value o f d e m a n d [ • D E T ' , • b a n d a ' ] , the dual price f o r the
constraint tells you the slope o f the cost c u r v e , at the dcmand's current value. In our
exampkr, reading from the table above, w e find thai the slope o f t h e curve ai the current
demand is 201. This means that total pnxluction and shipping cost is increasing at the
rate o f $201 for each extra ton o f bands demandcd at DET. or is dccreaiing by $201 f o r
each rcduction o f one k>n in the demand.
A s an exampkr o f an inequality, consider the f o l l o w i n g constraint from the same
model:
s u b j o c t t o Time ( i i n ORIG}:
sum ( p i n PROD} ( 1 / r a t o l i . p 1J * Makeli.pl <= availlil:
244 D3=LAYCOVVAfC<S C H í f T E R 12
I lere it is rc vealing t o loofc at the dual values together with the slacks:
Where the slack is positive, the dual value is zero. Indeed. the positive slack iniplies that
the optimal solution does not use ali o f the time available at P I T T : hence changing
a v a i l [ • P I T T ' J some what does not affeet the optimum. On the other hand. where the
slack is zero the dual value may be significam. In the case o f G A R Y the value i s - 3 0 1 0 .
implying that the total cost is dccreaiing at a rate o f $3010 f o r each extra hour available
at G A R Y , or is increaiing at a rate o f $3010 f o r each hour lost.
In general, if \V>Í plot the optimal objeetive versus a constraint s constam term, the
curve w i l l be c o n v e x piecewise-linear (Figure 12-1) for a minimizatk>n, or concave
piecewise-linear (the same, but upside-down) for a maximi/ation.
In ter m i o f the standard form lunrr bound £ body £ upper l/ound introduced previ-
ously, the optimal dual values can be viewxxl as f o l l o w s . If the slack o f the constraint is
positive, the dual value is z e r o . I f the slack is z e r o , the body o f the constraint must equal
one ( o r both) o f the bounds, and the dual value penains t o the equalcd bound or bounds.
vSpeci ficai ly, the dual vahie is the slope o f the plot o f the objeetive versus the bound, e v a l -
uated at the current value o f the bound: cquivalently it is the rate o f change o f the optimal
objeetive with respect t o the bound value.
A nearly identical analysis applies t o the bounds on a variable. T h e role o f the dual
value is played by the variable's so-called rcduced c o s t w h i c h can be viewxxl from the
A M P L command environment by use o f the suíllx .rc. A s an example, here are the
bounds and rcducvd costi for the variables in Figure 5-1:
S E C T C N 126 OTHER D S R - A Y FE ATURES F O R W C C € L S A N D ttSTANCCS 245
Smce BuyftfTL') has slack with both its bounds, its reduced cost is zoa.
B u y [ • HAM • J is at its tower bound. s o its reduced cost indicatcs thai total cost is increas-
ing at about 70 centi per unit increasc in the l o w e r bound. or is dccreasing at about 70
cents per unit decrease in the k>\ver bound. On the other hand. B u y [ • C H K ' ] is at its
upper bound. and its negative reduced cost indicatcs that total cost is decreasing at about
85 cents per unit increase in the upper bound. or is incrcasing at about 85 cents per unit
decrease in the upper bound.
I f the current vahie o f a bound happens t o lie right at a brcakpoint in the relevam
curve — one o f the places where the slope c h a n g e s a b m p t l y in Figure 12-1 — the o b j e c -
tive will change at one rate ai the bound increases. but at a different rate as the bound
decreases. In the extreme case either o f these rates may be infinite. indicating that the lin-
ear program becomes infeavible if the bound is increased or de cr ca se d by any further
amount. A sol v e r repor ts only one optimal dual price or reduced cost t o A M P L howevcr,
which may bethe rate in either direction. or s o m e value between them.
In any case. moreover, a dual price or reduced cost can g i v e you only one slope on the
piecewise-linear curve o f objective values. Ilcncx? these quantities should only be used ai
an initial gukle t o the o b j e c t i v e ' s senshivity t o c e n a i n variable or constraint bounds. If
the senshivity is very importam t o your application. you can make a series o f mns with
ditTerent bound settings: see Scction 11J f o r w a y s *> quickly change a smaD part o f the
data. (There d o exist algorithms for finding pan or ali o f the piecewise-linear curve,
given a linear change in one or more bounds, but they are not directly supported by the
current version o f A M P L . )
B y kself, the s h o w c\>mmand lists the nanies o f ali components o f the current nnxlel:
a m p l : c o d o l j s u i t n i p 3 .mod;
ampl: ohc%f;
paramcLcrs: dcmar>d f c o s L l i m i t max s e r v e m i n l o a d s u p p l y v c o s L
seLs: DESr ORIG PROD
variables: Trans Use
consLrainLs: Demand Max S e r v e Min__Ship Mui L i Supply
objecLive: ToLal_CosL
chocks: one. c a l l o r i chock 1.
a m p l : ahoif vara;
va r i a b l c s : Trans U se
a m p l : ahoif obj, conatr;
objecLive: ToLal_CosL
consLrainLs: Demand Max S e r v e Min__Ship Mui L i Supply
a m p l : shoif chock 3;
c h o c k ( p i n PROD} :
s u m ( i i n ORIG} s u p p l y [ i . p | == sum( j i n DEST} demandlj.pl:
I n c h c c k i n g a nuxlel and its data f o r oorreetness. you m a y want to look at some o f the
speeific constraints that A M P l . is gcnerating. T h e e x p a n d command displays ali con-
straints in a given indexed collection or speeific constraints that you idcntify:
a m p l : xzodol nl trana. ao d;
a m p l : data nltrana.datj
a m p l : axpand Supply;
s u b j e c t to Supply ['QARY'] :
T r a n s [ ' GARV . ' FRA' 1 + T r a n s l • G A R V . ' DIÍl*' 1 +
T r a n s i • ÚAKY' . ' L A N ' 1 + T r a n s l • GARV . 'WIN ' 1 +
T r a n s [ ' G A R V , ' SYL ' j + T r a n s l • G A R V . ' FRK ' 1 +
Trans[' GARV,'LAF'j = 14 0 0 ;
subject to Supply r C L K V l :
T r a n s [ • C L B V ' , • FRA • ] + T r a n s [ ' CLBV* , ' DBY ' ] +
T r a n s i • CLKV' . » L A N ' 1 + T r a n s l ' CLEV' , ' W I N ' 1 +
T r a n s i ' C L K V * . ' SYL ' 1 + T r a n s l • CLEV' , ' FRK ' 1 +
Transi•CLBV','LAF•j = 2600;
(See Figures 18-4 and 18-5.) T h e ordering o f terms in an expandcd constraint dixrs not
neccssarily correspond t o the order o f the symbolic terms in the constraint's dcclaration.
Objectives may be expandcd in the same way:
248 D3=LAYCOVVAfC<S CHífTER 12
a m p l : axpand Trans;
C o e i f i c i c n L s o£ T r a n s i ' G A R Y F R A ' l :
Supplyl'GARY'J 1
Dcmandl'FRA* 1 1
ToLal_CosL 0 + nonlinear
Occasionally il ts useful t o make a listing or a test that applies *> ali variables. c o n -
straints, or objectives. K>r this purpose. A M P l . provides automatically updated parame-
ters that hold the numbers o f variables. constraints. and objectives in the currently gener-
ated problem instance:
These synonyms let you refer t o components by number. rather than by the usual indexed
names. Using the variables a* an example. _ v a r [ 5 ] refers t o the fifth variable in the
problem. _ v a r 1 5 ) . u b t o its upper bound. . v a r [ 5 ] . r c t o hs reduced c o s t and s o
forth. while _ v a r n a m e [ 5 ] is a string giving the variable's tme A M P l . name. Table A -
13 lists ali o f the generic synonyms for sets. variables. and the like.
Generic names are useful f o r tabubting properties o f a l l variables. where the variables
have been defined in several d i f l e i e n i v a r declarations:
ampl: c o d o l nat3.xsod
a m p l : data not3.dat
ampl: aolvo;
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
3 i t c r a t i o n s . o b j o c t i v c 1819
Anothcr use is *> list ali variables having s o m e property, such as being a\vay from lhe
upper bound in lhe optimal solution:
a m p l : diaplay { j in 2 . . nvara:
ampl? var[j) < var[j).ub - 0.00001) varnaxsa[j) j
_ v a r n a m e l j 1 1*1 : =
2 *PD_Ship['SE'1 -
S "DW_Shipl *HB', • m i ' 1-
G " D W _ S h i p [ 'SE'. 'BMR' 1 -
7 "DW_Ship[ ' S K ' , • m i ' J-
Resource Hstings
Changing optk>n s h o v _ s t a t s from its default o f 0 k> a non/ero value requests sum-
mary statistics on the size o f the optimi/ation problem that A M P L generates:
P r e s o l v e e l i m i n a t e s 2 c o n s t r a i n t s and 2 variable».
Adjusted problem:
24 v a r i a b l e s , a l i linear
12 c o n s t r a i n t s . a l i l i n e a r : 3B n o n z e r o s
1 l i n e a r o b j e c t i v e ; 24 n o n z e r o s .
M1MDS S . S : o p t i m a l s o l u t i o n f o u n d .
I S i t e r a t i o n s . o b j e c t i v e S15033
Additional lines report lhe numbers o f integer and variables and nonlinear components
where appropriate.
Changing option t i m e s from its default o f 0 t o a non/cro value requests a summary
o f the A M P L transhtor's time and memory requirements. Simflarly, by changing option
g e n t i m e s t o a non/ero vahie, you can g e t a detailed summary o f the resources that
A M P L ' s gennnxl phase consumes in generating a nnxlel instanevr.
SECTCN 12.7 GBVJERAL F A C L 7 E S F O R W / N F U L A T N 3 O J T P U T 251
When A M PI. appears to hang or takcs much more time than expeeted. lhe d&play pro-
ducvrd by g e n t i m e s can help associate the difilcuhy with a particular nxxlel compo-
nent. Typically, some parameter. variable or constraint been indexed over a set far
larger than intended or anticipated. with the result that excessive amounts o f time and
memory are required.
T h e timings given by these commands apply only to the AMPL transbtor, not k> the
solver. A variety ofprcdefined parameters (Table A - l - l ) let you work with both AMPI.
and solver times. K>r example, _ s o l v e _ t i : r > e always equals total CPU seconds
required for the most reeent s o l v e c\>mmand, and _ a n p l _ t i m e equals total CPU sec-
onds for AMPI. excluding time spent in solvers and other externai programs.
Many solvers also have directives for requesting breakdowns of the solve time. The
speeifies vary considerably. however, so information onrequesting and interpreting these
timings is provided in the documentation o f A M P I . s links to individual solvers, rather
than in this book.
Redirection of output
T h e examples in this book ali show the outputs o f commands ai they would appear in
an interactive session, with typed cx>mmands and printed responses alternating. You may
dircct ali such output ti> a file instead, howvrver, by adding a > and the name of the file:
The first command that speeifies > m u l t i . o u t createsa new file by that name ( o r over-
writes any existing file o f the same name). Subscquent c\>mmands add k> the end o f the
file. until the end o f the session ora matching c l o s e command:
T o open a file and append output to whatever is already there (ralher than overwrkingX
use > > instead o f >. Once a file is open, subscquent uses o f > and > > have the same
effect.
Output logs
T h e log file colfccts ali A M P L statements and the output that they prtxluee, whh a f e w
exeeptions described b e l o w . Setting l c < j _ £ i l e t o lhe e m p t y string:
turns o f f writing t o the file: the empty string is the default vahie f o r this option.
W h e n AMPI. reads f r o m an input file by means o f a m o d e l or d a t a command ( o r an
i n c l u d e command as defined in Chapter I3X the statements from that file are not nor-
mally c o p i c d t o the log file. T o rcquest that A M P I . echo the contcnts o f input files,
change option l c < j _ m c d e l (for input in nnxlel nnxle) or l c < j _ d a t a (for input in data
nnxle) from the default value o f O u » a nonzcro value.
W h e n you invoke a solver, AMPI. k>gs at leait a f e w lines summari/ing the objective
value, solution status and work required. Through solve r-speci fie directivei, you can typ-
ically request additional solver output such ai logs o f iterations or branch-and-bound
•iodes. Many solvers automatically send ali o f the ir output k> A M P I . ' s k>g file, but this
compatibility ii not universal, lf a s o l v e r ' s output does not appear in your log file, you
should consult the supplemcntary documentai ion f o r thai s o l v e r ' s A M P I . interface: possi-
bly that solver accepts nonstandard directives f o r d i v e n i n g ifc output t o files.
Limits on messages
d i e L . m a d . l i n e S ( o í í s e L S6J :
e x p e c t e d ; < l : o r symbol
context: param £ _ m i n » > ( < « FOOD} > = 0:
13
Command Scripts
Y o u w f l l probably find that your most inwrnsive use o f A M P L ' s cx>mmand environ-
meni occurs during the initial deveiopment o f a model, when the results are unfamiliar
and change & are froquent. W h e n the formulation eventually settles down. you may find
y o u n e l f typing the same series o f cx>mmands over and o v e r t o solve for diíTerent c o l l e c -
tions o f data. T o acceleraie this process. you can arrange *> have A M PI. read often-used
s e q u c n c e s o f c o m m a n d s from files or torepeat command sequences automatica lly, deter-
mining h o w k> proceed and when t o s t o p o n the hasisof intermcdiatc resulfc.
A scripí is a sequence o f cx>mmands. capturcd in a f i l e , t o be used and re-used.
Scripts can cx>ntain any A M P I . commands. and may includc programming language con-
stmcts like f o r , r e p e a t , and i £ t o repeat state mente and per form them condi tk>nalty.
In e f f e c t , these and r e b t e d commands let you write small programs in the AMPI. o o m -
mand language. Another collection o f c o m m a n d s permit stcpping through a script f o r
observation t>r debugging. This chapter introducvrs AMPI. cx>mmand scripts, using for-
matted printing and sensitivity analysis as examples.
A M P I . c o m m m d scripts are able t o work directly with the sets ofcharacter strings that
are central t o the definitk>n o f models. A f o r statement can specify cx>mmands t o be
executed once for each member o f s o m e set, f o r example. T o suppon scripts that w o r k
with strings, A M P I . provides a variety o f string funetions and operator s. whose use is
described in the bst sectk>n o f this chapter.
i n c l u d e fútn<v)\ir
is replaced by the c o M e n t s o f the named file. A n i n c l u d e can even appcar in the mid-
dle o f s o m e other statement and does not requirc a ter mina tine semieolon.
2S6
256 CQHVX4D SCR P T S C H í f T E R 13
msdel d i o L u . n o d ;
da La d i o L u . d a L :
solvc :
o p L i o n d i s p l a y _ l c o l S:
opLion display_rourxi 1:
d i s p l a y Buy:
then including it w i l l load the mixlel and data, run the problem, and display the optimal
values o f the variables:
Buy 1*1 : =
BKKF 2.0 FISli 2.0 ML*1J 2.0 SK3 S.3
CHK 1 0 . 0 li>\M 2.0 yTVL 6.2 TUR 2.0
c o n m a n d s fútntin* •
time are available in w e e k 3, compared l o -10 hours in lhe other weeks. Suppose that we
want t o see h o w m u c h extra profit c o u l d be gaincd f o r each extra hour in week 3. W e can
acoomplish this by rcpcatcdly s o l v i n g . displaying the solutk>n values, and incrcasing
âvâil(3J:
ampl: aolvo;
MINOS S . S : o p t i m a l s o l u t i o n í o u n d .
I S i t e r a t i o n s . o b j e c t i v e 515033
a m p l : diaplay Total Profit >ataalT. aona;
a m p l : option diaplay lcol 0;
a m p l : option arzit zaro roxra 0;
a m p l : diaplay Mako >ataolT. aona;
a m p l : diaplay Sol 1 >ataolT. aona;
a m p l : option diaplay lcol 20;
a m p l : option arzit zaro roxra 1;
a m p l : diaplay Inv >ataolT. aona ;
solve :
display Total_Proíit >steelT.sens:
o p t i o n d i s p l a y _ l c o l 0:
o p t i o n ccni t _ z e r o _ r o w s 0:
d i s p l a y Ma k e > s t e e l T . s e n s :
d i s p l a y Se 11 > s t e e l T . s e n s :
o p t i o n d i s p l a y _ l c o l 20:
o p t i o n ccni t _ z e r o _ r o w s 1:
d i s p l a y Inv > s t e e l T . sons:
l e t a v a i l 1 3 1 := a v a i l U l «• 5 :
258 CQHVX4D SCR P T S C H í f T E R 13
ampl: c o d o l ataalT.xsod;
a m p l : data ataalT.dat;
a m p l : ccnxzands ataalT. sal/
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
I S i t o r a L i o n s . o b j o c L i v e S1S033
a m p l : ccnxzanda ataalT. aalj
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
1 i t o r a L i o n s . o b j o c t i v o S32 033
a m p l : ccnxzanda ataalT. aalj
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
1 i t e r a t i o n s . o b j o c t i v o S49033
a m p l : ccnxzanda ataalT. aalj
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
2 i t e r a t i o n s , o b j o c t i v o SGS193
ampl:
<AII output from the d i s p l a y command & redirected ti> the file steelT.sens,
although w e could just as wxrll have made it appear on the screen.)
In th& and many other cases, you can substitua i n c l u d e for corerKinds. In gen-
eral it is best to use ccrerKinds within command scripk. however, to avoid uncxpectcd
interactions with r e p e a t , f o r and i £ statcmcnts.
a m p l : izodal ataalT.xsod;
a m p l : data ataalT .dat;
a m p l : for {1..4) oonudl ataalT.aal;
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
I S i t e r a t i o n s . o b j o c t i v o S1S033
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
1 i t e r a t i o n s , o b j o c t i v o S32 033
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
1 i t e r a t i o n s , o b j o c t i v o S49033
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
2 i t e r a t i o n s , o b j o c t i v o SGS193
ampl:
SECT C N 132 TERAT N G OVER A S E T THE r o * STATEVENT 259
m s d e l r. t_oc l T . mad:
data s t e e l T. daL;
£or (1. .4} (
solvo:
d i s p l a y T o t a 1_ P r o £ i t > s t e e l T . s e n s :
o p t i o n d i s p l a y _ l c o l 0:
o p t i o n c c n i t _ z o r o _ r o w s 0:
d i s p l a y Make > s t e e l T . s e n s ;
display Sell >steelT.sens;
o p t i o n d i s p l a y _ l c o l 20;
o p t i o n c c n i t _ z e r o _ r o w s 1:
display Inv >steelT.sens;
let availUl :=avail[3J + S:
}
lf thisscript isstored in s t e e l T . s a 2 , then the whole iterated sensitivity analysis i s c a r •
ried out by typing
This approach lends t o be clearer and eaiier t o w o r k whh, panicularly as wxr m a k e the
l o o p n*>re sophisticatcd. A s a first example, consider h o w w e would g o a b o u t c o m p i l i n g
a table o f the objective and the dual value on constraint T i r r » e [ 3 ] , for successivc values
of a v a i l ( 3 ) . A script for l h a purpose ii s h o w n in Fjgure 13-1. After the nnxlel and
daia are read. the script provkftes addhional declaraiions f o r the table o f values:
s e t AVA1L3:
param a v a i l 3 _ o b j (AVA1L3}:
param a v a i l 3 _ d u a l (AVA1L3}:
íor ( a i n AVA1L3} (
l e t a v a i l 131 : = a :
solve:
l e t a v a i l 3 _ o b j lal : = T o t a l _ P r o £ i t :
l e t a v a i l 3 _ d c a l l a 1 : = T i m e l 31 . d u a l :
}
W e see here that a f o r l o o p can be o v e r an arbhrary set, and that the index running o v e r
the set ( a in thts c a i e ) can be used in statemenfc within the loop. After the l o o p ii c o m -
260 CCWV/NDSCRPTS CHÍFTER 13
m o d e l s L e e l T . mod:
data s t e e l T . d a t ;
o p L i o n s o l v o r . msg 0:
M L AVA1L3;
param a v a i l 3 _ o b j ( A V A I L ) } ;
param a v a i l 3 _ d u a l (AVAIL3};
l e t A V A I L 3 : = a v a i l 13] . . a v a i l l 3 ] «- I S b y 5:
íor (a in AVAIL3} (
l e L a v a i l 13] : = a :
solve:
leL a v a i l 3 _ o b j Ia] : = T o t a l _ P r o f i t :
l e L a v a i l 3 _ d u a l l a | : = T i m e [ 31 . d u a l :
>
diaplay avail3_obj. a v a i l 3_dual;
a m p l : caazanda atoolT.aa3;
i avail3_obj avail3_dual :=
32 S1S033 34 00
37 S32033 34 00
42 549033 34 00
47 S 65193 29B0
In this e x a m p l e w e have suppressed lhe messages from the solver, by ineluding the c o m -
mand o p t i o n s o l v e r _ m s g 0 in the script
A M P L ' * f o r loops are also convenicnt for generating formattcd tables. Suppose that
after solving lhe multi-perkxl produetion problem, \V>Í want display sales both in tons
and as a percentage o f the market limit. W e c o u l d use a d i s p l a y c\>mmand t o producc
a table like this:
a m p l : diaplay ( t in 1 . . T , p in PROD)
ampl? (Soll [p, t ) , 100* Soll [p, t)/xaarkot [p, t ) ) /
i Selllp.tJ 100* S e i 1 [ p , t J / m a r k e t ( p , 11 :=
1 bands 6000 100
1 coils 307 7 .. 6 7 5
2 bands 6000 100
2 coils 2 500 100
3 bands 1400 35
3 coils 3500 100
4 bands 2 000 3 0 . .7 692
4 coils 4200 100
SECT C N 132 TCRAT N G OVER A S E T THE roat STATEVENT 261
By writing a script thai uses the p r i n t £ c o m m a n d ( A . 16), w e can create a much more
e f f e c t i v e table:
a m p l : ccnxrandfl atoolT.tablj
SALES bands coils
week 1 G000 100.0% 307 7 .7%
wock 2 G000 100.0% 2500 100.0%
wock 3 1399 3S.0% 3S00 100.0%
wi«k 4 1999 30.8% 4200 100.0%
printf "\nSALES":
printf ( p i n P R O D } : "%14s p:
printf "\n":
for ( t in 1..T} (
p r i n t f "wock %d". t:
f o r ( p i n PROD} (
p r i n t f "%9d". Selllp.tl:
p r i n t f " % 7 . 1 f % % " . 100 * S o l l l p . t l / m a r k c t l p . 11 :
>
printf "\n":
the c h o i c e is the same every time: the Figure 13-2 script relies on this consistency t o
en&ure that ali o f the entries in one cohimn o f the table refer t o the same product.
c o t AVAIL3 d e f a u l t ( > ;
param a v a i l 3 _ o b j (AVA1L3};
param a v a i l 3 _ d u a l (AVAIL3}:
.cot A V A I L 3 d e f a u l t ( } :
param a v a i l 3 _ o b j (AVAIL)};
param a v a i l 3 _ d u a l (AVAIL)};
param a v a i 1 3 _ s t e p : = S :
ropeat (
solve:
l e t AVAIL3 : = AVAIL3 union (availl31>:
l e t a v a i l 3 _ o b j l a v a i 1(3 J J := T o t a l . P r o f i t :
l o t a v a i l 3 _ d u a l l a v a i l l 3 ] J : = T i m o l 31 . d u a l :
l o t a v a i l 131 : = a v a i l 131 «- a v a i l 3 _ s t o p :
} u n t i l T i m o 131 . d u a l = 0:
toward the beginning o f Fjgure 13-3 this e f i e c t ; it states that solution values are t o be
rounded t o 10 significam digits. This and related rounding options are discussed and
ilhistratcd in Section 12.3.
N o t e finally that the script declares set A V A I L 3 as d e f a u l t {} rather than = {}.
T h e former ali ow s A V À I L 3 t o be changed by l e t c o m m m d s as the script proceeds.
whereas the latter permanently defines A V A I L 3 t o be the empty s e t
or a group o f commands:
ií Make [ - c o i l s - . 2 | < 1500 t h e n
p r i n t í -under 1500\n-;
else {
p r i n t í - a t l e a s t 1500\n-;
l e t m a r k e t l - c o i l s - . 2] : = m a r k e t [ - c o i l s - . 2 ] * 0.9:
}
A M P L executes these commands by first cvaluating the l o g i c a l expressk>n f o l l o w i n g i£.
If the exprcssion is true, the cx>mmand or cx>mmands f o l l o w i n g t h e n areexccutcd. If the
exprcssion is false, the command or cx>mmands f o l l o w i n g e l s e , i f a n y , are exccuwrd.
T h e i £ command is most useful for regulating the fiow o f control in scripts. In F i g -
ure 13-2. wxr cx>uld suppressany occuriences o f 100% by placing the statement that prints
Selllp.t)/market[p.t) insideanií:
ií S e l l l p . t | < m a r k e t [ p . 11 then
p r i n t í - % ? . l í % % - . 100 * Selllp.tl/market(p.tl;
else
printí -
In the script o f Figure 13-3, we can use an i £ command inside the r e p e a t kx>p t o test
whether the dual value changcd since the prevk>us pass through the kx>p, as shown in
the script o f Figure 13-4. This l o o p creates a table that exactly one entry f o r each d i f -
ferent dual v a l u e d i s o o v e r e d .
T h e statement following t h e n or e l s e can itself be an i £ statement. In the format-
ting example (Figure I3-2X could handlc both 0% and 100% specially by writing
ií S e l l l p . t| < m a r k e t [ p . 11 then
ií Selllp. t| = 0 then
printí -
else
printí -%?.lí%%-. 100 * Selllp. t|/marketlp.tl :
else
printí -
ií S e l l l p . t | = 0 then
printí -
else ií Selllp.tl < marketlp.tl then
p r i n t í - % 7 . 1 í % % - . 100 * S e l l l p . t l / m a r k e t l p . t j :
else
printí -
266 CQHVX4DS C R PTS C H í f T E R 13
msdel s t e e l T .nüd; d a t a s t e e l T . d a t :
o p L i o n s o l u t i o n p r e c i s i o n 10: o p L i o n s o l v e r . msg 0:
s e t AVA1L3 d e f a u l t ( } :
param a v a i l 3 _ o b j ( A V A 1 L 3 } ;
param a v a i l 3 _ d u a l (AVA1L3}:
l e t a v a i l l 3] : = 1 ;
param a v a i 1 3 _ c t e p : = 1 ;
param p r e v i o u s _ d u a l d e f a u l t Infinity:
lf h is. there is nothing t o be done for this value o f a v a i l 131, and the c o n t i n u e
statement j um ps k> the end o f t h e currcnt pais: execution resumes w h h the next pass,
staning at the beginning o f the loop.
A f t e r adding an entry k> the table. w e test t o see i f t h e dual value hai fallen t o zero:
SEC7 CN 13S TttMNATNG A LOOP BRZXJ. A N D cccr?zzrjz 267
l e L a v a i l ( 3] : = 0 :
param p r e v i o u s _ d u a l deíaulL InfiniLy:
repeaL (
l e L a v a i l ( 3 ] : = a v a i l ( 3 1 + 1:
solve:
i£ Time ( 3 ] . d u a l = p r e v i o u s _ d u a l Lhen conLinue:
If it has, lhe l o o p is donc and the b r e a k statement jumps out: execution passes t o the
d i s p l a y command that f o l l o w s the l o o p in the script Since the r e p e a t statement in
this example has n o w h i l e or u n t i l condhion, it relies on the b r e a k statement f o r
termination.
W h e n a b r e a k or c o n t i n u e lies within a nested kx>p. it applies only t o the inner-
most kx>p. This convention gcnerally ha* the desired e f l e c t . A s an example, considcr
how could expand Figure 13-5 *> perform a separa te sensitivity analysis on each
avail [tj. T h e r e p e a t l o o p woukl be nested i n a £ o r { t in 1 . . T ) kx>p, but the
c o n t i n u e and b r e a k statements would apply k> the inner repeat as before.
There d o exist situatk>ns in which the l o g i c o f a script requires breaking out o f multi-
pie loops. In the script o f Figure 13-5, for instance, w e can imagine that instcad o f stop-
ping w h e n T i r r » e [ 3 ] . d u a l iszero.
\V>Í want t o stop when T i r r v e l t l . d u a l falls b e l o w 2700 for any t . It might seem that
one w a y t o implement this criterk>n is:
f o r ( t in 1..T>
if Time[Ll.dual < 27 00 L h e n break:
268 CQHVX4DS C R PTS C H í f T E R 13
This statement d o e s not have the dcsircd e f T e c t howxrver, because b r e a k applies only t o
the inner f o r kx>p that contains it. rather than k> the outer r e p e a t l o o p a s w e ilesire. In
such situations. can g i v e a nante t o a loop, and b r e a k or c o n t i n u e can s p e c i f y by
nante the l o o p k> which it should apply. Using this feature. the outer l o o p in our example
could be named s e n s _ l o o p :
repeat sens_ l o o p (
and the test for ter mi na ti on inside it could refer t o its name:
for (t i n 1. . T >
if Time(t].dual < 2700 t h e n b r e a k scns_loop:
<2>ampl: atop
s t e e l T . sa7 : 4 <36) option ...
<2>ampl: atop
s t e e l T . sa7 : 5 <66) option ...
<2>ampl: atop
steelT.sa7:l1(167J let ...
<2 >ampl :
SECT C N 136 S T E F P N 3 THFOJGH A PT 269
<2>ampl: atop
s t e e l T . sa7 : 1 7 <317) continue ...
<2>ampl: atop
s t e c l T . sa7 : 1 S<2 37 J let ...
<2>ampl: atop
steelT.sa7:16<270) solve ...
<2>ampl: atop
steelT.sa7:17<2B0j if ...
<2>ampl: atop
steelT.sa7:19<331J let ...
< 2 > a m p l : diaplay avail 13J , Tiiso(3) . dual, proviouo dual;
a v a i l 131 = 2 3
T i t n c l 31 . d u a l = 3S00
p r e v i o u s _ d u a l = 3G20
<2 >ampl :
T h e cx>ncatenatk>n operator & takes two strings as operands, and returns a string con-
sisting o f the left operand followed by the right operand. H>r example, given the sets
NUTR and FOOD defined by d i e t . r » c d and d i e t 2 . d a t (Figures 2-1 and 2-3), you
could use concatcnation to define a set NUTR_FOOD whose members represem nutrient-
food pairs:
ampl: c o d o l dlot.xsod;
a m p l : data diot2.dat;
a m p l : diaplay NUTR, FOOD;
s e t NITTR : = A B l B2 C NA CAL;
s e t FOOD : = BEHF ClIX F1S1J 1JAM MCU MTL SPG TUR:
ampl: aat NUTR FOOD i» aotof ( i in JK7ZR, j in FOOD) i í " " í jj
a m p l : diaplay NUTR FOOD;
s e t NtxrR_F(X>D : =
A-BKKF Bl ,_BIÍ KF B2_BEKF CL-BKKF NA. _BKKF CAL_BKKF
A_CHK Bl_CllK B2_CllX C_ClIK NA..C1JK CAL_CHK
A_F1SU Bl _F1 Sll B2 _F1 Sll C_F1S1I NA._F1 Sll CAL_F1SU
A HAM Bl 11»\M B2_HAM C_11AM NA. 11AM CAL 11 AM
A.MCH Bl B2_>CU c_ycii NA_>CH CAL_MCH
A . MTL Bl W L B2 OTL c_yrrL NA. m L CAL_MTL
A_SR3 Bl_SPQ B2_SPQ C_SKJ NA._SPG CAL_SB3
A_TUR Bl_TUR B2_TUR C_TUR NA._TUR CAL_TUR:
This is not a set that you \vx>uld normally want to define, but it might be useful if you
have to read data in which strings like • B 2 _ B E E F " appear.
SECT-ON 1 i 7 WANRJLATP»3CHí«/C7mSTRM3S 271
param T i n t e g e r > 1;
s e t WBBXS o r d e r e d = s e t o í ( t in l..T> *WBBX" & t :
Numeric operands to & are ai ways convcned *> full precision (or equivalently, to %. Og
format) a* defined in Section A.16. The conversion thus produces the expected results
for concatenation o f numérica] constants and o f Índices that run over sets o f integers or
constantv. as in our examples. Full precision conversion of computed fractional values
may sometimesyiekl surprbing results. howxíver. The foDowing var ia tion on the preced-
ing example would seem to create a set o f members WEEKO. 1, WEEKO. 2, and so forth:
param T i n t e g e r > 1;
h^tv the length given hy the third argument, or extends tothe end o f the string if no third
argument ti given. An empty string is returned if the seoond argument is greater than the
length o f the first argument. i>r if the third argument is less than I.
A s an example comhining several o f these functions. suppose that you want to use the
nnxlel from d i e t . r>cd but to supply the nutrition amount data in a table like this:
param: NUTR_KOOD: a m l _ n u t r :=
A_HKBF GO
Bl_BBKF 10
CAL_BKEF 2 9S
CAL_C11X 7 70
Then in addhion to the declarations for the parameter a m t used in the model.
s e t NITTR:
s e t FOOD:
you would declare a set and a parameter tohold the data from the "nonstandard" table:
s e t Nl/rR_FCX)D:
param amL_nuLr (MtTTR_FOQD} >= 0:
T o use the nnxlel. you need to write an assignment o f some kind to get the data from set
NUTR_FOOD and parameter amtjtixxtr into sets NUTR and FOOD and parameter a m t .
One solution is toextract the sets first, and then convert the parameters:
s e t NITTR = s e L o f (ij
i n NtTTR_F00D}
subsLr(ij .l.maLch(i J-1J ;
s e t FOOD = SOLO £ ( i j i n NtTTR^FOOD}
s u b s L r ( i j ,maLch(i j , J«-lJ:
param amL ( i i n NITTR. j i n FOOD} = a m t _ n u L r ( i U U jl:
As an alternative. you can extract the sets and parameters together with a script such as
the following:
AMPI. providos two other functions. s u b and g s u b , that look for the second argu-
ment in the first, like r w i t c h , but that then substitua a third argument for either the first
occurrcnce ( s u b ) or ali oecurrenees ( g s u b ) found. The second argument o f ali three o f
these functions is actually a regular expréssiott: if it contains certain special characters, it
is interpreted ai a pattern that may match many sub-strings. The paitern • * B [ 0 - 9 1
for example, matches any sub-stringconsisting o f a B followod by one o r m o r e digits and
then an underscx>re. and occurring at the beginning o f a string. Details of these feaiures
are given in Section A.4.2.
msdel d i o t . m o d :
SOt CASES = 1 . . 3;
í o r ( j i n CASES} (
reset data:
data ( " d i o f & j & - . d a t - ) ;
solve:
d i s p l a y Buy >< - d i e t " & j & " . o u t " ) í
}
msdel s c h s d . m o d ;
data sched.dat:
option solver cplex:
s e t D1R1 = ( - p r i m a i - . - d u a l - } :
s e t D1K2 = ( - p r i m a l o p t - , - d u a l o p t - } ;
í o r ( i i n Dl K l . j i n D1K2} (
o p t i o n c p l c x _ o p t i o n s (L & m m & j) :
solve:
>
274 CQHVX4D S C R PTS C H í f T E R 13
The loop in this ser ipt solves the same problem four times, each using a dilYerent pairing
o f thcdireclives p r í r r u i l and d u a l with the d i r e e t i v e s p r i r r u i l o p t a n d d u a l o p t .
Examples o f the use o f string expressions in the t a b l e statement k> work with mul-
liple databaie files, tables, or columns, are presented in Section 10.6.
Coftyrçht O2003by RobcrtFourer. DfevkJ M.Gay aikJ B r i » W . KCTTÚ&\JJ\
14
Interactions with Solvers
This chapter describes in mote detail a variety of mechanisms used by AMPl. to con-
trol and adjust the problems sent to solvers. and to extract and interpret information
retumed by them. One of the most importam is the presolve ph^e. which pcrforms sim-
plifications and transformatk>ns that can o f l e n reduce the size o f the problem actually
seen by the solver: this t% the lopic o f Section I I. I. Suffixes on model components per-
mit a variety o f useful information to be returncd by or cxchangcd whh advanced solvers.
ai described inSections 142 and 14.3. Named problems enabkr AMPl. scripts to manage
multiple problem instances within a single ntxlcl and carry out iicrative proccdures that
alternate between very dilTerent models, a s w e s h o w inSections 11.4 and 14.5.
14.1 Presolve
AMPl.'s presolve phase attempts to simpfify a problem instance after h has been gen-
erated but before h is sent to a solver. It runs automaticaDy when a s o l v e cx>mmand is
given or in response to other cx>mmands that generate an instance. as explained in Section
A . I&.l. Any simplificaiions that presolve makes are reversed after a solution & returncd.
so that you can view the solution in terms o f the original problem. Thus presolve nor-
mally proceeds sikrntly bchind the scenes. Its effects are only reported when you changc
option s h o v _ s t a t s from hsdefauh value o f O to I:
27S
276 N T E F V C T CNS V / T H S O L \ € R S C H í f T E R 14
a m p l : prínt {j in 1. . nvara:
ampl? var[j J. BtatuB M "pro")i varsaoo l j ) j
I n v l • b a n d s ' . 01
invl'coils'.01
a m p l : print {i in 1. . ncona:
ampl? con[i].atatua * "pro")i connarao [i] ;
l n i t w l n v [ ' bands' 1
lnitwlnv(' coilsv j
M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
S i t e r a t i o n s . o b j e e t i v e 74.27382022
SECT0N14 1 RRESCLVE 277
a m p l : print (i in 1. . ncona:
ampl? con[i) . ata tu a * " p r o ") i connarao [i] ;
DieL_Minl ' Blv ]
DioL_Minl,B2,|
D i e L . M a x ( * A" 1
s u b j e c L Lo D i e L _ M i n ( i i n M I N R B Q } :
sum ( j i n KOOD} a m L l i . j l * Buyljl >= n _ m i n [ i l ;
with n _ m i n l ' B l ' ] equal t o zero in the data. Clearly this is satisfied by any combina-
tion o f the variables, since they ali have nonnegative lowor bounds. A less trivial case is
given by D i e t _ M a x [ ' A ' 1, which is generated from
s u b j e c L Lo D i e L Max ( i i n MAXRBQ}:
sum ( j i n KOOD} a m L l i . j l * Buyljl <= n nvaxlil:
By setting each variable *> its upper bound on the left-hand side o f this constraint, w e get
an upper bound on the total amount o f the nutrient that any solution can possibly supply.
In particular, for nutrient A :
Since the data file gives n _ m a x j ' A ' 1 ai 20000, this is another constraint that cannot
possibly be violated by the variables.
F o l l o w i n g these tests, the first pari o f presolve is completed. T h e remainder consists
o f a series o f passes through the problem, each attempting t o deducvr still tighter variable
bounds from the current bounds and the linear constraints. W e present here only one
example o f the outcome, f o r the problem instance generated from m u i t i . r > c d and
r n u l t i . d a t (Figures -l-1 and 1-2):
P r e s o l v e e l i m i n a L e s 7 c o n s L r a i n L s arxi 3 v a r i a b l e s .
AdjusLed problem:
60 v a r i a b l e s , a l i linear
44 c o n s L r a i n L s . a l i l i n e a r : 16S m n z e r o s
1 l i n e a r o b j e c L i v e : 60 n o n z e r o s .
M1MDS S . S : o p L i m a l s o l u L i o n f o u n d .
41 i L e r a L i o n s . o b j e c L i v e 199S00
ampl: p r i n t ( i in 1 . . ncona:
ampl? con[i) . ata tu a * "pro")i cornarao [i] /
Demand[ ' L A N ' . ' p l a t e ' |
Mui t i [ ' GARY' . * LAN ' 1
Mui t i [ ' QARY' , ' W I I Í ' !
Mui t i [ ' C L K V , ' L A N ' 1
Mui t i [ ' C L K V , ' W I I Í ' !
Multi['PITT'.'LAN')
Multi['PITT'.'WIN')
W e can see where s o m e o!" lhe simplifications c o m e from by cxpanding lhe climinated
demand constraint
a m p l : oxpand Domand['LAN','plato')/
s u b j e c t t o Dcmarxi [ ' L A N *» ' p l a t e ' 1 :
T r a n s i ' GARY* a ' LAN ' , ' p l a t e ' J + T r a n s i ' C L E V . ' L A N ' » ' p l a t e ' 1 +
T r a n s i ' P I T T ' a ' LAN', ' p l a t e ' j = 0:
Because d e m a n d [ ' L A K ' . ' p l a t e ' 1 is zero in the data. this constraint forces the sum
o f three nonnegative variables t o be zero, as a result o f which ali three must have an
upper limit o f zero in any solution. Since they already have a l o w e r limit o f z e r o , they
may be fixed and the constraint may be dropped. T h e other climinated constraints ali
look like this:
a m p l : oxpand Kulti['GARY','LAN');
s u b j e c t t o M u l t i ( ' G A R Y ' , ' LAM' ] :
T r a n s i ' GARY' . ' LAN ' . ' b a r a d s ' 1 + T r a n s i * GARY* , ' LAN ' » ' c o i l s * 1 +
T r a n s i ' Q A R Y ' a ' LAN', ' p l a t e ' j <= 62S:
T h e y can be dropped because the sum o f the upper bounds o f the variables on the left is
less than 623. T h e s e variables were not original ly given upper bounds in the problem,
however. Instead. the second pan o f presolve deduced their bounds. For this simple
problem, it is not hard t o see h o w the deduced bounds ar s e : the amount o f any product
shipped ak>ng any one link cannot exceed the demand f o r that producl at the deitinaiion
o f the link. In the case o f the destinations L A N and M K , the total demand f o r the three
produets is leis than the limit o f 6 2 5 on total shipments f r o m any origin, making the
total-shipment constraints redundant.
l f presolve determines that any variable's l o w e r bound is greater than its upper bound,
then there can be n o solution satisfying ali the bounds and other constraints. and an error
message s printed. R>r example, here's what would happen t o s t e e l 3 . r > c d (Figure
I -5a) if \V>Í changed rnar k e t I • b a n d s • ] t o 500 when wc meant 5000:
a m p l : modol atooU.xsod/
a m p l : data atool3.dat;
a m p l : lot markot[ "banda"J i - 500;
ampl: aolvo;
inconsisLenL teimeis í o r v a r Make [ • b a n d s • 1 :
l o w e r b o u n d = 1000 > u p p e r bound = S 0 0 :
d i f f e r e n c o = SOO
infeaiibilities that are not due k> any one variable. A s an example, consider the constraint
inthis model:
lf reduce the value o f â v a i l t o 13 hours, presolve dcduccs that this constraint can't
possibly be satisficd:
a m p l : l o t avail t» 13.238929;
ampl: aolvo;
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
0 i t e r a t i o n s . o b j o c t i v e 6 1 7 S O . 00214
lf make a v a i l just slightly lowxrr, hcwrever, w e again get the infeasibility message:
a m p l : l o t avail t» 13.253923;
ampl: aolvo;
p r e s o l v e : c o n s t r a i n t Time cannot h o l d :
bDdy <= 1 3 . 2 S B 9 c a n n o t b e > = 1 3 . 2 S B 9 :
d i í í e r e n c e = -S.71429e-07
S e t t i n ? $p r e s o l v o . e p s >= G. 8 6 o - 0 7 m i g h t h e l p .
Although the l o w e r bound here is the same ai the upper bound k> six digits. it is greater
than the upper bound in fuD precision. as the negaiive value o f t h e d i f f e r e n c e indicates.
T y p i n g s o l v e a second time in this situatk>n tells A M P I . t o override presolve and
send the seemingly inconsistcnt deducvd bounds t o the solver:
S E C T - G N 14.1 RRESCLVE 281
ampl: aolvo;
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
0 i t e r a t i o n s . o b j e c t i v e 61749.99714
Ml NOS declares thai it ha* found an optimal solution. though with > C a k e [ ' b a n d s ' )
being slightly less than its lower bound e o r e n i t [ ' b a n d s ' ] í I l e i e MDMQS is applying
an internai tofcrance that a l l o w s s m a l l infeasibilities to bc ignorcd: the A M P L / M I N O S d o c -
umcntation explains h o w this tolerance works and h o w it can bc changcd. Each s o l v e r
applies feasibility tolerances in its o w n w a y , s o it's not surprising that a different s o l v e r
gives different results:
ampl: aolvo;
CPLlüí 8 . 0 . 0 : Bound i n f e a s i b i l i t y c o l u m n 'xl'.
i n í e a s i b l e problem.
1 d u a l s i m p l e x i t e r a t i o n s <0 i n p h a s e IJ
l l e r e C P L K X ha* applied its o w n presolve routinc and detected the same infeasibility
that A M P l . did. < Y o u m a y see a f e w additional lines about a 4 'suíTix'' named d u n b d d :
this penains to a direction o f unboundcdncss that you can retrkrve via A M P L ' s solver -
defined s u f f i x feature dcscribed in Scctk>n 1 4 3 . )
Situations like xht% c o m e about when the implkrd tower and upper bounds on some
variable or constraku b o d y are equal. at least for ali practical purposes. D u e t o impreci-
sion in the computations, the l o w e r bound m a y c o m e out slightly greater than the upper
bound. causing A M F L ' s presolve t o report an infeasible problem. T o circumvent this d i f -
ficuky, you can reset the option p r e s o l v e _ e p s from its default value o f 0 t o s o m e
small positive value. DifTerences between the lowxrr and upper bound are ignorcd when
they are less than this value. I f increasing the current p r e s o l v e _ e p s value t o a value
n o greater than p r e s o l v e _ e p s r w i x would changc presolve^s handling o f the problem,
then presolve d i s p b y s a message t o this elYeet such as
ever lhe upper bound mi nus the \ o w a bound on a variable or constraint body is positive
but less than the value o f option p r e s o l v e _ £ i x e p s . the variable or constraint body is
f i x e d a t the average o f the t w o bounds. If incrcasing the value o f presolve_£ixeps
t o a t most the value o f p r e s o l v e _ £ i x e p s r w i x would change the resuhs o f presolve. a
message t o thisefToct is displaycd.
T h e number o f separate messagcs displaycd by presolve is limited t o the value o f
p r e s o l v e _ v a r n i n g s . which is 5 by default. Incrcasing option s h o w _ s t a t s to 2
may elicit s o m e additional information about the presolve run. including the number o f
passes that made a dilTerence t o t h e resuhs and the values to which p r e s o l v e _ e p s and
presolve_inteps would have t o be incrcascd or dccrcaícd t o makc a dilTerence.
In addition t o the solution and relatcd numérica] values. h can be useful t o have c e r -
tain symbolic information about the results o f s o l v e commands. R>r example. in a
script o f A M P L commands. you may want t o test whether the most recent s o l v e encoun-
tered an unbounded i>r infeavible problem. Or. after you have solvcd a linear program by
the simplex metluxl. you may want t o use the optimal hasis panition to provide a g o o d
stan f o r solving a relatcd problem. T h e A M P L - s o l v e r interface permits solvers t o return
these and relatcd kinds o f status information that you can examine and use.
Solve results
A solver fin&hes its w o r k because it h^v identified an optimal solution or has encoun-
tered s o m e other terminating condition. In addition t o the values o f the variables, the
solver m a y set t w o built-in A M P L parameters and an A M P L option that provide informa-
tion about thcoutcome o f the optimi/ation process:
ampl: aolvo;
Ml NOS S . S : i n í e a n i b l c problcm.
9 iLeraLions
s o l v e _ r e s u l t vaüu»
numh.*r string inlcTpretitkin
0 - 99 solvod uptinLilsolution founJ
100-199 solvod? uptinLilsolutkin indicafcd. but emir hkely
200-2 99 iníeasible c<tn-4rxxnts cjmncit be titKficd
300-399 untourxicd abjcdivecAn be improwd witkiul limit
400-499 limit stuppcd A Imüt thJA youse* (such AS on iter.itians)
S00-S99 failure stupjx-d An c m i conditian inth: solver
Normally this status information is used in scripts. where it can be tested to distinguish
among cases that must be handled in diíTerent ways. A s an example. Figure 14-1 depicts
an AMPI. script for the diet mudei that reads the name of a nutrient (from the standard
input. using the filename - ai cxplained in Scction 9.5), a starling upper limit for that
nutrient in the diet, and a step size for rcducing the limit The loop continues running
until the limit is reduced *> a point where the problem is infcasiblc, at which point it
prints an appropr iate message and a table of solutions previously found. A representative
mn kx>ks like this:
. N
n _. u
obu jj ?J_dual
Muai
S I 000 11S.62S -0.002197 7
S4000 109.42 - 0 . 0 0 1 7 8981
S7000 104.OS - 0 . 0 0 1 7 8981
GO000 101.013 7.037S7e-19
llere the limit on sodium (NA in the data) is reducvd from 60000 in steps o f 3000. until
the problem becomes infeasible at a limit of 18000.
T h e key statement of d i e t . r u n that tests for infeaiibility is
284 N T E F V C T CNS V / T H S O L \ € R S C H í f T E R 14
model d i e t . m o d :
data d i e t 2 . d a t :
param ?J s y m b o l i c i n NUTR:
param n s t a r t > 0:
param n s L e p > 0 :
r e a d N. n s t a r t . n s L e p < - ; * read data inLcractively
s e t N_MAX d e f a u l t (}:
param N _ o b j ( N _ H A X > ;
param N _ d u a l ( N _ H A X > ;
o p t i o n s o l v e r msg 0:
for ( i i n n s L a r L . . 0 by - n s t e p } (
l e t n max[N| : = i :
solve:
i£ solve_ r e s u l t = " i n f e a s i b l e " then (
printf • i n f e a s i b l e a t %d \n\n-. i:
break:
>
let N MAX : = N MAX u n i o n ( i > ;
let N _ o b j l i ) := Total_Cost:
let N _ d u a l l i l := Dietl?J) . d u a l :
>
di solay N_ob j . N dua 1:
if s o l v e _ r e s u l t = - i n f e a s i b l e - then (
printf i n f e a s i b l e a t %d \n\n-. i:
break:
>
T h e i £ condition could equivalcntly be written 2 0 0 < = s o l v e _ r e s u l t _ n u : n < 3 0 0 .
Normally you will want t o avoid this lattcr ahernative, since it make* the script more
cryptic. It can occasionally be useful. ho\v\?ver. in making fine distinctions a m o n g dilYer-
ent solver terminatk>n conditions. K>r example. here are s o m e o f the values that the
C P L K X solver sets f o r different optimality conditions:
T h e value o f s o l v e _ r e s u l t is ' s o l v e d ' in ali o f these cases, but you can test
solve_result_nun if you need k> distinguish among them. T h e interpretaiions o f
s o l v e _ r e s u l t _ n u m are entirely solver-specific: you'11 have t o kx>k at a particular
solver' s documentation t o see w h i c h values it returns and what they mean.
A M P I . ' s solver interfaces are set up t o display a f e w lines like
SECT ON 14 2 R E T R E V N Q RESULTS FTOW SCLVERS 285
Ml NOS S . S : i n f e a s i b l c problem.
9 iterations
to summari/e a solver run that ha* fmishcd. If you are running a script that executes
s o l v e frequently, these messages can add up to a lot o f output: you can supprcss their
appear ance by setting the option s o l v e r _ m s g to 0. A buih-in symbolic para n v ter.
s o l v e _ m e s s a g e , still always contains the most reeent solver return messagc. even
when display o f the messagc ha* been turned ofT. You can display this parameter to ver-
ify its value:
Since return messages vary from one solver to the next, howxrver. for most situations a
testof s o l v e _ r e s u l t will besimpler and ksssolver-dependcnt.
S o l v e resuhs can be returned as described above only if A M P L ' s invocation o f the
solver has been suceessful. Invocation can fail because the operating system is unable to
fínd i>r execute the specified solver. or because some low-levei error prevents the solver
from attempting or complcting the optimi/ation. Ty picai causes include a misspelled
solver name, improper instailation or licensing o f the solver, insufficient resources. and
termination o f the solver process by an exeeution fault <; 'core d u m p " ) or a " b r e a k ' ' from
the keyboard. In these cases the error messagc that follows s o l v e is generated by the
operating system rather than by the solver, and you might have to consult a system guru
to track down the problem For example. a messagc like c a n ' t o p e n at8871.nl
usually indicates that AMPL is not able to write a temporary file: it might be trying to
write to a disk that is f u l l or to a directory < folder) for which you do not have write per-
mission. (The directory for temporary files is specified in option TOPDIR.)
T h e built-in parameter s o l v e _ e x i t c c d e records the successor faihire o f the most
reeent solver invocation. Initially - I, h is reset t o O whenever there has been a suceessful
invocation, and to some system-dependem non/ero vahie other wise:
ampl: roaotj
a m p l : diaplay aolvo oxiteodoj
solve. e x i t e o d e = -1
a m p l : xzodol diot.xsod;
a m p l : data diot2.dats
a m p l : option oolvor xploxj
ampl: aolvo;
Cannat i n v o k e x p l e x : No such f i l o o r directory
286 NTEFVCT CNS V/TH S O L \ € R S CHífTER 14
ampl: d i s p l a y a o l v o oxitcodo;
s o l v c o x i l c o d o = 1024
a m p l : diaplay aolvo roault, aolvo raault UUB;
solve_result = '?'
s o l v e ^ r e s u l L _num = - 1
Here lhe failed invocatk>n. due k> the mis&pelled s o l v e r name x p l e x , is reflectcd in a
positive solve_exitccde value. The staius parameters solve_result and
a o l v e _ r e a u l t _ n u í r » are a k o reset t o their initial values ' ? ' and - 1 .
I f s o l v e _ e x i t c c d e exceeds the value in option s o l v e _ e x i t c c d e _ r n a x , then
A M P l . aborto any currently executing compound statements ( i n c l u d e , ccreruinds,
r e p e a t , f o r . Li). T h e default value o f s o l v e _ e x i t c c d e _ r n a x is 0, s o that A M P l .
norma D y abons cx>mpound statements whenever a solver invocatk>n fails. A script that
sets solve_exitccde_max to a higher value may test the value of
a o l v e _ e x i t c c d e , but in general ifc interpretaiion is not consistem across operaiing
systems or solvers.
solve_result .result
solve_result_num .result_num
so 1 v c m e s s a g e .mcssage
solve. e x i t e o d e .exiLcode
minimize Total_Cost:
sum ( i i n O R I G . j in DEST} costli.jl * Transli.jl:
minimize P r e f _ o f ( i in ORIG}:
sum ( j i n DE5>r} c o s t l i . j l * Transli.jl:
A f t e r minimizing three o f these objectives, w e can v i e w the solve status values for ali o f
them:
P r e £ _ o £ . r e s u l t 1*1 : =
Coul l a r d
Ca sk i n . solvod
liazen
. solvod
Itopp
.
Iravani
.
Linetsky
.
Mehrotra
.
?Je l s o n
.
Snilowi tz
Tamhane .
Whi t e
For t h e o b j e c t i v e s that have not yet been used. the . r e s u l t sulYix is unchangcd (at hs
initial value o f ' ? ' in this case).
T h e s e same sulllxes can be applied t o the " p r o b l e m " names whose use \V>Í describe
later in this chapter. W h e n appended t o a problem name. they refer t o the nu>st reeent
optimi/ation carried out when that problem was current.
In additk>n t o pr ovkling for return o f t h e over ali status o f the optimi/aiion process a»
described above, A M P I . lets a solver return an individual status for each variable. This
feaiure is intendcd mainly for reponing the basis status o f variables after a linear program
is solved either by the simplex method, i>r by an intcrk>r-point < barrier) metluxl f o D o w e d
by a " c r o s s o v e r " routine. T h e basis status is also relevam t o solutk>ns returned by cer-
tain nonlinear solvers. notably MINQS, that employ an extension o f the concept o f a basic
solution.
In addhion k> the variables declared by v a r statements in an A M P I . model. solvers
also d e f i n e " s b c k " or " a r t i f i c i a r ' variables that are associatcd with constraints. Solver
statuses f o r these latter variables are defined in a similar w a y . as explainod later in this
sectk>n. Both variables and constraints also have an " A M P I . status" that distinguishes
those in the current problem from those that have been removed from the problem by pre-
s o l v e or by c o m m a n d s such as d r o p . T h e interpretation o f A M P I . statuses and their rela-
tionship k> solver staiuses are discussed ai the end o f this sectk>n.
288 NTEFVCT CNS V/TH S O L \ € R S CHífTER 14
T h e major use o f solver status vahies from an optimal hasie solution is t o provide a
g o o d starting point f o r the next optimi/ation run. T h e option s e n d _ s t a t u s e s , when
left at its defauh value o f I, instmets A M P L to include statuses with the information about
variables sent t o the solver at each s o l v e . Y o u can see the elTeet o f this feature in
a l m o s t a n y sensitivity analysis that re-solve» after m a k i n g s o m e s m a l l c h a n g e t o t h e prob-
lem.
A s an example, consider what happens when the multi-pcrkxl pnxluction example
from Figure 6-3 is s o l v c d repeatedly after increases o f f i v e percent in the availability o f
labor. With the s e n d _ s t a t u s e s option set t o 0, the solver reports about 18 herations
o f the dual simplex mctfuxl each time it is mn:
ampl: c o d o l ataolT3.xood;
a m p l : data atoolT3.dat;
a m p l : option aond atatuaaa 0;
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 514521.7143
18 d u a l s i m p l e x i t e r a t i o n s ( 0 i n phase IJ
a m p l : lot {t in 1..T) avail [t) Í « 1.05 • avail[t);
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 537104
19 d u a l s i m p l e x i t e r a t i o n s ( 0 i n phase IJ
a m p l : l o t {t in 1..T) avail [t) Í « 1.05 • avail[t);
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 560800.4
19 d u a l s i m p l e x i t e r a t i o n s ( 0 i n phase IJ
a m p l : l o t {t in 1..T) avail [t) Í « 1.05 • avail[t);
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 585116.22
17 d u a l s i m p l e x i t e r a t i o n s ( 0 i n phase IJ
With s e n d _ s t a t u s e s left at its defauh vahie o f I, h o w ; ver. only the first solve
takes 18 iterations. Subsequent runs take a f e w iterations at most:
Each s o l v e after the first automatically uses the variables' haiis statuses from the previ-
ous s o l v e t o constmct a starting poíni that turnsout t o b e only a f e w iterations from the
optimum. In the c a i e o f the third s o l v e , the previous basti remains optimal: the s o l v e r
thus c o n f i r m s optimality immediately and repons taking 0 iterations.
T h e f o l b w i n g discussion e x p h i n s h o w you can view, interpret. and change status v a l -
ues o f variables in the A M P L environment. Y o u don't need to k n o w any o f this t o use
optimal haies ai starting points ai shown above, but these features can be useful in c e r -
tain advanced circumstances.
A M P L r e f e r s t o a variable's solver status by appending . s s t a t u s ii> its name. Thus
you can print the statuses o f variables with d i s p l a y . A t the beginning o f a session ( o r
after a r e s e t X when n o problem has y e t been solved, ali variables have the status
none:
ampl: aolvo;
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
13 i t e r a t i o n s . o b j e c t i v e 1 1 8 . 0 5 9 4 0 3 2
a m p l : diaplay Buy.aatatua/
Buy.sstatus 1*1 :=
BKKF bas
CliX
F1S11
UAM upp
MCll upp
MTL upp
SPG bas
TUR low
T w o o f the variables. B u y [ ' B E E F ' ] and B u y [ ' S P G ' ] . have status b a s . w h i c h means
they are in the optimal basis. Three have status l o w and three u p p , indk-ating that they
are nonhaiic at lo\v\;rand upper bounds. respectively. A table o f t h e recognized s o l v e r
status vahies isstored in option sstatus_table:
290 N T E F V C T CNS V / T H S O L \ € R S C H í f T E R 14
Numbers and short strings represe nting status values are given in the first t w o columns.
( T h e numbers are mainly f o r oommunijaiion between A M P L and solvers, though you can
access them by using the suffix . s s t a t u s _ n u m in place o f . s s t a t u s . ) T h e entries
in the third column are comments. For nonbasic variables as defined in many tcxtbook
simplex mettuxls, only the l o w status is applicable: other nonbasic statuses are required
for the more general bounded-variable simplex methods in large-scale implementatk>ns.
T h e s u p status is used by solvers like MINCXS t o a c c o m m o d a t e nonlinear problems. This
is A M P L * s standard s s t a t u s _ t a b l e : a solver may substitute its o w n table, in which
case its documentai ion will indica te the interpretation o f t h e table entries.
Y o u can changc a variable's status with the l e t cx>mmand. This facilhy is some-
times useful when you want t o re-solve a problem after a small, we 11-defined changc. In
a later section o f this chapter, for example, we e m p l o y a pattcm-cutting nuxlel < Figure
14-2a) that contains the declarations
In a rclatcd script (Figure 11-3), each pass through the main l o o p steps n P A T by one,
causing a new variable C u t l n P A T ) to be created. It has an initial s o l v e r status o f
" n o n e * . like ali new variables, but it is guaranteed, by the w a y that the pattern genera-
tion procedure ti constructed, t o enter the basis as s*x>n » the expandcd cutting problem
is re-solvcd. Thus we g i v e it a status o f " b a s • instead:
l e t C u t InPATl . s s t a t u s := "bas*;
It tuxns out that this changc tends t o reduce the number o f iterations in each re-
opcimization o f the cutting problem, at least with some simplex solvers. Setting a f e w
statuses in this w a y is never guaranteed t o reduo? the number o f iterations, h o w e v e r . Its
succcss depends on the particular problem and solver, and on their intcractk>n whh a
number o f complicating factors:
not corrcspond ti> a useful starting point for lhe next s o l v e . and may not
pcoperly d e f i n e a basic solution.
• S o m e solvers. notably MOMOS, use the current vahies as wcD ai the statuses
o f the variables in constructing the starting point at the next s o l v e (unless
optionreset_initial_guesses issetto I).
Each solver ha* its o w n way o f adjusting the statuses that it reeeives from A M P L . when
necessary. t o producv? an initial basic sohition that it can use. Thus s o m e experimentation
is usually necessary ti> determine whether any particular strategy for m o d i f y i n g the sta-
tuses is useful.
For models that have several v a r declarations. A M P L ' s generic synonyms (Section
12.6) f o r variables provide a convenient w a y o f getting overall summaries o f statuses.
For example, using expressk>ns like _ v a r , _ v a r n a a > e and — v a r . s s t a t u s in a d i s -
p l a y statement. you can easily s p e c i f y a table o f ali basic variables in s t e e l T 3 .rr»cd
along with their optimal values:
ampl? ( vamamoljJ, v a r [ j ) ) j
: varrvamel j l _varljl
1 "Make l '• b a n d s '. 1 1 - S990
2 - M a k e l • b a n d s '. 2 1 - GO 00
3 - M a k e l • b a n d s '. 3 1 - 14 00
4 - M a k e l • b a n d s '. 4 1 - 2000
S -Make l ' c o i l s * . 1 1 - 14 07
G -Make l ' c o i l s * . 2 1 - 14 00
7 -Make l ' c o i l s * . 3 1 - 3S00
8 -Make l ' c o i l s * . 4 1 - 42 00
IS -lnv['coils'. u- 1100
21 - S e l l l ' ' bands * .31- 14 00
22 - S e l l l ' bands * .41- 2000
23 - S e l l l' c o i l s * .11- 307
l m p l e m e n t a t i o n s o f the simplex mcthod typically add one variable for each constraint
that they r e c e i v e from A M P L . Each addcd variable ha* a c o e f l l c i e n t o f I o r - l in its asso-
ciated constraint. and c o e f l l c i e n t s o f 0 in ali other constraints. I f the associated constraint
is an inequality. the addition is used as a " s l a c k " or " s u r p l u s " variable: its bounds are
chosen s o that it has the elYeet o f turning the incquality into an eqüivalem equation. 1 f the
associatcd constraint fc an cquality ti> begin with. the addcd variable isan " a r t i f i c i a r ' one
whose lower and upper bounds are both z e r o .
A n e f f t c i e n t large-scale simplex solver gains t\vx> advantages from having these 4 'lógi-
c a ! " variables addcd t o the 44 structuraT ones that it gets from A M P L : the linear program
292 N T E F V C T CNS V/TH SOL\€RS CHífTER 14
is convcrtcd t o a simplcr form, in which the only inequalities are the bounds on the vari-
ables. and the solver*s inhiali/atk>n ( o r " c r a v h " ) routines can be dcsigned s o that they
find a staning haiisquickly. Given any staning basti, a first phaic o f the simplcx method
finds a basti f o r a f e a i i b l e solution ( i f neeessary) and a sccond phase fiikis a baiis for an
optimal solution: the t w o phaies are d&tinguishcd in some solvers* messages:
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 1 3 9 2 1 7 S
27 d u a l s i m p l e x i t e r a t i o n s ( 0 i n p h a s e 1J
Solvers thus commonly treat ali lógica! variables in much the same w a y ai the structural
ones, with only very minor aJjustments t o handle the case in w h i c h lowor and upper
bounds are both zero. A baiic solution is defined by the collection o f hasis statuses o f ali
variables, stmetural and logical.
T o a c c o m n u x l a t e statuses o f logical variables, A M P L permits a solver k> return status
values corresponding t o the constraints as w e l l as the variables. T h e solver status o f a
constraint written a* the constraint name suftlxed by . s s t a t u s , is intcrprctcd ai the
status o f the logical variable aisociatcd with that constraint R>r example, in our diet
nnxlel, where the constraints are ali inequalities:
the k>gical variables are slacks that have the same variety o f statuses as the structural vari-
ables:
There are a total o f six hasic variables. equal in number t o the six constraints (one f o r
each member o f set N U T R ) ai t% ahvays the case at a basic solution. In our transportation
nnxlel. where the constraints are equalhies:
s u b j e c L Lo S u p p l y (i inORlG}:
sum ( j i n D i í S r } Transli, jl = supplylil:
s u b j e c L Lo Dcmarxi ( j i n DEST}:
sum ( i i n O R I G } T r a n s l i , j l = dcmand ( j l ;
the logical variables are artificiais that reeeive the status ' e q u ' when nonbasic. Ilere's
h o w the statuses for ali constraints might b e d i s p l a y c d using A M P L ' s generic constraint
synonyms (analogous t o the variable synonyms previously shown):
a m p l : xsodol tranap.niod;
a m p l : data tranap .dat;
ampl: aolvo;
M1NQS S . S : o p L i m a l s o l u L i o n f o u n d .
13 i L e r a L i o n s , o b j e c L i v e 19G200
One artificial variable, on the constraint D e m a n d t ' F R A ' 1, is in the optimal basis.
though at a slack value o f es&entially zero like ali artificial variables in any feasible solu-
tion. ( I n fact there must be s o m e artificial variable in every basis for this problem, duc t o
a linear dependency a m o n g the equations in the nnxlel.)
AMPL statuses
Only those variables, objectives and constraints that A M P L actually sends t o a solver
can reeeive solver statuses on return. S o that you candistingu&h these from components
294 NTEFVCT CNS V/TH S O L \ € R S CHífTER 14
thai are removed prior k> a s o l v e . a separaie " A M P I . status" is a l s o maintaincd. You
can work with A M P L statuses much like solver staiuses. by using the s u f f i x .astatus
in p b c e o f . s s t a t u s , and referring t o optk>n a s t a t u s _ t a b l e f o r a summary o f the
recognized vahies:
a m p l : irodei diotu.xood;
a m p l : data diotu. dat;
a m p l : drop Diot Min['CAL');
a m p l : f i x Buy ['SPG') i - 5;
a m p l : f i x Buy['CHK') i - 3;
ampl: aolvo;
Ml NOS S . S : o p t i m a l s o l u t i o n í o u n d .
3 i t e r a t i o n s , o b j e c t i v e S4.76
a m p l : diaplay Buy.aotatua;
Buy.astatus l*l :=
BKKF in
C11K fix
K1S1J in
HAM in
MCil in
MTL in
SPG íix
TUR in
A n AMPI. staius o f i n indkrates componente that are in the problem s e m t o the solver,
such ai variable B u y [ ' B E E F ' ] and constraint D i e t _ M i n [ ' A ' ] . Three other statuses
indicatc componente left out o f the problem:
Not s h o w n here are the A M P l . status ' u n u s e d ' f o r a variable that does not appear in
any objective or constraint. and • s u b ' for variables and constraints climinated by substi-
tutk>n (as expiained in Section 1 8 2 ) . T h e o b j e c t i v e oommand, and the p r o b l e s i
commands t o be defined later in this chapter, also have the e f f e c t o f fixing or dropping
nnxlel components that are not in use.
For a variable or constraint you will norma D y be interested in only one o f the statuses
at a time: the solver status if the variable or constraint was inchided in the problem sent
most recently *> the solver. or the A M P l . status otherwise. Thus A M P l . provides the suf-
fix . s t a t u s t o denote the one status o f interest:
ampl: aolvo;
CPLEX 8 . 0 . 0 : n a d e s e i 3
va rrxj 1 1
hacktrack 0.1
CPLttX 8 . 0 . 0 : o p t i m a l i n t e g e r solution: objective 235625
1052 M l P s i m p l e x i t e r a t i o n s
75 h r a n c h - a n d - b o u n d n a d e s
A f e w kinds o f solver settings are more complex, howxrver. in that they require separate
values t o be set for individual nnxlel components. T h e s e settings are far kx> numerous t o
be accomnnxlated in a directive string. Instead the solver interface can be set up t o r e c o g -
nize newsulYixes that the user defines specially for the solver's purposes.
A s a n example, for each variable in an integer program, C P L I i X recognizes a separate
branching priority and a separate preferred branching direction. represented by an integer
in ( O . W W ) and in ( - 1 . 1 ) respeetively. A M P L ' s C P L E X driver r e c o g n i z e s the s u f f i x e s
.priority and .direction ai giving these settings. T o use these suffixes. wvr
begin by g i v i n g a s u £ £ i x command lo define each one for the currcnt A M P L session:
With the s u f f i x values assigned ai shown, C P L E X ' s search f o r a solution turns out t o
require fewer simplex iterations and f e w e r branch-and-bound nodes:
ampl: aolvo;
CPLlüí 8 . 0 . 0 : n o d o s e l 3
v a rs e 1 1
hacktrack 0.1
CPLttX B . 0 . 0 : o p t i m a l i n L e g e r solution: objective 23SG2S
7 9 9 M1P s i m p l e x i t e r a t i o n s
G9 b r a n c h - a n d - b o u r x i n o d e s
ampl: aolvo;
CPLlüí 8 . 0 . 0 : s e n s i t i v i t y
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n : o b j e e t i v e 515033
1G d u a l s i m p l e x i t e r a t i o n s ( 0 i n p h a s e l j
s u f f i x up OUT;
s u f f i x d o * n OUT:
s u f f i x c u r r e n t OUT:
The three lines at the end o f the output from the s o l v e command show the s u f f i x
commands that are exeeuvrd by A M P I . in response to the results from the solver. These
statementv are executed automatica Hy: you do not need to type them. The argument OUT
in each c\>mmand says that these are suíllxes whose values will be written out by the
solver (in contra st to the previous exampkr. where the argument I K indicatcd sufTix val-
ues that the solver was to read in).
T h e sensitivity suffixes are interpreted as foDows. K>r variables, sufTix .current
indicates the objeetive funetion coefficicnt in the current problem, whfle . d o w n and . u p
g i v e the smallestand largest values o f the objeetive coefficient f o r which the cutrent L P
basis remains optimal:
For constraints. the interpretation fc similar except that it applics to a constraint's constam
term (the so-calkrd rjght-hand-side value):
You can use generie synonyntv (Section l2/>) to display a table o f ranges for ali variables
or constraints, similar to the tables producod by the siandalonc version o f CPLHX. (Val-
ues o f - l e + 2 0 in the . d o w n column and l e + 2 0 in the . u p column correspond to what
CPLKX calk - i n f i n i t y and * i n f i n i t y in its tables.)
For a linear program that ha* no feasible solution, you can ask CPLKX to fmd an irrt-
chuiblf infetisfole subset (or IIS): a collcction o f constraints and variable bounds that is
infcasible but that becomes feasible when any one constraint or bound is removed. lfa
small ILS exists and can be found. it can provide valuable clues as to the source o f the
infeasibility. You turn on the ILS finder by changing the i i s f i n d directive from hs
default value o f 0 to either 1 ( f o r a relatively fast version) or 2 (for a slower version that
tends to fmd a smaller ILS).
T h e following example shows how ILS finding might be applied to the infeasible diet
problem from Chapter 2. After s o l v e detects that there is no feasible solution. h is
repcated with the directive ' i i s f i n d 1':
option iis_table
0 non not in the i i s \
1 low a t l c w c r bound\
2 íix í ixed\
3 upp a t u p p e r bound\
••
Again. A M P l . shows any s u f f i x statement that ha* been executed automatically. Our
interest is in the new suffix named . i i s , which is s y m b o l i c , or string-vahicd. An
associatcd option i i s _ t a b l e , also set up by the solver driver and displayed automati-
cally by s o l v e , shows the strings that may be associatcd with . i i s and gives brief
descri pi ions o f what they mean.
Y o u can use d i s p l a y to kx>katthc . i i s vahies that have been returncd:
300 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14
This information indicatcs that the ILS consists o f four l o w e r and three upper bounds on
the variables, plusthe constraints providing the lowar bound on B2 and the upper bound
on N A in the diet. Together these restrictions have n o feasibkr solution, but dropping any
one o f them will permit a solution *> be found k> the remaining ones.
I f dropping the bounds is not o f intereu. then you may want t o list only the c o n -
straints in the ILS. A p r i n t statement produccs a concisc listing:
a m p l : prínt (i in 1. . ncona:
ampl? . con[i) . iia o "non") t _connaisa [ i J/
Dict_l ' B 2 ' 1
DicL l 'NA* 1
Y o u could concludc in this case that. t o a v o i d violating the bounds on amounts pur-
chased. you might need *> accept either leis vitamin B 2 or more sodium. or both, in the
diet. Further experimentation would be neeessary t o determine h o w much less or more.
h o w » ver. and what other changes you might need t o accept in order t o gain feasibility.
<A linear program can have several irreducible infeasible subsets. but C P L I : X ' s ILS-
finding algorithm detectsonly one 11S at a t i m e . )
v a r S u p p l y _ P r i c e (ORIG} <= 0;
v a r Dcmand . P r i c e ( D E C T } :
maximize Dual_Ship_Cost:
sum ( i i n O R I G } S u p p l y _ P r i c e ( í\ * supplylil * buildlil «•
sum ( j i n DK5?r} Dcmand . P r i c e l j J * dcmandljl:
s u b j e c L Lo D u a l _ S h i p ( i i n ORIG. j in DBST}:
S u p p l y _ P r i c e l i 1 • Dcmand_Pr i c e l j 1 <= v a r _ c o s L l i . j 1:
When ali values b u i l d [ i J are set to zero, no warehouses are built, and the primai sub-
problem is infeasible. A s a result, the dual fomuilationof the subproblem. which ahvays
hítv a feasible solution, must be unbounded.
A s the remainder o f this chapter will c x p b i n . solve a subproblem by collecting its
components into an AMPL " p r o b l e m " and then diiecting A M PI. k> solve only that prob-
lem. When this approaeh is applied to the dual subproblem from the AMPL command -
line, CPLHX returns the dircction o f unboundedness in the expected way:
The s u f f i x messagc indica tes that . u n l x i d been creatod automaticaDy. You can
use this suftlx k> display the dircctk>n o f unboundedness. which issimple in this case:
solve, the result is tcstcd for unboundcdness and an extension o f the master problem is
constmctcd accordingly. The esse ntiak o f t h e main loop are a* follows:
repeat (
s o l v o Sub;
i f D u a l _ S h i p _ C o s t <= Max S h i p _ C o s L «• 0 . 0 0 0 0 1 Lhen b r e a k ;
i í Sub. r e s u l t = " u n h o u n d o d " Lhen (
l e t rCUV : = rCUV «• 1;
l e t cut_typelnCUTl := - r a y - ;
l e t ( i i n ORIG}
s u p p l y _ p r i c e [ i.nCUTl : = S u p p l y _ P r i c e [ i 1 .unbdd:
l e t ( j i n DKOT}
d c m a n d _ p r i c e [ j . n C U T l : = Demand P r i c e [ j 1 . u n b d d :
} e l se {
l e t rCUV : = nCOT «• 1;
l e t cut_typelnCUTl := " p o i n f ;
l e t ( i i n O R I G } s u p p l y _ p r i o » [ i , nCüTl : = S u p p l y _ P r i c « [ i I :
l e t ( j i n DKST} demand p r i c e l j . r C J T l : = Dcmand_Pr i c e l j 1 ;
}
s o l v e Mas t e r ;
l e t ( i i n ORIG} b u i l d [ i j := Build[iJ;
}
An aitempt to use . u n l x i d in this context fails. however.
a m p l : ccazands trnlocld.run/
t r n l o c l d . r u n . l i n e 39 ( o í í s e t 931J:
lia d s u í í i x . unbcfci í o r S u p p l y _ P r i c e
context: l e t ( i i n ORIG} s u p p l y _ p r i c e l i .nClTT 1 : =
> » S u p p l y _ P r i c e l i l .unbdd: « <
The difíicuhy here is that A M P L scans ali commands in the r e p e a t loop before
beginning to execute any o f them. As a result it encounters the use o f . u n l x i d before
any infcasiblc subproblem ha» had a chance to cause this suffix to be defined. T o make
this script run as intended. h t% necessary to place the statement
in the script before the r e p e a t loop, so that . u n l x i d is already defined at the time the
loop is scanncd.
suffix i i s s y m b o l i c OUT;
option iis_table f\
0 ixín n o t i n Lhe i i s \
1 low a t l c w c r bouixi\
2 fix fixed\
3 upp a t u p p e r bound\
Each line of the table consists o f an integer value, a string value, and an optional com-
ment. Every string value is associated with its adjacent integer value, and with any
higher integer values that are less than the integer on the next line. Ass^gning a string
value to a .suffix-mime expression is eqüivalem to ass^gning the associated numeric
value to a . s u f f i x - m i m e _ n u m expression. The latter expressions are inhially assigned the
value 0, and are subject to any type and bound qualifiers a* described above. (Normal ly
the string values of s y m b o l i c suffixes are used in A M P l . commands and scripfc, while
the numeric values are used in communL-ation with solvers.)
T h e optional »t-uui qualifier de termines how suffix vahies inter act with the solver:
304 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14
l l e r e just one variable is assigned a sulTixed value. but o f t e n there are sulTixed values f o r
ali variables in an indexed coilection:
v a r U s e ( O R I G . DEST} b i n a r y :
l e t ( i i n ORIG. j i n D E S T }
U s e i i . j 1 . p r i o r i t y : = sum (p i n PttDD} demandlj.pl:
In this case the assignment o f suíTix values can be combined with the variable's declara-
tion:
v a r U s e ( i i n O R I G . j i n DBST} b i n a r y .
s u í í i x p r i o r i t y sum ( p i n PttDD} d e m a n d l j . p l :
W e ilhistrate these po&sibflities through a script for a basic form o f the " r o l l t r i m " or
"cutting s t o c k " problem. using a wvll-known, clcmentary cohimn-generation procedure.
In the interest o f brevity, g i v e only a skctchy description o f the procedure here, while
the references at the end o f this chapter provide sources for thorough descriptions. There
are several other examples o f generation. dccomposition. and rebxation schemes on the
A M P L wxrb site. and wc will also use a f e w excerpts from them later, without showing the
whole models.
In a roll trim problem. w e wish to cut up long raw widths o f some commodity such ai
rolls o f paper into a oombination o f smaller widths that meet given orders with ai little
waste ai possible. T h i i problem can be viewxrd ai deciding. for each raw-width r o l l
where the cuts should be madc so ai *> pnxlucc one or more o f the smaller widths that
wxrre ordered. Exprcssing such a problem in terms o f dccision variables is awkward.
howxrver. and leads to an integer program that is difllcuh to solve except for very small
insta nces.
T h e cuning optimi/ation nnxlel (Figure 14-2a) finds the minimum number o f raw
rolls that need be cut, given a collection o f known cutting patterns that may be used. This
is actually a ck>se cousin to the diet nnxlel, with the variables representing patterns cut
rather than food kems bought, and the constraints enforcing a lower limk on cut widths
rather than nutrienti provided.
T h e pattern generation nnxlel (Figure 14-2b) seeks to identify a n e w pattern that can
be used in the cutting optimi/ation, either toreduce the number o f raw rolls needed, or to
determine that no such n e w pattern existi. The variables o f this nnxlel are the numbers o f
each desired width in the new pattern: the single constraint ensures that the lotai width o f
the pattern does not exceed the raw width. W e won't try to explain the objective here.
except to note that the coefficient o f a variable ii given by its corresponding "dual
v a l u e " or "dual price" from the linear relaxationof the cutting optimi/atk>n nnxlel.
W e can search for a good cutting plan by solving these t w o problem* rcpcatedly in
alternation. First the continuous-variable relaxation o f the cutting optimi/ation problem
gcncrates some dual prices, then the pattern generation problem uses the prices *> gener-
ate a new pattern, and then the procedure repeats with the collection o f patterns extended
by one. W e stop repeating when the pattern generation problem indicatcs that no n e w
pattern can lead to an improvement. W e then have the best possible solution in terms o f
(possibly) fractional numbers o f raw rolls cut. W e may make one last run o f the cutting
optimi/ation nnxlel with the integrality restriction restored, t o gel the best integral sohi-
306 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14
s u b j e c L Lo K i 1 1 ( i i n W I D T H S } !
sum ( j i n PATTBKNS} n b r l i . j l * C u L l j l >= o r d e r s l i l ;
4 f o r each widLh. L o L a l r o l l s cuL meeLs L o L a l orders
param p r i c e (WIDTHS} d e f a u l L 0 . 0 : 4 p r i c e s f r o m c u L L i n g o p L
v a r U s e (WIDTHS} i n L e g e r > = 0:
# numbers o f each widLh i n p a L L e r n
m i n i m i zc R e d u c « d _ C o s L :
1 - sum ( i i n WIDTHS} p r i c e l i l * U s e ( i J ;
s u b j e c L Lo W i d L h _ L i m i L :
sum ( i i n WIDTHS} i * U s e l i l <= roll_widLh:
lion using the patterns generated. or w e may sim pl y round the fractional numbers o f rolls
up to the next largest integers if that g i v e s an acceptablc result.
This is the Gilmore-Gomory procedure. In terms o f our t w o AMPL mudeis. its steps
may be described as follows:
An easy w a y to initiali/c ti to gcneraie one pattern for each width, conta ining as many
copies o f that width ai will fh insidc the raw rolL These patterns elearly can cover any
dcmands, though not nccessarily inancconomical way.
A n implementation o f the Gil more-Gomory proccdure ai an AMPl. script ti shown in
Figure 14-3. The file c u t .r»c<lcontains both the cutting optimi/ation and panem gener-
ation nxxlcls in Figure 14-2. Since these m o d e k have no variables or constrainti i n c o m -
mon. it would be possible to write the script with simple s o l v e statements using alter-
nai ing objective funetions:
repeat (
objective Number:
solve:
objoctive Reduced_Coa:t:
solve:
>
Under this approach, however, every s o l v e would send the solver ali o f the variables
and constraints gene rate d by both models. Such an arrangement is inefiicient and prone
to error, especially for larger and more complex iterative procedures.
W e could instead ensure that only the immediately relevant variables and constraints
are sent to the solver, by using l i i x and d r o p commands to suppress the others. Then
the outline o f our kx>p would look like this:
repeat (
uníix Cut; restore F i l l ; o b j e c t i v e Number:
£ i x Use: drop W i d t h _ L i m i t :
solve:
>
Before each s o l v e , the prevk>usly fixed variables and dropped constraints mustalüo be
brought back, by use o f u n f i x and r e s t o r e . This approach i s e l l l c i e n t but it remains
highly error-prone, and makes scripts difllcuh to read.
A s an alternative. therefore, A M P l . allows nuxlels to be distinguished by use o f the
p r o b l e r » statement seen in Figure 14-3:
p r o b l e m C u t t i n g _ O p t : C u t . Number. Fill;
o p t i o n r e i a x _ i n t e g r a l i t y 1:
TOdel cuL.mad:
daLa c u L . d a L ;
o p L i o n s o l v o r c p l c x . s o l u L i o n ^ rourxi 6 :
o p L i o n d i s p l a y _ l c o l 0. d i s p l a y _ t r a n s p o s e -10:
l o L nPAT : = 0:
í o r ( i i n W1171*11 S } (
l o L nPAT : = nPAT 1:
loL nhrli.nPATl : = íloor (rol l_widLh/ij :
l o L ( i 2 i n W1DTHS: i2 o i } nbr(i2.nPATj := 0:
}
rcpeaL (
s o l v e CuLLing_OpL:
l e L ( i i n WIDTHS} p r i c o [ i l : = F i 11 ( x 1 . d u a l •
s o l v e PaLLern_Gen:
i £ R e d u c e d _ C o s L < - 0 . 0 0 0 0 1 Lhen (
l e L nPAT : = nPAT 1;
l e L ( i i n WIDTHS} n b r [ i . nPATl : = U s e [ i l ;
}
else break:
}
display nbr. CuL:
o p L i o n CuLLing O p L . r e l a x . i n Logra l i L y 0:
s o 1 v e C uLL i n g _ 0 p L :
d i s p l a y CuL:
s o 1 v e C uLL i n g _ 0 p L :
SECT C N 14 S NAVED FRD0LEVS 309
param r o l l _ w i d t h : = 110 :
p a r a m : W1DT1JS: o r d c r s : =
20 48
4S 3S
SO 24
SS 10
7S 8 :
restorei C u t t i n g _ O p t ai the current problem. along with its environment, and solves
the associated linear program. Then the ass|gnment
option Cutting O p t . r c l a x ^ i n t o g r a l i t y 0:
53o 1 v c C u t t i n g _ O p t :
14.5 N a m e d problems
A s our cutting-stock example has shown, the key to writing a clear and elYicient script
for alternaiing between t w o ( o r m o r e ) models lies in working with named pmí?lem.\ thai
310 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14
CPLtíX B . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 5 2 . 1
0 d u a l s i m p l e x i t e r a t i o n s ( 0 i n pha.cc IJ
CPLtíX B . 0 . 0 : o p t i m a l i n t « y ; c r s o l u t i o n : o b j e t i v e -0.2
1 M1P s i m p l e x i L e r a L i o ns
0 branch-and-bound nades
CPLtíX B . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 4 B . G
2 d u a l s i m p l e x i t e r a t i o n s ( 0 i n p h a s e IJ
CPLtíX B . 0 . 0 : o p t i m a l i n t « y ; e r s o l u t i o n : o b j e c t i v e -0.2
2 M1P s i m p l e x i t e r a t i o n s
0 branch-and-bound nades
CPLtíX B . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 47
1 d u a l s i m p l e x i t e r a t i o n s ( 0 i n p h a s e IJ
CPLtíX B . 0 . 0 : o p t i m a l i n t « y ; e r s o l u t i o n : o b j e c t i v e -0.1
2 M1P s i m p l e x i t e r a t i o n s
0 branch-and-bound nades
CPLlíX B . 0 . 0 : o p t i m a l s o l u t i o n : o b j e c t i v e 4 G . 2 S
2 d u a l s i m p l e x i t e r a t i o n s ( 0 i n p h a s e IJ
CPLliX B . 0 . 0 : o p t i m a l i n t e g e r s o l u t i o n : o b j e c t i v e -le-OG
B M1P s i m p l e x i t e r a t i o n s
0 branch-and-bound nades
nbr l * . *1
• 1 2 3 4 5 G 7 B
20 5 0 0 0 0 1 1 3
45 0 2 0 0 0 2 0 0
50 0 0 2 0 0 0 0 1
55 0 0 0 2 0 0 0 0
75 0 0 0 0 1 0 1 0
Cut [ * ] : =
1 0 2 0 3 B.2S 4 S S 0 G 17.S 7 B B 7.5
Cut l*| : =
1 0 2 0 3 B 4 5 5 0 G1B 7 B B B
represem diffcrent subsets o f nnxlel componcnts. In this scction \V>Í describe in more
detail how A M P L ' s p r o b l e s i statement is e m p l o y e d to define, use. and display named
problem*. At the end we also intnxluce a similar idea. name d environmenis, which facili-
tates switching between colleetk>ns o f A M P L options.
SECT C N 14 S NAVED FRD0LEVS 311
Uhistrations in this section are taken from the cutting-stock script and from some o f
the other example scripts on the A M P l . web site. An explanatk>n o f the logic hehind these
scripts is bcyond the scope o f this book: some sug^estions for learning more are given in
the references at the end o f the chapter.
p r o b l e m Sub: H a k o . I n v . Scll,
S t a g e 2 _ P r o í i t . Time. Balance2. Balance;
By specifying an indexing-expression after the problem name, you can define an indexed
collccik>n o f problems, such these in m u l t i 2 .run<another w e b site example):
p r o b l e m S u b l l ( p i n PROD}: R o d u c « x t _ C o s t I p J .
( i i n O R l G . j i n DlíSr} T r a n s i i . j . p 1 .
( i i n O R l G } S u p p l y l i . p l . ( j i n DKST} D e m a n d l j . p l :
For each p in the set PROD. a problem S u b l l [ p ] is defined. Its oomponents inelude
the objective R e d u c e d _ C o s t ( p l , the variables T r a n s [ i . j , p ] for each combina-
tion o f i in O R I G and j in DEST, and the constrainfc Supplyli.pl and
D e m a n d I j . p J for each i i n O R I G and each j i n DEST. respec tive ly.
312 MTEFVCT Cf*S Y/TH 30L\€RS C H í f T E R 14
T o save the trouble o f repeating an indexing expression when several components are
indexed in the same w a y , the p r o b l e r » statement also altow s an indexing expression fol-
lowvd by a parenthesi/cd list o f components. Thus for example the f o l l o w i n g would be
eqüivalem:
(i in ORIG} <Supplyl l i . p l . S u p p l y 2 l i . p l .
( j i n DEST} ( T r a n s l i . j . p l . Uscli.j.plJJ
A s these examples show, the list inside the parcntheses may c\>ntain any item that is valid
in a component list even an indexing expression f o l t o w c d by another parenthesi/cd list
This sort o f rccursion is also found in A M P I . ' s p r i n t command, but is more general
than the list formai allowxrd in d i s p l a y commands.
W h e n e v e r a variable, objective or c\>nstraint is declared, it is automatically added t o
the current problem <or ali current problems, if the most rccent p r o b l e r » statement spec-
ified an indexed collection o f problems). Thus in our cutting-stock example, ali o f Figure
14-2's nnxlel components are first placed by defauh into the problem I n i t i a l : then,
when the script o f Figure 14-3 t% run, the components are divided into the problems
C u t t i n g _ O p t and P a t t e r n _ G e n by use o f p r o b l e s i statements. A s an alternative.
can declare empty problems and then fill in their members through A M PI. dcclara-
tions. Figure 14-6 < c u t 2 . r » c d ) shows h o w this would be done f o r the Figure 14-2 nnxl-
els. Thisapproach is sometimes clearer or easier f o r s i m p l e r applications.
A n y use o f d r o p / r e s t o r e or £ i x / u n £ i x a b o m o d i f i e s the current p r o b l e m The
d r o p command hai the elYect o f removing constraints or objcctives from the current
problem, while the r e s t o r e c o m m a n d has the elTect o f a d d i n g constraints or objcctives.
Similarly, the i i x command removes variables from the current problem and the u n f i x
SECT C N 14 S NAVED FRD0LEVS 313
problem Cutting_Opt:
param nPAT i n t e g e r 0. d e f a u l t 0 ;
param r o l l _ w i d t h :
KCL PATTERNS = 1 . . n P A T :
RCL WIDTHS;
param o r d e r s (W1DT11S} > 0 ;
param n b r (WIDTHS.PATTERNS} i n t e g e r > = 0 ;
c h e c k ( j i n PATTERNS}!
sum ( i i n WIDTHS} i * n b r ( i . j l <= r o l l _ w i d t h :
v a r C u t (PATTERNS} > = 0:
m i n i m i z e Number : sum ( j i n PATTERNS} Cut ( j ] ;
s u b j e c t t o F i l l ( i i n WIDTHS}:
sum ( j i n PATTERNS} n b r l i . j l * Cutljl >=orders[i|:
problem P a t t e r n . Gen:
param o r i c e ( W I D T H S } :
v a r U s e (WIDTHS} i n t e g e r >= 0:
m i n i m i z e Reduced_Cos t :
1 - sum ( i i n WIDTHS} p r i c e l i ] * U s e [ i ] ;
subject to Width_Limit:
sum ( i i n WIDTHS} i * U s e ( i l <= r o l l _ w i d t h :
p r o b l e m M a s t e r l l : To La l _ C o s t , W e i g h t . M u l t i . Co ir/cx;
p r o b l e m S u b i 1 : R e d u c e d _ C O s t . T r a n s . S u p p l y , Demand:
to define named problems for phases I and 11 o f its decomposition procedure. By con-
t r a s t , r n u l t i l a . r u n speeifies
problem ttaster:
drop A r t i f i c i a l ; r e s t o r e Total_Cost: £ix Excess:
p r o b l e m Sub:
d r o p A r t i £_ Red uced_ C o s t : restore Reduced_Cost:
when the time comes to conven the problems to a form appropriakr for the second phase.
vSince the names J í a s t e r and S u b are used throughout the procedure. one loop in the
script sulVicestoimplcmcnt bothphases.
314 M T E F V C T Cf*S Y / T H 30L\€RS C H í f T E R 14
r e d o c l a r e p r o b l e m Mas t e r : T o t a l _ _ C o s t . W e i g h t . M u l t i . C o n v e x :
r e d o c l a r e p r o b l e m Sub: Roducod^CosL. T r a n s . S u p p l y , Demand:
Like other declarations. however. this cannot be used within a compound statement ( i £ ,
f o r or r e p e a t ) and so cannot be used in the r i u l t i l a . r u n example.
A form of the r e s e t command lets you undoany changes made to the definhion of a
problem. H>r example.
W e next describe alternatives for changing the current problem. Any change will in
general cause different objectives and constraints to be dropped. and different variables to
be fixed, with the resuh that a different optimizatk>n problem is generated for the solver.
The values associated with nnxlel components are not affected simply by a change in the
current problem, howxrver. Ali prevk>usly declared components are accessible regardless
of the current problem, and they keep the same values unless they are explicitly changcd
by l e t or d a t a statements. or by a s o l v e in the case of variable and objeetive values
and rebtcd quantities(such av dual values, slacks, and reducedcosts).
A n y p r o b l e s i statement that refers to only one problem (not an indexed colleetion
o f problem*) has the eftect o f making that problem current. As an example, at the begin-
ning of the cutting-stock script \V>Í want make first one and then the other named prob-
lem currcnt, so that we can adjust certain optk>ns in the environments of the problem*.
The p r o b l e m statements in c u t l . r u n (Figure 14-3):
p r o b l e m C u t t i n g _ O p t : C u t . Number. Pill;
o p t i o n r e l A x _ i n t e g r a l i t y 1:
p r o b l e m P a t t e r n . G e n : U s e . Rc*iuced_Cos t . Width_Limit:
o p t i o n r e l A X _ i n t e g r a l i t y 0:
serve both to define the new problem* and to make those problems current. The analo-
gous state ments in c u t 2 . r u n are simpler:
problem C u t t i n g _ O p t :
o p t i o n relAX_integrality 1:
problem Pattern_Gen:
option relAX_integrality 0:
These statements serve only to make the named problema current, because the problems
have already been defined by p r o b i e r » statements in c u t 2 .r>cd(Figure 14-6).
SECT CN 14 S NAVED FRD0LEVS 315
This form defines poteniially many problems, one for each member o f lhe sei PROD.
Subsequcnt problem statements can make members o f a collcctk>n current one at a time.
av i n a l o o p h a v i n g the form
for ( p i n PROD} (
problem Subi1(pl:
>
or in a statement such as p r o b l e m S u b l l [ ' c o i l s • ] that refers k> a particular m e m -
ber.
A s seen in previous examples. the s o l v e statement can also include a problem name.
in which c a i e the named problem is made current and then sent t o the solver. T h e eftect
o f a statement such as s o l v e P a t t e r n _ G e n is thus exactly the same as the eíTect o f
p r o b l e m P a t t e r n _ G e n f o l l o w v d by s o l v e .
a m p l : c o d o l c u t .mod;
ampl: data cut.datj
ampl: problomj
problem Initial;
T h e current problem K always I n i t i a l until other named problems have been defined.
T h e s h o v command can g i v e a list o f the named problem* that have been defined:
a m p l : ahoif probloisa;
problems: Cutting_Opt P a t t o r n^Gen
W e can also use s h o v t o s e e the variables, objectives and constraints that make up a par-
ticular problem or indexed collcction o f problems:
and use e x p a n d t o see the explicit objectives and constraints o f the current problem,
after ali data values have been substituted:
316 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14
subjoct t o Width_ L i m i t :
20*Use[201 45*Use[451 «• 5 0 » U s e l 5 0 1 «• 5 5 * U s e [ 5 5 1 «•
7 5 * U s e l 7 5 1 < = 110:
In the same way that there ii a currcnt problem at any point in an AMPI. session. there
is also a current ênvironmens. W h e r e » a problem is a list o f non-fixed variables and
non-dropped objectives and constxaints. an environment records the values of ali AMPI.
options. By naming dilTerent environments. a script can easily switch between different
collcctk>ns of option settings.
In the default nuxle o f operatk>n. which is suíTicient for many purposes, the current
environment always has the same name ai the current problem. At the start of an AMPI.
session the currcnt environment is named I n i t i a l . and each subsequent p r o b l e m
statement that defines a new named problem also defines a new environment having the
same name as the problem. An environment initially inheriti ali the option settings that
existed when it was created, but h retains new settings that are made while it is current
Any p r o b l e m or s o l v e statement thai changes the current problem alsoswitches to the
cor respondi ngly named environment, with options set accordingly.
A s an example. our script for the cutting stock problem (Figure 14-3) sets up the
nnxlel and data and then procceds as follows:
o p t i o n s o l v e r c p l c x . s o l u t i on_ round 6 ;
o p t i o n d i s p l a y _ l c o l 0. d i s p l a y _ t r a n s p o s e -10:
p r o b l e m C u t t i n g _ O p t : C u t . Number. Fill;
o p t i o n r e i a x _ i n t e g r a l i t y 1:
p r o b l e m P a t t e r n . G e n : U s e . Rc*iuced_Cos t . Width_Limit;
o p t i o n r e i a x _ i n t e g r a l i t y 0:
Options s o l v e r and three others are changed <by the first two o p t i o n statements)
before any o f the problem statements: hence their new settings are inherited by subse-
quently defined environments and are the same throughout the rest o f t h e script. Next a
problem statement defines a new problem and a new environment named
C u t t i n g _ O p t , and make* them current. The ensuing o p t i o n statement changes
r e l a x _ i n t e g r a l i t y to I. Thereafter. when C u t t i n g _ O p t is the current problem
<and environment) in the script r e l a x _ i n t e g r a l i t y will have the value I. Finally.
another p r o b l e m and o p t i o n statement do much the same for problem <and environ-
ment) P a t t e m _ G e n . e x c e p t that r e l a x _ i n t e g r a l i t y issetback t o O i n that envi-
ronment
SECT CN 14 S N A V E D FRD0LEVS 317
T h e r e s u l t o f these inhial statcmcnts tv toguarantcc a proper setup for each o f lhe sub-
sequem s o l v e statement* in the repeat kx>p. T h e resuh o f s o l v e C u t t i n g _ O p t isto
set the current environment t o C u t t i n g _ O p t , thereby setting relax_integrality
t o I and causing the linear relaxaiion o f the cutting optimi/ation problem t o be solved.
Similarly the resultof s o l v e P a t t e r n _ G e n i s t o cause the pattern generation problem
t o be solved av an integer program. W e could instead have used o p t i o n statements
within the l o o p t o switch the sening o f r e l a x _ i n t e g r a l i t y . but with th& approach
w e have kept the l o o p — the k e y part o f the script — ai simple ai possible.
In m o r e complex situatk>ns. you can declare named environments independently o f
named problem s. by use o f a statement that consists o f the key word e n v i r o n foi l o w õd
by a name:
environ Master;
Environments have their o w n name space. If the name has not been used previously ai
an environment name, it fc defined av one and isassociated whh ali o f the current option
values. Otherwise, the statement has the e f t e c t o f making that environment <and its asso-
ciated option vahies) current.
A prevk>usly declared environment may a b o be associatcd with the declaration o f a
new named problem, by placing e n v i r o n and the environment name before the colon in
the p r o b l e m statement:
Bibliography
Vaffck Chvátal, Unrar P)-ogmmmin& IreenLin ( N e w Y<rk. N Y . 1983). A general irtruduclkin lei
Imuir programming thit hxs chipten on the cutting *fc>ck problem sketchcd in Seclian 14.4 and <*i
th: Dant/jg W o l f e dcoampacition procvdure that is bdiind th: mui t i cnmples citcd in .Seclian
Marshall I"i<h.-T, " A n Applicatkim Oricnted Giádc to I.agrangian RcLvatum." Interfaces 15. 2
(1985) pp. 10-21. An mtruductian tc» the I-agrarçgiin rclixatiun proccdun» undcrlying th? L r n -
l o c 2 script o f Scction 14.3.
318 MTEFVCT Cf*S Y/TH 30L\€RS C H í f T E R 14
Robert Fourer and Dfcvid M . G i y . " E i f e r i B i c t wilh a Primai Presohe A l g c r i t i m . " In Inrgp
Sailt Opimizalhn: SíaJr <>f iiar An W . W . Ifificr, D . W . lirarn .md P. M . P w b k K , e d « , Kluwcr
Academic Pubhshers (DcrdrcchC The Nrthetlmdx, 1994) pp. 135-154. A dctailed descripúin o f
th: presolve procedure sketchcd in Sertian 14.1.
Roheit W . Haesstr. "Selcelicin and IX-sign o f liruristic PracediMW for Solvjnc Roll Trim Prc*)
Icms." Majugemenl Science M. 12 (1988) pp. 1460-1471. Descriptian* o f read ciMtiiç tfaefc
pmbleim. some amenablc tolhe fcchniques of Seclicin 144 OIKI same not.
Lcon S. I.asdon. Opiimizalinn Tlteary for Inrgt Syxkrmx. Macnúllan (New Y<rk, N Y . 1970),
reprinted by Dover (Mmeola. N Y . 2002). A clissic source for sevenú of th: decompositoon OIKJ
ccncraton pracedures betarei the script*.
Copyrçhl O 2003 by Robert Fourcr. DfevkJ M . Qay .ukJ BrianW. Kcrnigh.in
15
Network Linear Programs
319
320 PCTVOFKLNEAFRFOGRAVS C H í f T E R 15
F f c u r e 15-1: A d ir cc te d network.
makc 150.000 packages o f a certa in product in the next w e e k , as indicated by the -150 at
the left o f the diagram. T h e cilics marked N E and SE are the northc&it and southeast dis-
tribution centers, which reeeive packages from the plant and transship them t o ware-
houses at the c i t i e s o o d e d a s BOS, K W R , BWI, A T I . and M C O . (Frequent flyers will r e c o g -
nize Boston, Newark, Bahimore, Atlanta, and Orlando.) T h e s e warehouses require 90,
120, 120, 70 and 50 thousand packages, respectively, ai indLated by the numbers at the
right. K>r each intercity link there is a shipping cost per thousand packages and an upper
limit on the packages that can be shipped, indicatcd by the t w o numbers next t o the cor re-
spondi ng arrow in the diagram.
T h e optimization problem over this network is to find the lowxst-cost plan o f ship-
ments that uses only the available links, respects the specified capacities. and mcets the
requirementi at the warehouses. W e first model this ai a general network flow problem,
and then consider alternatives that speciali/e the nnxlel to the particular situation at hand.
W e conclude by introducing a f e w o f the most c o m m o n variations on the network flow
constraints.
T o w r i t e a nnxlel f o r any problem o f shipments from city t o city, \V>Í can stari by
d e f i n n g a set o f cities and a set o f links. Each link is in turn defined by a start city and an
end city, s o w e want the set o f links t o b e a subset o f the set o f ordered pairs o f cities:
ML C1T1KS:
ML LiWXS w i L h i n (CITIES cross CITIES):
SECT C N 15.1 M N W W C O S T TRATTS&<FVBVT WCC€LS 321
In the case o f the problem described by Figure 15-1. the only non/ero value o f supply
should be the one f o r PITT. where packagcs are manufacturcd and supplicd t o the distri-
bution network. T h e only non/ero values o f d e s w m d shoukl be those corresponding t o
the f i v e warehouses.
T h e c o s f c and capacitics are indexed o v e r the links:
p a r a m c o s L ( L I N K S } > = 0:
p a r a m c a p a c i t y ( L I N K S } >= 0:
a* are the dccisk>n variables. which represem the amounts t o ship over the links. These
variables are nonnegativeand boundcd by the capacities:
T h e objeetive is
minimize ToLal_CosL:
sum ( < i . j ) i n L I N K S } cost(i.j| * Shipli.jl;
which represents the sum o f the shipping costs over ali o f the links.
It remains t o describe the constraints. A t each city. the packagcs supplicd plus pack-
agcs shipped in must balance the packagcs demanded plus packagcs shipped out:
s u b j e c L Lo B a l a n c e ( k i n CXT1HS} s
s u p p l y l kl sum ( < i . k j i n L I N K S } Shipli.kl
= d e m a n d l k l «• sum ( < k . j ) i n L I N K S } Shiplk.jl:
appears within the scope o f dcfinition o f the dummy index k. the summation is inter-
preted t o run over ali c i t i e i I such that { I . K> is in LINKS. That is. the summation is
over ali links into city k: similarly. the second summation is over ali links out o f k. This
indexing oonvention, which w a s e x p l a i n e d in Section 6 2 . is frcquently useful in describ-
ing network balance constraints algcbraically. Figurei l5-2a and l5-2b display the c o m -
plete nnxlel and data f o r the particular problem depicted in Figure 15-1.
I f ali o f the variables are m o v e d k> the left o f the = sjgn and the constants t o the right
the B a l a n c e constraint beeomes:
subjecL Lo B a l a n c e ( k i n CXT1HS} s
sum ( < i . k ) i n LINKS} S h i p l i . k l
- sum ( < k . j ) i n LINKS} S h i p l k . j l
= demarxilkl - s u p p l y [ k l :
This variation may be interpretcd a s s a y i n g that at each city k. shipments in minus ship-
ments out must equal " n e t d e m a n d " . I f n o city has both a plant and a warehouse (as in
322 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
SOL C l T l K S :
soL LINKS w i t h i n <ClTIKS c r o s s C l T I K S ) :
m i n i mi zc T o L a l _ C o s L :
sum ( < i . j ) i n L I N K S } cosLli.jl * Shipli.jJ;
s u b j o c L t o B a l a n c e (k i n C l T I K S } :
s u p p l y [ k ] + sum ( < i . k j i n L I N K S } S h i p l i . k l
= demand [ k l «• sum ( < k . j ) i n L I N K S } Shiplk.jl;
p a r a m demand deíaulL 0 :=
BDS 90. BMR 1 2 0 . BWI 1 2 0 . ATL 70. M20 S0:
SK K WR 1.3 100
SK BWI o.e 100
SK ATL 0.2 100
SK MCO 2.1 100
our example), then positive net demand always indicates warchouse eities, negative net
demand indicates pbnt cities, and z e r o net demand indicates transshipment cities. Thus
w e could have gotten by with just one parameter n e t _ d e s t a n d in place o f d e m a n d and
s u p p l y , with the sign o f n e t _ d e r > a n d [ k ] indicating what g o e s on at city k. Alterna-
t i v e f o r m u l a t i o n s o f t h k kind are often found in descriptions o f n e t w o r f c í l o w n u x l e k .
SECT C N 15.1 M N W W C O S T TRATTS&<FVBVT WCC€LS 323
T h e prcccding general approach has the advantagc o f being able t o accomnnxlatc any
pattern o f supplics. demands. and links betwxxrn cities. For example. a simple change in
the data would suffice t o nxxlel a plant at one o f the distribui k>n centers. or t o a l l o w ship-
ment links between s o m e o f the warehouses.
T h e d i s a d v a n t a g e o f a general formulation is that it f a i k t o s h o w clearly what arrange-
ment o f supplies. demands and links is expected. and in fact wiD a l l o w inappropriatc
arrangements. If k n o w that the shuation will be like the one shown in Figure 15-1,
with supply at one plant, which ships t o distribution centers. which then ship *> ware-
houses that satisfy dcmand. the nnxlel can be speciali/ed t o exhibit and e n f o r c e such a
structure.
T o show explicitly that there are three different kinds o f cities in the specialized
nnxlel. \vv can declare them separately. W e use a s y m b o l i c parameter rather than a set t o
hold the name o f the plant, k> s p e e i f y that only one plant i s e x p e c t e d :
param p _ c i L y .symbolic;
M L D_C 1 T Y ;
M L W_C1TY;
There must be a link betwxren the plant and each distribution center. s o need a subset
o f pairs only t o s p e e i f y which links connect distribution centers t o warehouses:
ML W i L1.NXS w i L h i n <D_CITY c r o s s W _ C l T Y j ;
param p _ s u p p l y >= 0:
p a r a m w. domarei (W_CITY} >= 0;
These declarations a l l o w supply and dcmand t o be defined only where they bek>ng.
A t this juneture, \V>Í can d e f i n e the sets C I T I E S and LINKS and the parameters
s u p p l y and d e m a n d ai they woukl be required by our prcvk>us model:
param s u p p l y (k i n C l T l I i S } =
i f k = p _ c i L y Lhen p _ s u p p l y cise 0;
param dcmand ( k i n C l T l I i S } =
i f k i n W_CITY Lhen w demandlkl else 0:
T h e rest o f the nnxlel can then be exactly ai in the general case. as indk.-ated in Figures
15-3a and l5-3b.
324 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
param p _ c i t y symbolic;
5CL D_ClTY:
5CL W_CITY;
set DW_LINKS w i L h i n <D_C1TY c r o s s W _ C I T Y ) ;
param s u p p l y (k i n C1T1KS} =
i f k = p _ c i t y Lhen p _ s u p p l y else 0:
p a r a m demand ( k i n C l T I ES} =
i í k i n W_C1TY L h e n w demand l k ) else 0;
minimize Total_Cost:
sum ( < i . j ) i n L I N K S } cost li. j] * Shipli.jl:
s u b j o c t t o B a l a n c e (k i n C I T 1 I Í S } :
s u p p l y [ k l «• sum ( < i . k j i n L I N K S } S h i p l i . k J
= d e m a n d [ k l «• sum ( < k . j j i n L I N K S } Shiplk.jl;
Ahernatively, w e can maintain references t o the dilTerent types o f cities and links
throughout the nuxlel. This means that w e must declare t w o types o f costs. capacitie» and
shipments:
param p d _ c o s t ( D _ C l T Y } >= 0 ;
param d w _ c o s t ( D W _ L I N K S } >= 0:
param p d _ c a p ( D _ C l T Y } >= 0:
param d w _ c a p (DW_L1ÍJXS} > = 0 ;
T h e " p d " quantities are associated with shipments from the plant k> distribution centers:
because they ali relate k> shipments from the same plant they need only be indexed o v e r
D _ C I T Y . T h e " d w " quantities are associated with shipments from distribution centers
t o warehouses. and s o a r e naiurally indexed over D W _ L I N K S .
T h e total shipment cost can n o w be g i v e n as the sum o f t w o summations:
SECT C N 15.1 M N W W C O S T TRATTS&<FVBVT WCC€LS 325
param p _ c i t y := PITT ;
5CL D L C I T Y : = NB SK :
r . c l W__CITY : = ODS UMR BWI A T L MCO :
p a r a m w demand : =
BOS 90. BWR 12 0. BWI 12 0. ATL 7 0. MCO S0:
param: cosL capaciLy :=
PITT NB 2. S 2 S0
PITT SK 3.S 2 S0
minimize ToLal_CosL:
sum ( i i n D _ C I T Y } p d _ c o s L [ i l * PD_Shiplü
• sum ( ( i . j ) i n D W _ L I N K S } d * _ c o s L l i . j | * D W _ S h i p [ i . j J ;
Finally. there must be three kinds o f balance constraints. one for each kind o f cMy. Ship-
ments f r o m the plant t o thedistribution centers must equal the supply at the plant:
A t each distribution center, shipments in from the plant must equal shipments out *> ali
the warehouses:
s u b j o c L Lo D. Ba 1 ( i i n E L C I T * } !
P D _ S h i p [ i 1 = SLm ( ( i . j ) i n DW_L1NKS} DW_ S b i p [ i . j 1 ;
And at each warehouse, shipmentv in from ali distribution centers must equal the
demand:
s u b j o c L Lo W _ B a l ( j i n W__CIT¥} :
sum ( ( i . j ) i n DW_LINKS} D W _ S b i p [ i . j l = w_d«mand(j1:
Mt D_CITY:
ML W_ClTY:
ML DW_LINKS w i t h I n (D_CLTY c r o s s W_CITYJ ;
minimize ToLal_CosL:
sum ( i i n D _ C l T Y } p d ^ c o s L l i l * PD_Shiplil +
Sum ( ( i . j J i n DWJLINKS} d * _ c o s L l i . j 1 * D W j S h i p l i . j l ;
lhe lattcr f o r m facilitatesalierations thai affect only particular kinds o f cities. such as the
gene ra li/ations \V\Í describe next.
scL DL.CITY : = NB SH :
param p s u p p l y := 450 :
p a r a m w dcmand : =
BOS 90. KWR 12 0. BWI 12 0. ATL 7 0. MCO S0;
s u b j o c L Lo D. Ba 1 ( i i n E L C I T Y } :
<l-pd_lossli|) * FD_Shipli|
= sum ( < i . j ) i n D W _ L I N K S } D6C.Shipii.jl:
T h e expression *> lhe left o f the = s^gn has been modifiod t o reflect the fact that only
<l-pd_loss[i)} • PD_Shipti) packages arrive at city i when ?D_Shipti)
packages are shipped from the plant.
A similar variaiion o c c u r s when the flow & not measured in the same units throughout
the networic. If dcmand is reported in canons rather than thousands o f packages. f o r
example. the model will require a parameter t o represem packages percarii>n:
s u b j o c L Lo W B a l ( j i n W _ C I T V } í
sum ( < i . j ) i n DW_ L I N K S } <1000/ppcJ * DW_ S h i p l i . j 1
= w. dcmand [ j | :
set IWTKR:
This dcfinition ensures that n o road begins at the exh o r e n d s at the entrance.
N e x t , thecapacity and trafTic load are defined f o r each road:
SECT C N 15.2 OTHER NE"TY/CFK WCC€LS 329
data:
sot IWTKR := a b C d o £ g ;
param c n t r := a ;
param o x i L := g ;
ROADS: cap : =
a b SO. a c 100
b d 40. b c 20
c d 60. c £ 20
d c SO. d £ GO
c g 70. f 9 70 ;
T h e constrainfc say thai except f o r lhe entrance and exit. f b w into each inter section
equals flow out:
s u b j e c t t o B a l a n ç o ( k i n IWTKR d i f f ( c n t r , o x i L } } :
sum ( ( i . k ) i n ROADS} T r a £ f ( i . k l
= sum ( ( k . j ) i n ROADS} T r a £ £ ( k . j l :
Given these oonstraints. the f l o w out o f the entrance must be the total f b w through the
network, which ti t o b e maximi/ed:
m a x i m i z e I £ n L e r i n g _ T r a £ £: sum ( ( e n L r . j J in ROADS } T r a í í [ e n L r , j 1 :
l f you were to use the optimal solution t o any o f our models thus far, you would have
t o send each o f the packages, cars, or whatever a l o n g s o m e path f r o m a supply ( o r
entrance) node t o a demand (or e x i t ) node. T h e values o f the dccision variables d o not
330 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
directly say what the optimal paths are, o r h o w much f l o w must g o on each one. Usually
it is not t o o h a r d to deducc these paths. h o w e v e r , cspecially when the network ha* a regu-
lar or special structure.
I f a network ha* just one unit o f supply and one unit o f demand. the optimal solution
assumes a quite dilTerent nature. T h e variable associatcd with each are is ehher 0 or I,
and the ares whose variables have value I c o m p r i s e a minimum-oost path from the supply
node t o the demand node. O f t e n the " c o s t s " are in fact times or distances. s o that the
optimum gives a shortest path.
Only a f e w changes need be made to the maximum f b w nuxlel o f Figure 15-6 t o turn
it into a shortest path nuxlel. There are still a parameter and a variable associated with
each road from i lo j , but w e c a l l them t i m e [ i . j ] and U s e t i , j J, and the sum o f
their pnxluct* yields the objective:
Since only those variables U s e [ i . j ] on the optimal path equal I . while the rest are 0,
this sum does correetly represent the total time to traverse the optimal path. T h e only
other changc is the additk>n o f a constraint toensurc that exactly one unit o f flow is avail-
able at the entrance t o the network:
T h e complete nuxlel is shown in Figure 15-7. If w e imagine that the numbers on the ares
in Figure 15-5 are travei times in minutes rather than capacities, the data are the same:
A M P L finds the sohition as f o l l o w s :
T h e best known and most w i d e l y used special network structure is the * ' b i p a n i t e ' '
structure depicted in Figure 15-8. T h e nodes fali i n t o t w o groups. one serving a* origins
o f flow and the other as destinations. Each are conncct* an origin t o a destination.
SECT C N 15.2 O T H E R NETY/CFK WCC€LS 331
seL IWTKR : = a b c d e f g ;
param e n L r := a ;
param e x i L := g ;
ROADS: Lime : =
a b SO. a c 100
b d 40. b e 20
c d 60. c £ 20
d e SO. d £ 60
e g 70. £ 9 70 ;
s e L PHDPLK:
s e L PROJHCTS;
seL ABIL1T1KS w i L h i n ( PI*)PLK c r o s s PROJKCTS) :
332 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
F i g u r e 15-9: Assignmcntmodel(netâsgn.mod).
that are not s o quickly comprehendcd. T h e more complex and realistic the network, the
worse the problem. Indecd. it can be hard t o tell whether a model*s algebraic constraints
represem a valid collcction o f flow balancei on a network, and consequently whether spe-
cializod network optimi/ation software (described later in thischapter) can be used.
AlgebraL- formulations o f network flows tend t o be problematical because they are
constmcted explicitly in term* o f variables and constraints. while the nodes and ares are
merely implicit in the way that the constraints are struetured. feople prefer t o approach
network flow problems in the opposite w a y . They imagine g i v i n g an explicit dcfinition
o f nodes and ares. from which f l o w variables and balance constraints implicitly arise. To
deal with this shuation. A M P L provides an alternative that allows network concepts t o b e
declared directly in a nnxlel.
334 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
In rewriting the nnxlel o f Figure 15-2a using n c d e and d r e , w e can retain ali o f the
s e t and p a r a m declarations and associated data. T h e changes aíícct only the three dec-
l a r a t i o n s — m i n i m i z e , v a r . and s u b j e c t t o — that d e f i n e the linear p r o g r a m
There is a node in the itetwork for every member o f the set C I T I E S . Using a n c d e
declaratk>n. w e c a n say this directly:
T h e key wx>rd n e t . i n stands for 4, net input", that is. the flow in minus the f l o w out. s o
this declaration says that net f b w in must equal net demand at each node B a l a n c e [ k ] .
Thus it says the same thing as the constraint named B a l a n c e [ k ) in the algebraic ver-
sion, except that h uses the concise temi n e t _ i n in place o f the lengthy expressk>n
Indeed. the syntax o f s u b j e c t t o and n c d e are practicaDy the same except f o r the w a y
that the conservation-of-llow constraint is stated. ( T h e keywxwd n e t _ o u t may a b o be
used t o stand for flow out minus f b w in, s o that w e c o u l d have written n e t _ o u t =
supply [k] - demand[k].)
There i s a n are in the network for every pair in the set L I N K S . This t o o can be said
directly, using an a r e declaration:
minimize ToLal_CosL:
SECT C N 15.3 C€<XARN3 NFTY/OFK WOC&S BV«OTOCAND 335
set C1T1BS:
ML links within <ClTllíS c r o s s C1T1BSJ:
minimize Total_Cost;
node F l a n L : neL_ouL = p _ s u p p l y :
node D i s t ( i in D _ C l T Y } :
n o d e Whse ( j i n W _ C I T Y } : n e t _ i n = w_d«mand[jl;
SOL D _ C 1 T Y :
SOL W_CXTY;
soL m^âZNXS w i t h i n ( D _ C I T Y c r o s s W_ClTYJ :
T h i i network has t w o kinds o f ares. There is an are f r o m the plant l o each member o f
D _ C I T Y , which can be declared by:
And there is an are from distribution center i to warehouse j for each pair { i , j > in
DW.LINKS:
T h e condition net_out > = 0 implies that the f l o w out o f node Entr _Int may be any
amount at ali: this is the proper condition, since there is n o balance constraint on the
entranevr node. A n anak>gous comment applics t o the condition f o r node E x i t _ I n t .
There i s o n e are in this network f o r each pair { i . j J in the set ROADS. T h u s the dec-
laration should look somcthing like this:
Since the aim ti t o maximi/e the total trafTic leaving the entrance nixle, the are is g i v e n a
c o e f Y i c i c n t o f I in the objective if and only if i takes the value entr. W h e n i d o e s t a k e
this value, h o w e v e r , the are is specified to be from Inter s e c t i o n [entr ] , a node
that does not exist: the are should rather be from node E n t r _ I n t . S i m i b r l y , when j
takes the value exit, the are should not be t o Intersection!exit1, l>ut t o
338 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
E x i t _ I n t . A M P L w i l l catch these errors and issue a message naming one o f the nonex-
istent nodes that has been referenced.
It might seem rcasonablc t o use an i f - t h e n - e l s e to g e t around this problem, in the
following way:
T h e special indexing expression bcginning with i í works much the same w a y here as it
does for constraints <Scctk>n 8.4); the f r o m or t o phrase is proccsscd if the condition
following i f is tnie. Thus T r a í f l i . j 1 is declared t o b e from E n t r _ I n t if i cquals
e n t r , and t o be from I n t e r s e c t i o n [ i ] if i is not equal t o e n t r , which is what w e
intend.
A s an ahernative. can combine the dcclarations o f the three dilTerent kinds o f
nodes into one. Observing that n e t _ o u t is positive or z e r o for E n t r _ I n t , negative or
zero for E x i t . I n t , and zero f o r a l l other mxles I n t e r s e c t i o n [ i ] , can declare:
node I n L c r s o c L i o n (k i n INTER} :
( i í k = e x i t then - I n í i n i t y J
< = n e L _ o u t <= ( i í k = e n t r Lhcn IníiniLy) :
a r e T r a f £ _ I n >= 0. t o I n L c r s o c t i o n l e n t r j :
are Tra££_0ut > = 0. írom I n t e r s e c t i o n [ c x i t ] :
data:
set IWTBR : = a b c d c £ g ;
param c n L r := a ;
param c x i t := g ;
ROADS: cap : =
a b 50. a c 100
b d 40. b e 20
c d 60. c £ 20
d c SO. d £ 60
c g 70. £ 9 70 ;
T h e t w o ares " h a n g i n g " ai the entrance and e x i t are defined in the o b v i o u s w a y , but
inelude only a t o o r a f r o m phrase:
a r e T r a £ £ _ l n >= 0 . t o I n t c r s e c L i o n [ c n L r 1 :
a r e T r a £ £ _ 0 u t > = 0. i r e m i n L c r s e c L i o n [ c x i L 1:
T h e ares that represem roads within the network are dcclarcd a* before:
node declarations
where an ariíh-t.xpr may be any arithmetic expression that uses previously dcclarcd
nnxlel oomponenfe and cunrently defined dummy Índices. A nts-txpr is restricied t o one
o f t h e following:
± not_in ± not_out
± n o t _ i n • ariih'txpr ± n o t _ o u t «• ariih-txpr
ariih-txpr ± not_in ariih-txpr ± not_out
(and a unary • may be omitied). Each node defined in this way induces a constraint in
the resulting linear program. A node name t% treated like a constraint name in the A M P I .
command environment f o r e x a m p l e in a d i s p l a y statement.
For declarations that use n e t _ i n . A M P I . generates the constraint by substituting, at
the p b c e where n e t _ i n appears in the balance condi tions, a linear expression that repre-
sents flow into the node minus flow out o f t h e node. LXx-laratk>ns that use n e t _ o u t are
handlcd the same w a y . except that A M P I . substhutes flow out minus f l o w in. T h e expres-
sions for flow in and flow out are deduced from the a r e declarations.
are declarations
and < = phraies are used to specify values for lower and upper bounds on the f l o w along
the are.
The irem and to phraies specify the nodes conncctcd by an are. Usually these con-
sist o f the key wordfrom or to followed by a node nanie. An are ii interpreted to con-
tribute ti> the flow out of the f r o m node, and to the flow into the t o node; these interpre-
tations are what permit the inference o f t h e constraints assoeiated with the nodes.
Typically one I r e m and one t o phraie are specified in an a r e declaration. Either
may be omhtcd, however, ai in F y u r e 15-12. Either may a b o be followttl by an optional
indexing expression, which should be one o f two kinds:
• An indexing expressk>n that speeifies — depending on the data — an empty set (in
which caie the f r o m or t o phraie is ignored) or a set with one member (in which
case the f r o m or t o phrase ii used).
• An indexing expression of the special form ( i £ logical-expr), which causes the
f r o m or t o phrase to be used if and only if the logical-expr evahiates to true.
It is possible to specify that an are carries flow out o f or into two or more nodes, by giv-
ing more than one f r o m or t o phraie, or by using an indexing expression that speeifies a
set having more than one member. The result is not a network linear program, however.
and AMPI. displays an appropriate warning message.
A t the end of a f r o m or t o phraie, you may add an arithmetic expression represent-
ing a factor to multiply the f l o w , ai shown in our examples o f shipping-k>ss and change-
of-unit variations in Section I 5 J . I f the factor t> in the t o phrase, it muhiplies the are
variable in determining the flow into the specified node: that is» for a given flow along the
are, an amount equal to the t o - f a c t o r times the flow is considcrcd to enter the t o node.
A factor in the f r o m phrase is interpreted analogously. The default factor is 1.
A n optional o b j phrase speeifies a coefllcient that will multiply the are variable to
creatc a linear term in a specified objeetive funetion. Such a phraie consisti of the key-
word o b j , the name of an objeetive that hai previously been defined in a m i n i m i z e or
m a x i m i z e dcclaratk>n, and an arithmetic expressk>n for the coefllcient value. The key-
word may be followxrd by an indexing expression, which is interpreted ai for the f r o m
and t o phraies.
I f ali terms in the objeetive funetion are specified through o b j phraies in a r e dccla-
rations. the declaration o f t h e objeetive issimply m i n i m i z e or m a x i m i z e follow&d by
an optional indexing expression and a name. This dcclaratk>n must come before the a r e
declaratkxns that referto the objeetive.
Ahernatively, are names may be used ai variables to specify the objeetive funetion in
the usual algebraic way. In this case the objeetive must be dcclarcd after the ares, ai in
Fjgure 15-12.
342 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
s e t CiTiiiS:
ML LINKS w i t h i i l <C1T1IÍS c r o s s C1T1KSJ:
ML FRODS:
param s u p p l y ( C 1 T 1 I Í S . PROOS} >=0; 4 amounLs a v a i l a b l e aL c i L i e s
p a r a m demand ( C 1 T 1 I Í S . PROOS} >=0; 4 amounLs r e q u i r e d aL c i L i e s
c h o c k ( p i n FRODS}:
sum ( i i n C 1 T 1 K S } supplyli.pl = sum (j i n C1T1KS} dcmandlj.pl:
p a r a m c o s L ( L I N K S . P R Q D S } >= 0 ; i shipmcnt cosLs/1000 packages
p a r a m c a p a c i L y ( L I N K S . F R 0 D S } >= 0: i max p a c k a g e s s h i p p o d
p a r a m c a p j o i n L { L I N K S } >= 0: i nvax L o L a l p a c k a g e s s h i p p c d / l i n k
minimize ToLal_CosL;
n o d e B a l a n c e ( k i n C1T1KS. p i n FR0DS}:
neL_in = demandlk.pl - s u p p l y l k . p l ;
are S h i p ( < i . j ) i n L I N K S , p i n FRODS} > = 0 . <= c a p a c i L y l i . j . p l .
i r e m B a l a n c e l i . p 1 . Lo B a l a n c e l j . p l . o b j T o L a l _ C o s L cosLli.j.pl;
s u b j o c L t o Mui L i ( ( i . j ) i n L I N K S } :
sum ( p i n FRODS} S h i p l i . j . p l <= c a p _ j o i n L l i . jJ :
s u b j e c L Lo M u l L i ( < i . j ) i n L I N K S } :
sum ( p i n FRODS} S h i p l p . i . j l <= c a p _ j o i n L l i . j J :
T h e final mixlel, shown in Figure 15-13, is not a network linear program, but the network
and non-network paris o f it are cleanty separated.
declaratk>n may contain references *> variables lhat w e i e defined by prcccding v a r dec-
larations. These refercncei define " s i d e variables*' t o the network linear p r o g r a m
A s an example, w e again replicate the formulation o f Figure I 5 - I 0 over the set
PRODS. This time w e tie the net works together by introducing a set o f feedstocks and
a i s o c b t e d data:
s e t FlíBDS;
param y i c l d (PRODS,KBBDS} > = 0 :
param l i m i t ( 1 ' B B D S . C l T l B S } >= 0 ;
T h e ha lance condhion f o r product p a t chy k can n o w say that the net flow out equals net
supply plus the sum o f the amounts derived from the various feedstocks:
n o d e B a l a n c e ( p i n PRODS. k i n C 1 T 1 B S } :
n e t _ o u t = s u p p l y [ p . k j - dcmand l p . k \
+ sum ( í i n KBKDS} y i e l d l p . i l * Feedlf.kl;
T h e ares are unchanged, leaJing k> the mixlel shown in Figure 15-14. A t a given city k,
the variables F e e d [ £ , k ] appear in the node babnevr conditions for ali the different
produets. br ing ing together the product nctworks in*> a single linear program.
set ClTlIiS:
set LINKS w i t h i n <C1T1IÍS c r o s s C1T1KSJ:
ML PRODS:
param s u p p l y (PRODS . C 1 T 1 K S } >=0; 4 amounts a v a i l a b l e at cities
bounds are integers. a network linear program must have an optimal solution in which ali
flows are integers. M o r e o v e r , if the solver is o f a kind that flnds " e x t r e m e " sohitions
(such as those based on the simplex method) h will always find one o f the all-integer
optimal solutions. W e have taken advantage o f thi> propeny. without explicitly mention-
ing it. in avsuming that the variables in the shortest path problem and in cenain assign-
ment problems c o m e out t o be either z e r o o r one, and never s o m e fraction in bctween.
Network linear programs can also be solvcd much faster than other linear programs o f
comparable size. through the use o f solvers that are specialized t o take advantage o f the
network structure. If you wrile your nnxlel in terms o f n e d e and a r e declarations,
A M P L automatically oommunkatcs the network structure to the solver, and any speeial
network algorithms available in the solver can be applied automatically. On the other
hand. a network expressed algebraically using v a r and s u b j e c t t o may or m a y not be
recognized by the solver. and cenain optk>ns may have t o be set t o e n s u i e that it is r e c o g -
nized. For example, when using the algebraic nnxlel o f Figure 15-la. you may see the
usual response from the general L P algorithm:
But w h e n using the eqüivalem node and are f o r m u h t i o n o f Figure I 5 - I I , you may g e t a
somcwhat d i f l e i e n t response t o refkrct the application o f a special network L P algorithm:
T o determine h o w your favorite solver behaves in this situation. consuh the solver-
specific documcntation that issupplicd whh your A M P l . instalhtion.
Bccause network linear programs are much eaiier t o solve, espeeiaily w h h integer
data. the success o f a large-scale application may depend on whether a pure network for-
mulation is pussible. In the caie o f the multicommodity f l o w nuxlel o f Figure 13-13, f o r
example, the j o i n t capacity constraints disrupt the network structure — they represent a
third constraint in w h i c h each variable f i g u r e s — but their presence can not be avoidcd in
a correct representation o f the problem. Multicommodity fk>w problems thus d o not nee-
cssarily have integer sohitions, and are generally much harder to s o l v e than single-
c o m m o d i t y flow problems o f comparable size.
In s o m e caies, a judicious reformulation can turn what appears t o be a more general
nuxlel into a pure network nuxlel. Considcr, f o r instance, a gene ra li/at ion o f Figure
15-10 in which capachies are d e f i n e d at the nodes as w d l asak>ng the ares:
param c i t y _ c a p ( C l T I K S } >= 0:
param l i n k _ c a p ( L I N K S } >= 0 :
T h e are capacitics represem, as before. upper limhs on the shipments between cities. T h e
node capacities limh the thxoughput or total flow handled at a city, which may be written
av the supply at the city plus the sum o f the flows in, or equivalently ai the demand at the
city plus the sum o f the f l o w s out. Using the former, w e arrive at the f o l l o w i n g c o n -
straint:
s u b j e c t t o t h r o u g h _ l i m i t (k i n C I T I E S } :
supply l kj sum ( < i . k j i n L I N K S } S b i p l i . k l <= node_cap [kj ;
V i e w e d in this way, the thxoughput limit is another example o f a 4 'side constraint" that
disrupts the network structure by adding a third c o e f f i c i e n t for each variable. But we can
achicvc the same e f l e c t without a side constraint by using t w o nodes t o represent each
city: one receives flow into a c h y plus any supply, and the other sends f l o w out o f a city
plus any demand:
A shipment link between cities i and j is represented by an are that connccts the node
Demand [ i ) to node S u p p l y I j ) :
346 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15
set CiTiiiS:
ML LINKS w i L h i n (ClTlIiS cross C1T1KSJ:
minimize ToLal_CosL;
node Supply (k in ClTlIiS}: neL_ouL = s u p p l y [ k l :
node Demarxi (k in ClTlIiS}: neL_in = dcmarxi(kj;
are Ship ( < i . j ) i n L I N K S } > = 0. <= l i n k _ c a p l i . j ] .
irem Dcmarxili], Lo S u p p l y l j l » o b j T o L a l _ C o s L cost(i.jl:
Bibliography
Rjvirxlra K . Ahuja. Tlximas L. Magiunti and Janics B. Orhn. A'i-lwoii Flows: Theary, Al flori ih ms,
and Appíicabons Prentice HaD (linglcwaad Cliflx. NJL 1993).
Dinúri P. Hcrtsekos AVÍHWA Opiioiizaiinn: Continuou* <in<i Discrrkr Afodrlx. Athena Scientific
(Princekin. NI. 1998).
1- R. Ixrd, Jr. JLIKI D. R. luHeiNon. Fh ws in AVJHYJvkx Princcton Uni\rrsity P ( P r i n c r t a n . NJ,
1962). A highly influential sunry o f ndwotfc fincar programo» ng and relited tapics. which stimu
iJcd much subsequcntstudy.
F f t d Cik)\vr. Darwin Khneman aixJ hhncy V . Phillips AV/mymâ M/)drls in Opúmiyiíon and ifitb-
Applications in Pmcicr. John W ü e y &. Sons (New York. 1992).
Wtller Jbcolh, " T h e CXcrer Problem." Naval Research Logistics Quirterly 1 (1954) pp.
151-165. T h : criginafthe ne« workproblem described in lixcicwc 15 8.
Katti G. Murtv. AVMyhA Frogmmmin^ Prentice HaD (Englewood ClifTx, NJ. 1992).
Excrcises
15-1. The falkiwing dügram can be interprcted xs representinga network transshipment problem:
The ÍITIiws inki rodes A and H represei* supply in f h : indicaled amaunts. 1 (Kl and 50; the arrows
out af nodes I: and I" similarlv represem demand «n the amounls30 oixl 120. T h : nrmainíng arrows
inJicaà: shipnienl possibilites. oi»J the numbers an them aretficunit shippirçg costs. There is a
cajucitY af 80an e\rry are.
(a) Solve this problem by dcvekipírçg apprapriale dita st&tcmcnts <a go alang with th: model o f
Figure 15-2a.
<b) Check thit yau gci the some solution using the nade anJ are fcrmuLukin af Figure 15 10. Daes
the solver appear t o be using the « m e algcnéini as in (a)? Try this campirixan with each I.P
salsvr available to yau.
15-2. Rdnlerpret the numbers <*i the ares ftrtHWfl nades, «n the diagram af the precedmg exer
cise. lei salve the foüawing problems. (Ignoie the numbers an the arrows mfct A and H ai»J an the
arraws aut af E and F.)
(a) Recordinc éie numbers an the ares hetuvvn nctdes as l e i ç i i x . use a model such as tfie ane «n
Figure 15 -7 ki fmd the shciHest path from A ki F.
348 PCTVOFKLNEAFRFOGRAVS CHÍFTER 15
<b) R c c j j d i n c lhe numbers c*i lhe ares b d w x n nades AS cajucilics. use a model such as lhe one «n
Figure 15-6 fct find lhe maumum ftow from A 1o F .
( c ) Generalize lhe model iram <b) so Ihil it can finJ lhe m u i n u m f b w from any sub sei o f nades
l o any odier sufoel of nades, in some meaningful sen se. Use your generab/alian Io finJ lhe ma\i
mum f b w from A jmd II Io K aid F.
1 5 - 3 . Scclkin 4.2 showed how a multiperiod model could be canslriKled by replicaling a slalic
model o\er lime periodt, jmd usirçg in\enkiries lei tie lhe periods lagrthcr. Coiwider applvirçg lhe
sane apprcuch (Olhe speciili/ed transe hipmenl xnadel o f Figure 15 4a.
( a ) Comlrucl a muki w e e k v c t x i o n o f Figure 15 4a, with lhe inventeries kepl al lhe dwtributian
centers (lhe members o f D _ C X T Y ) .
<b) N o w consider ekjundirç; lhe dati o f Figure 15 4b for Ihrs mcdel. Suppose thil lhe mitül
inventory k 200 al Mli ai»J 75 al Slí.and lhal lhe «i\enlory canyiqg cosi per 1000 packages k 0.15
per week al NH ard 0.12 per week al SE. Ix*l lhe suppÜes and demaixJs o\er 5 weeks be as foi*
lows:
Demand
Week Supply BÍK KWR BWI ATL MCO
1 450 50 90 95 50 20
2 450 65 100 105 50 20
3 400 10 100 110 50 25
4 250 10 110 120 50 40
5 325 a» 115 120 55 45
L e a v e lhe CXK! and capacily dati uncharçged. lhe %me in ali weeks. D e v e b p an appropriile dxla
file for Ihissitiulkin. and sol\e lhe multi-weci. problem.
( c ) T h : mulb week model inlhis case can be viewed as a purê network model. wüh ares represent •
irçg inventeries as w l l as shipments. To show lhal úm is lhe case. refcrmuUle the mcdel frcm ( a )
usirçg only n o d e ard a r e dcclaralians fer the constrainfe ard v m b b .
15-5. Reformula*? each of lhe folkiwirç; netwcrk models using m á o ard a r e dcclaralians as
mu di as potsible:
( a ) The transp<rtalian mcdel of F i g w e ó 2a.
<b) The shortestpalh model of Figme 15 7.
( c ) T h : productionAramportalion model o f F j g u e A 6 .
( d ) The mukiconimcdit v Iranepcirtukin model o f Figure 6-5.
1 5 - 6 . The professor «n charge of an mdustriil eiyincxrhng design cciurse n faced with the prob
lem o f aseignirçg 28 sludenls lo eight project*. I:ach sludent must be assigned Io one project, ard
each project group imisl have 3 cr 4 siudents. The stuJenls h i v e been asked l o rank the project*.
wiéi 1 being lhe bestrankirçg and higher numbers representong kiwer rankings.
SECT CN 15.5 Sa.VIS»3NETY/CR<LNE/«FTOGRftWS 349
(c> Some o f lhe projectx an: hirder lhan oéiers to m e t i withoul a cor. Thus it is dcsiroble OIJU at
IOLSI a ceitiin number of studenfe assigned to each project must hasv a cor: flie numbers vary by
psojcct as folkiws:
A 1 ED 0 EZ 0 G 2 III 2 112 2 RH 1 SC 1
M o d i f y the model to add this cor constraint oikJ solve the pfftíblem again. I l o w many ntere stu
denfc thin befare must be assigned second cr third choice?
1 5 * 7 . To maiuge its excess cash over the next 12 months. a c o m j u n y may purchase 1 month.
2 month <r 3 numth certificai es o f deposit f r o m any of xcvcval difíerent hinks. The current cash
on hind and amounts invested are known. while the comjuny mutt estimote the cash receipts aixl
expenditures for each month. and the retumson the different ccvtifi cates.
The company's problem is to determine the best mwstment strategy, subject to cash xequnemcnts.
(As a practical nutter. the comjuny would m e the first month of the optimal solutkin as a guide to
its current purchises. aixl then re solve with ujxlated es ti nules at the bcginning o f t h e next month.)
( a ) Draw a network dugram for Ihrs si tu aliem. Show each month as a nade, aixl the n v H l n e n t c ,
receipts and expenditures as ares.
c^
V M Jl fl CE a ts r i r i r i JI JI RI
•5 rH r« •X a: a ro <x ri «x r- r- ri
O O O O H H H r i r i RI r i M
£ a a a a a a a a a a a a
E O A A A A A A A A A D A
r- fl ri
Q] Cl JI r••i f l r* r* f l Cl
IP
~ • oi ri CE , i ,i FO JL
O O a Cl V •» rH H ri ri ri ri
r1 H H ri ,i , 1, i ,i ri ri
,I
Q O o O ,O1 O o O o o Q O
d d Cl Cl a Cl a a a a d a
Ml
s M CE eÍ JI
A S FL M a s JL p a a CE R-
ri n « « ri « « V v v M y
ri ri ri ri ri ri ri ri n
Q Cl Cl O Cl Cl O O Cl Cl Q Q
£
d a a a a a a a a a d a
£
ML ri M JL <x r- CE o» Cl c-i r i
s H rH r-i
s CE Cl FL A: Cl A: FL r* r* Cl O *
AS O , 1 fO JJ CE , 1 cs FI JJ JI
fi r l ri
s g g g g g ri ri ÍI Í1 Í 1 Í 1
ci a O a o a o o o o o a
L
5 d a a a Cl a Cl Cl a Cl d a
£ r- FL r i
Q] Cl JI r••i FL r* r* r» r»
ip m ri CE , i , i r l rH
u» V • »
a a a a H H ri H r« ri r i r i
g g g•í gtc grí gJlgMgtcgX sss r H
a
H
a
H ri
a a
H
a
H ri
a A
H H
a a ri rH rH
a a a
ci a A a A A A A A A ci a
ÍP m r- r i •X A CE R* r* a a RI FI
fOfi JJ JJ CE r i ri (7* CE
" V ^ ** IX Jl Jl
,, a a a o a o o o o a a a ri ri ri ri ri ri ri ri ri n
ri n Cl Cl
Iá 3SSSSSSRSS sss Q O
d a A A
O Cl Cl Cl O
A A A A A
Cl
A
Q a
d Cl
I £
** JI «x CE cr» a r i ri rH n M JI •X CE tr>A rH ri
*1
O c
(S 2
£
Jl
-a
ML
5
8
a
3
--
£ s i.
e
•5
ç
a s
•5 d
S
i* li'*
% .2 C 5
I c
' 1É -
II lllilJ
se
O T3
SECT C N 15.5 S C L V NQ NETY/CFK L N E W F T O G R A V S 351
Thcrc an? twacollectians af camtraints <m ( h n e variables. which can be described as follaws:
- T h : nuniK-r af clean rupkim acqumrd through purchase. c i n y o w r and iiuraJcrxnc <«i d i v t
must equal #ie number scnl *> Uurxknnc. discorded <r carried o v e r after d i y t .
- T h : number o f used napkins Liurcleiedor dncarded after day L must eqtul lhe number thit w e t ü
required f o r thtf day's caftering.
l o r m u l J e a n A M R linear programming model f<* this problem.
<b) IxrmuUte JLII alternjitiw netwcrk linear programmirçg madcl far this problem. Write it «n
A M H . using nade and are declaratians.
< c ) T h e "catem p r a b l e m " wasintraduced in a 1954 piper by W a k e r Jjcabs af th? U-S. A i r Torce.
Althaugh it has been presented in countlewc books a n linear and network programmiqg, it does nat
seeni ki have e v e r been used h>- any cMcrcr. In w h i l applicotkin da you suppose it readly <rigi
naed?
(d> Since this is an artificiil prablem, you might as well make up your a w n dati far it. Use yaur
d J a t o check <h.U é i e fcmiuUtkim in ( a ) anJ <b> gise the same optimal value.
Copyright O 2003 by R<*>crt Fourcx, DavidM. Oay and Brian W . Kernighin
16
Columnwise Formulations
353
354 OCLUWW/SE FOFMJLAT-OMS C H Í F T E R 16
a wori-shift schcduling nuxlel — and concludes with a summary o f the languagc exten-
sionsthat may be used incohimnwisc formulations.
Formulation by constraints
Thcdcfinition o f our nuxlel starts whh a set o f materiais and a set o f activities:
M L MAX;
M L ACT;
The key data values are the input-output coefficients for ali material-activity combina-
tions:
param i o (MAT.ACT};
param a c L _ m i n ( A C T } >= 0:
param a c L _ m a x ( j i n >V!T> >= a c t _ m i n [ j 1:
s o t MAT: 4 materiais
s e t ACT: i» a c t i v i t i e s
param i o (MAT. A C T } ; 4 input-output coeííicients
param r e v e n u e (ACT} ;
param a c t _ m i n (ACT} >= 0 :
p a r a m a c t . max ( j i n A C T } > = a c t _ m i n ( j J;
s u b j e c t t o B a l a n c e ( i i n MAT} í
sum ( j i n A C T } i o l i . j l * Run(j| = 0;
represents the amount o f material i pnxluccd in the operation mi nus the amount con-
sumai. These amounts must baiano?, as expressed by the following constraint:
s u b j e c t t o B a l a n c e ( i i n MAT}:
sum ( j i n ACT} i o l i . j l * Runljl = 0:
\Vhat about the availability o f resourees, or the requirements for f i n & i c d gcxxls? These
are readily nnxlclcd through additional aetivities that represent the purchase or sale o f
materiais. A purchase activity for material i has no inputs and just i as an output: the
upper limit on Run I i ] represent* the amount o f this resource available. Similar ly. asale
activity for material i has no outputs and just i as an input, and the lower limit on
Run [ i 1 represents the amount o f this gtxxl that must be produced for sale.
W e complete the model by associating unh revenues with the activitics. Sale activi-
tics necessarily have positive revenues, while purchase and produetion aetivities have
negative revenues — that is, costs. The sum o f unit revenues times activity leveis gives
the total net profit o f the operation:
param r e v e n u e (ACT}:
A columnwise formulation
A s our discussion o f puicha&e and sale aetivities suggests, everything in this nnxlel
can be organi/ed by activity. Speeifically, for each activity j have a dccision variable
R u n l j l , a cost or income represented by r e v e n u e l j ] , limhs â c t _ m i n [ j ] and
àct_rrwax l j 1, and a collection o f input-output ooefficients i o [ i . j 1. Changes such as
improving the yield o f a unh, or aajuiring a n e w source o f supply, are accommodatcd by
adding an activity or by nnxlifying the data for an activity.
356 O C L U W W / S E FOFMJLAT-OMS C H Í F T E R 16
In the formulation by rows. the activities' importa nce to this model ii somewhat hid-
den. While a c t _ m i n [ j ) and a c t _ r n a x [ j ] appear in the dee)aratk>n o f the variables,
r e v e n u e [ j ] is in the objective, and the i o [ i . j ] values are in the constraint deebra-
tion. The columnwise alternative brings ali o f this informaiion together, by adding o b j
and c o e £ £ phraies to the v a r declaration:
The o b j phrase says that in the objective funetion named K e t _ P r o £ i t , the variable
Run [ j ] has the coefficient r e v e n u e [ j ) ; that is. the term r e v e n u e t j ] * Run [ j ]
should be added in. The c o e f f phrase is a bit more complicated. because h is indexed
over a set. It says that for each material i . in the constraint B a l a n c e t i J the variable
R u n [ j ] should have the coefíicient i o [ i . j ] , s o that the term i o [ i . j ] * R u n t j ] is
added in. Together, these phraies describe ali the coelTicients o f ali the variables in the
linear program.
Since wxr have placed ali the coelTicients in the v a r dcclaratk>n, \v>í must remove
them from the other declaratk>ns:
maximize N e L _ P r o f i t :
n u b j e c L Lo B a l a n c e ( i i n MAT}: Lo ccme = 0:
s e L MAT: * maLeriais
seL ACT: * ac Li v i L i e s
param i o (MAT. ACT } : 4 inpuL-ouLpuL coeff icienLs
param r e v e n u e (ACT}:
param a c L _ m i n ( A C T } >= 0:
param a c L _ m a x ( j i n ACT} >= acL_min(jl:
maximize NeL_Profit:
subjecL Lo B a l a n c e (i i n MAT}: Lo ccme = 0:
v a r Run ( j i n A C T } > = a c L _ m i n l j l . <= acL m a x l j l .
o b j MeL_ProfiL revenue ( j l .
c o e f f ( i i n MAT} B a l a n c e U l io(i.jl:
p a r a m s e l l .min ( M A T F } >= 0:
p a r a m s c l l . max ( i i n M A T F } >= s e l l _ m i n ( i 1 :
W e may n o w dispense with the special sale activities prevk>usly described. Since the
remaining members o f A C T represem purchase or produetion activities, w e can introduce
a nonnegative parameter c o s t aisociatcd with them:
maximize N e t _ P r o £ i t :
sum ( i i n M A T F } r e v e n u e l i l * S o l l l i J
- sum ( j i n A C T } c o s t l j l * Run(jl;
t o represem total sales revenue minus total raw material and production costs.
S o far \v\? se e m to have improved upon the model in Figure 16-1. T h e c o m p o s h i o n o f
net profit is more clearly modclcd. and sales are restricted t o explicitly designated fin-
ished materiais: a b o the optimal amounts sold are more easily examined apart from the
other variables, by a c\>mmand such ai d i s p l a y S e l l . It remains t o f i x up the c o n -
straints. W e woukl like t o say that the net output o f material 1 from ali activities. repre-
sentedas
in Figure 16-1, must balance the amount sokl — either S e l l ( i ) if i ts a finished mate-
r i a l or zero. Thus the constraint declaration must be written:
s u b j e c t t o B a l a n c e ( i i n MAT}:
sum ( j i n A C T } i o ( i . j l * Run(j|
= i í i i n MATF t h e n S e l l l i J e l s e 0;
Unfonunately this constraint seems less clear than our original one. due t o the complica-
tion inuoduced by the i £ - t h e n - e l s e expressk>n.
In the columnwise alternative. the objective and constraints are the same ai in Figure
16-2, while ali the changcs are reflectod in the declarations o f the variables:
358 OCLUWW/SE FOFMJLAT-OMS C H í f T E R 16
s e t MAT; 4 materiais
s e t ACT; 4 activities
param c o s t ( A C T } >= 0 ;
param a c t _ m i n ( A C T } >= 0 ;
param a c t _ m a x ( j i n >Y!T} >= act_min(j):
maximize Net_Pro£it;
In this view, the variable S e l l ( i ) represents the kind o f sale activity that w e previously
dcscribcd. with only material 1 ai input and no materiais ai output — hcncc the singlc
coelYicicnt o f - l in constraint B â l â n c e ( i ) . W e need not specify ali the z e r o c o e f f i -
cicnti for S e l l [ i J; a zero is assumed for any constraint not explichly ciied in a c o e £ £
phrase in the dcclaration. The whole nuxlel fc shown in Figure 16-3.
Th& example suggests that a columnwise approach iü panicularly suited to refine-
ments o f the input-output nuxlel that dtvtinguishditTerent kinds o f activities. It would be
easy to add another group o f variables that represent purchases o f raw materiais, for
instance.
O n the other hand. versions o f the input-output ntxlcl that involve numerous speeial-
i/edconstraints would lend themselves more t o a formulation by rows.
SECT C N 1 6 2 A S C H E C d t P*3 W O C G . 359
s o t SHIFTS: * shifts
param N s c h o d ; 4 number o f s c h e d u l e s :
s e t SCHKDS = 1. . N s c h « â : 4 s e t of schedules
For each schedule j in the set SCHEDS. the shifts that a person works on schedule j are
cx>ntained in the set S H I F T _ L I S T [ j J. W e also speeify a pay rate per person on each
schedule. and the number o f people required on each shift:
W e let the variable W o r k ( j ] represent the number o f people assigned to work each
schedule j . and minimize the sum o f r a t e [ j ] * W o r k [ j J over ali schedules:
Finally, our constraints say that the total o f employees assigned to each shift i must be at
least the number requircd:
s u b j e c t t o S h i f t íJeeds ( i i n S1J1FTS}:
sum ( j i n 9C11KDS: i i n SH1FT_L1STI j 1 } Workljl
>= r o q u i r e d l i l :
On the left wxr take the sum o f W o r k l j l over ali schedules j such that i is in
S H I F T _ L I S T [ j 1. This sum represents the total employees who are assigned to sched-
ules that conta in shift i , and hence equals the total employees cove ri ng shift i .
T h e awkward description o f the constraint in this formulation motivates us to try a
columnwise formulation. As in our previous examples. declare the objective and con-
straints first but with the variables left out:
minimize Total_Cost:
s u b j e c t t o S h i f t íJeeds (i i n SHIFTS}: to_ccme >= r«quir«â[i|;
360 OCLUWW/se FOFMJLAT-OMS c h í f t e r 16
a m p l : diaplay Work;
Vtork 1*1 : =
10 2 8 . 8 30 1 4 . 4 71 3 S . 6 106 2 3 . 2 123 3S.6
18 7.6 3S 6.8 73 2 8 109 1 4 . 4
24 6.8 66 3 S . 6 87 1 4 . 4 113 1 4 . 4
As you can see, this optimal solution makes use o f 13 o f the schedulcs. some in fractional
amounts. (There exist many other optimal solutions k> thts problem, so the resulfc you
get may differ.) l f you round each fraction in this solutk>n up to the next highest value,
you get a preuy gtxxl feasible solution using 271 employees. T o determine whether this
is the best whole-number solution, howxrver, it is necessary to use integer programming
techniques, which are the subject o f Chapicr 20.
T h e convenience o f t h e c o l u m n w a e formulaiion in this c a i e foi lows directly from
how w e have chosen k> represent the daia. W e imagine that the nnxle ler will be thinking
in t e r m s o f schedulcs. and will want *> try adding. dropping or mixlifying dilTerent sched-
ulcs to see what solutions can be obtained. The subsets S H I F T _ L I S T [ j 1 provkle a
convenient and concise way o f maintaining the schedulcs in the data. vSince the data are
then organi/cd by schedulcs. and there i s a b o a variable for each schcdulc. it proves to be
S E C T - G N 16.2 A QCHEÜUL NG UOC&. 361
s e t SHIFTS; A shiits
param N s c h o d ; * number o £ s c h e d u l e s ;
s e t SCHKDS = 1. . N s c h o d : .COL o í s c h e d u l e s
s e t S1JIFT_LIST (SCHIÍDS} w i t h i n SHIFTS:
param r a t e (SCiJEDS} >= 0:
param r e q u i r o d { S H I F T S } > = 0:
minimize Total_Cost:
s u b j e c t t o S h i f t íJeeds (i i n SHIFTS}: to_ccme >= r o q u i r e d [ i j :
(SJ76ntx omíkrd)
param r a t e default 1 ;
simpler — and for larger examples. more effieient — to specify the coelTicients by vari-
able.
M o d e l s o f this kind are used for a variety o f seheduling problems. A s a eonvenience.
the keyword c o v e r may be used < in the manner o f í r o n and t o for nctworks) to spec-
ify acoefficient o f I:
362 OCLUWW/se FOFMJLAT-OMS chífter 16
Some o f the best known and largest examples are in airline crew scheduling, where the
variable* may represem the s&signment o f crews rather than individual*, the shifts
beeome fljghts. and the requirement is one crew for each flighl. We then have what is
known av a set covering problem. in which the objeetive is to most economically cover
the set of ali flights with subsets representing crew schedules.
t o . come
Lo. come «- wilh expr
arilh-expr «• Lo come
set C1T1KS:
ML LiWXS w i t h i n (ClTlIíS cross C1T1KSJ:
ML FRODS:
param s u p p l y ( C l T l I í S , FW3DS} >=0: 4 amounLs a v a i l a b l c aL c i L i e s
p a r a m demand ( C l T l I í S , FW3DS} >=0: 4 amounLs r e q u i r o d aL c i L i e s
checrk ( p i n F R O D S } :
sum ( i i n C 1 T 1 K S } supplyli.pl = sum (j i n C1T1KS} dcmandlj.pl:
minimize ToLal_CosL;
n o d e B a l a n c e ( k i n C1T1KS. p i n FRODS}:
neL_in = demandlk.pl - s u p p l y l k . p l ;
s u b j o c L t o Mui L i ( ( i . j ) i n L I N K S } :
L o c c m e < = c a p _ j o i n t ( i . j 1;
Bibliography
(icrald KjJun. "W.*lljrçg Throush A Cohinuur Apprcuch tc» lincoi Prc»grxnuiuns of A Hmine**."
Interfaces 12. 3 (1982) pp. 32-39. A bricf f<* th: columnwise approach ki h r v j j prasr.imming,
with A small example.
364 OCLUWW/se FOFMJLAT-OMS chífter 16
Excrcises
1 6 - 1 . (a) C o n s t r u i a columnwise formulaticm o f the diet model o f Figure 2 1.
<b) Construct a columnwise fcrmuUtkin af the diet xnadel af Figure 5-1. Sina? there are t w o « p a -
ra*? colkctioiK o f constraints in this diet model. w u w i l l necd t w o c o e i £ phrases inth? v a r dec-
laration.
16-2. IixpanJ the columnwiseprodu^kin xnodel of 1'igure 16-3 t o inc<rp<ratc varables Buy [ i |
thit represent purchases af raw nuteriils.
1 6 - 3 . Formulite a mukipcriod versiem o f the model o f Figure 16-3, using é i e approadi xmrodiKvd
in Scclian -12: first rephcate é i e model over a set o f wrekx. then imrodure i n v e n k r y variables lo
tie # i e vxcks together. Use only columnwise decliratxixts f<r ali o f the v m b k s , inchidix^g thase
f<r in\mlory.
1 6 - 4 . The " r o l l t r i m " a r "culting s t a c k " problem his much in comntan with the schedulxiç;
pxtblem described m this chapter. Review the descriptian o f the roll trim problcm «n Hxercise 2-6,
xxxJ use it to answer the foDcrwing questiom.
( a ) Wh at is the reLukixiship betuvvn the available cutting jutterns in the roD trim prablcm, and the
coefficicnts a f the vambk-s inthe linear programmix^g fcrmuUtxtn?
<b) T o r m u l a t e an A M H . m o d e l f o r the r o l l trim p r o b l e m that uses o n l y c o l u m n w i s e decliratxixts o f
the v a r ú b l e s .
( c ) Saiu? the roD trim problem f<r the date given in lixcrcise 2-6. A s a test of your formulatum.
s h o w t h i t i t g i v e s tfie « n u ; optimal value as a r o w wisc formularem o f the model.
1 6 - 5 . The set cavering problem. xnentoncd at the end o f Section 16.2. can be stated m a general
way as foi k» ws. Y o u are given a set S. aixl certain subsets 7",. T2 f a o f £ a cost is avsociated
with each of the subsets. A selectian o f s a m e af the subsets T- is said t o covrr S ií every member
o f S is also a member of at least one of the selected subsets. For example. if
S - (1,2,3,4)
Piecewise-Linear Programs
S e v e r a ! k i n d s o f linear programming problems use functions thai are not really linear,
but are pieeed together from eonneeted linear segments:
These " p i e c e w i s e - l i n e a r " terms are ea*y t o imagine, but can be hard t o describe in c o n -
ventional algebraic notation. Hence A M P l . provides a special ooncise w a y o f wrhing
them.
This chapter introduces A M P L ' & piecewise-linear notation through examples of
piecewise-linear objective functions. In Scctk>n 17.1. terms o f potentially many picccs
are used t o describe costs more accurately than a single linear rcbtk>nship. Section 17.2
shows h o w terms o f t w o or three pieces can be valuable f o r such pur poses ai penal i/i ng
deviations from constraints. dea li ng with infeasibilities. and model ing " r e v e r s i b l e " activ-
ities. Finalty, Section 17.3 describes piecewise-linear functions that can be wrítten with
other A M P l . operators and functions: s o m e are most e f f e e t i v e l y handled by converting
them to the piecewise-linear notation. while others can be accommodated only through
more extensive transformations.
A h h o u g h the piecewise-linear examples in this chapter are ali easy t o solve, seem-
ingly similar examples can be much more dííTicult. T h e last section o f this chapter thus
olYers guidelincs for for mi ng and using piecewise-linear terms. W e expia in h o w the easy
cases can be characteri/ed by t h e c o n v e x i t y or concavity o f the piecewise-linear terms.
366
366 PECEV/SE L NEAR FTO3R6W5 C H í f T Ç R 17
rat_c31i. j ]
T r ans [ i , j )
limiLlli.j| limit2[i.jl
In a linear transponaiion nnxlel like Figure 3-Ia. any number of units can be shipped
from a given origin U» a given destination at the same cost per unit More rcaliiticalty,
howxrver, the most favorable rate may be available for only a limited number of units;
shipments beyond this limit pay higher rates. As an example, imagine that three cost raie
leveis are specified for each origin destinaiion pair. Then the total cost of shipments
along a link increases with the amount shipped in a piecewise-linear faüiion, with three
pieces as shown in Figure 17-1.
T o nnxlel the three-piece costs, repbce the parameter c o s t o f Figure 3-Ia by
three rates and twolimits:
minimize Total_Cost:
sum ( i i n ORIG. j i n DEST} c o s t l i . j | * Transli. j l ;
minimize Total_Cost:
sum ( i i n ORIG. j i n DEST} < r a t e l l i . j l * T r a n s l l i . j l
• r a t e 2 ( i . j ] * T r a n s 2 l i . j l • r a t e } l i . jl * Trans? I i . j | J :
But then the new variables w\>uld have to be introduced into ali the constraints. and wvr
would also have to deal with these variables whenever wxr wanted to display the optimal
resuhs. Rather than g o to ali this trouble, w e woukl much prefer to describe the
piecewise-linear cost funetion explicitly in ter ms o f the original variables. Since there is
no standard way to describe piecewise-linear funetions in algebraic notation. AMPL sup-
plies itsownsyntax for thts purpose.
T h e piecewfee-linear funetion dcpieted in Figure 17-1 iswrhten i n A M P L as follows:
« l i m i t l l i . j | . I i m i t 2 ( i . j J:
ratei li.j|. rate2li.j|. rate31i.j1>> Transii.j1
The expression between < < and > > describes the piecewise-linear funetion. and is f o l -
lowed by the name of the variable to which it applies. (You can think o f h as "multiply-
i n g " T r a n s t i . j J, but by a series o f c o e f f i c i e n t s rather than just one.) There are two
parts to the expression. a list o f breakpoinis where the slope of the funetion changes. and
a list o f the slopes — which in this case are the cost ratei. The lists are separated by a
semicolon. and members of each list are separated by oommas. Since the first sk>pe
applies to values before the first breakpoint. and the lavt slope to values after the last
breakpoint. the number of slopes must beone more than the number of breakpoinfc.
Ahhough the lists of brcakpoints and slopes are sulYicicnt to describe the piecewise-
linear cost funetion for optimi/ation. they do not quite speeify the funetion uniquely. I f
we added. say, 10 to the cost at every point we would have a dilTerent cost funetion even
though ali the brcakpoints and slopes w\>uld be the same. T o resolve this ambiguity.
368 PECEV/SE L NEAR F T O 3 R 6 W 5 C H í f T Ç R 17
minimizo Total_CosL:
sum ( i i n ORIG. j i n DEST}
< < l i m i L l ( i . j 1. l i m i L 2 l i . j l :
raLo11i.j1. raLo2li.j1. r a L o 3 ( 1 . j l » Trans(i.jl;
The dcclaratk>ns of the variables and constraint* stay the same as before: the complete
nnxlel is shown in Figure 17-2.
Theapproach taken in the preceding example ii most useful when there are only a f e w
linear pieves for each term. l f there were, for example. 12 p i c o s instcad of three, a
nnxlel defining r a t e i I i . j 1 through r a t e l 2 ( i . j 1 and l i m i t l ( i . j 1 through
l i m í t l l ( i . j ] would be unwieldy. Realistically, moreover, there would more likely
be up k> 12 piecei, rather than exactly 12. for each term: a icrm with fewer than 12 picces
could be handkd by making some rates e^ual but for large numbers of picces ihis would
SECT CN 17.2 CCWWCN T V O P ECE AND THREE PECE TE W S 389
be a cumbersome device thai would require many unnccessary data values and would
obscure the actual numberofpieces in each term.
A much better approach is to let the number o f pieces (that is. the number o f shipping
rates) itself be a parameter of the nnxlel, indexed over the links:
We can then index the rates and limits over ali combinaiions of links and pieces:
param r a L e ( i i n ORIG, j i n DESr. p i n 1 . . n p i e c e l i . j 1 }
>= i f p = 1 Lhen 0 c l s c r a L c l i . j . p - U ;
param l i m i t ( i i n ORlG. j i n DEST. p i n 1. . n p i e c e l i . j 1 - 1 }
> i f p = 1 Lhcn 0 e l . c c l i m i L { i . j . p - U ;
For any particular origin i and destination j , the number of linear pieces in the cost term
is given by n p i e c e [ i , j ] . The slopes are r a t e [ i , j , p ] for p ranging from I to
n p i e c e [ i . j J, and the intervening breakpoints are l i m i t [ i . j . p ] for p from 1 to
n p i e c e [ i , j J - 1 . A s before, there is one more slopethan there are breakpoints.
T o use AMPI/s piecewise-linear funetion notatk>n with these data values. w e have to
give indexed lists of breakpoints and slopes. rather than the explicit lists of the previous
example. This is done by pbeing indexing expressions in front of the slope and break-
point vahies:
minimize Total_Cost:
sum ( i i n ORIG. j i n DEST}
<<(p i n l . . n p i o c e [ i . j l - 1 } limit(i.j.pl;
( p i n l . . n p i o c e l i . j l } r a t e i i . j . p I > > T r a n s i i . j 1:
Once again. the rest of the nnxlel is the same. Figure l7-3a shows the whole nnxlel and
Figure l7-3b illustrates how the data would be specified. Notice that since
npiece[ •PITT'. 'STL*) is I. T r a n s [ " P I T T * , ' S T L ' ] has only one slope and
no breakpoints: this implies a one-piece linear term for T r a n s [ ' P I T T ' . • S T L * ] in
the objective funetion.
Linear programs most easily express " h a r d " constraints: that production must be at
least at a certain levei, for example. or that resources used must not exceed those avail-
able. Real shuations are often not nearly so definite. Prixluctk>n and resource use may
370 P E C E V / S E L NEAR FTO3R6W5 C H í f T Ç R 17
m i n i mi zc To t a l _ C o s t :
sum ( i i n O R I G . j i n D E S T }
« ( p i n 1. . r p i e c e l i . j | - l } l i m i t ( i . j . p l ;
( p i n 1. . r p i e c e l i . j l } r a t e ( i . j , p j » Transli.jl:
s u b j o c t t o Supply ( i in ORlG}:
sum ( j i n DEST} T r a n s l i . j l = supplylü;
s u b j o c t t o Demand ( j i n DE SI'} :
sum ( i i n O R I G } T r a n s l i . j l = d e m a n d ( j | ;
have certain preferred leveis, yet we may be allowed to vk>latc these leveis by acccpting
some extra costs or reduccd profits. The resulting " s o f t * ' constraints can be nuxlclcd by
adding piecewise-linear " p e n a l t y " terms to the objective function.
For an example. we return to the multi-wxxrk produetion nuxlel devcloped in Chapter
As seen in Figure 4-4, the constraints say that, in each o f weeks I through T , total
hours used to make ali prcxlucts may not exceed hours avaibble:
s u b j e c t t o Time ( t i n 1 . . T } :
sum ( p i n PROD} < l / r a t e l p | J * Hakelp. tl <= availltl:
Suppose that. in reaüty. a larger number o f hours may be used ineach week, but at some
penalty per hour to the total profit Specifically. w e replace the parameter a v a i l ( t ] by
tw\>availability leveis and an hourly penalty rate:
[PITT.FRA. *1 1 24 2 34 [ P I T T . DKT. *1 1 14 2 24
[PITT.LAN. *J 1 17 2 27 [ P I T T . W I N . *J 1 13 2 23
[PITT.STL. *1 1 28 [ P I T T . F R B . * J 1 99 2 140
[PITT.LAF. *1 1 20 •
param l i m i L :=
1 FRA 1 SOO FRA 2 1000 DKT 1 SOO DK1* 2 1000
LAN 1 soo LAN 2 1000 WIN 1 1000
STL 1 soo STL 2 1000 FRK 1 1000
LAF 1 soo LAF 2 1000
1 FRA 1 soo FRA 2 1000 DKT 1 soo DK1* 2 1000
LAN 1 soo LAN 2 1000 WIN 1 soo WIN 2 1000
STL 1 soo STL 2 1000 FRK 1 soo FRK 2 1000
LAF 1 soo LAF 2 1000
a v a i l _ m a x [ 1 1 . In place o f our previous constraint. \v>Í say that the total hours usod to
make ali products must equal U s e [ 1 1 :
s u b j o c L Lo T i m e ( t i n 1 . . T } :
sum ( p i n PROD} < l / r a L c l p | J * Makclp. t j = Uso[L|:
Uselt]
a v a i 1. min l t 1
maximize N e t _ P r o £ i t :
sum ( p i n PROD. t i n 1 . . T } < r e v e n u e l p . t 1 * S e l 1 l p . t 1 -
p r o r i c o s L l p l *>Sake l p . L j - i n v c o s t [pJ * I n v l p . t j J
- sum ( t i n 1. . T > < < a v a i l _ m i n l t 1; 0 . L i m e p e n a l L y l t l » U s e [ t J :
The first summation is the same expression for total profit ai before, while the second is
the sum o f the piecewise-linear penahy funetions o v e r ali wxreks. Between < < and > > are
the brcakpoint avail_snin(tJ and a list of the surrounding slopes, 0 and
t i m e _ p e n a l t y [ t ] ; this is followxrd by the argument U s e [ 1 1 .
T h e complete revised nnxlel t% shown in Figure l7-5a. and our small data set from
Chapter 1 is expanded whh the new availabilities and penahies in Figure l7-5b. In the
optimal solution, find that the hours used are as foDows:
In weeks I and 3 we use only the unpcnali/cd hours available. while in weeks 2 and 4 we
also use the penali/ed hours. *Solutions to piecewise-linear programs usually d&play this
sort o f solution, in which many (though not neeessarily ali) o f the variables " s t i c k " at
one o f the brcakpoints.
S E C T CN 17.2 C C W W C N T V O P E C E AND T H R E E P E C E TE W S 389
param c c c x n i L : 1 2 3 4 :=
bands 3S00 S900 3900 64 00
coils 2S00 2400 3400 4100 ;
374 PECEV/SE L NEAR FTO3R6W5 C H í f T Ç R 17
pa ram T : = 4 :
s e L PROD : = bands coils:
param r e v e n u e : 1 2 3 4
bands 2S 26 2? 27
coils 30 3S 3? 39
param c c c i n i t : 1 2 3 4
bands 3000 3 000 3000 3000
coils 2000 2 000 2000 2000
param m a r k e L : 1 2 3 4
bands GO 00 6000 4000 6S00
coils 4000 2 SOO 3S00 42 00
lhen there are not enough hours to produce even these minimum amounts. and the solver
repons that the problem is infeasible:
ampl: aolvo;
Ml NOS S . S : i n f e a s i b l e problem.
13 i L e r a L i o n s
In the solution that is returned. the inventory o f c o i k in the l&vt period is negative:
Thcsc are ty picai o f the infeasible results that solvcrs return. T h e infeasibilitkrs are scat-
tered around the solution. so that it is hard to tell what changes might be neeessary to
achieve feasibility. By extending the idea o f penahies. w e can better concentrate the
infeasibility where it can be under&lood.
Suppose that we want to view the infeasibility in terms o f a shonage o f hours. Imag-
ine that w e extend the piecewise-linear penalty funetion o f Figure 17-4 to the one shown
in Figure 17-6. N o w U s e i t l is allowad to incrcasc pavt â v â i l _ m a x ( t h but only
with an extremely steep penalty per hour — so that the solution will use hours above
avail_max(tl only totheextent absolutely neeessary.
In A M P L the new penalty funetion tv iniroducedthrough the following changes:
maximize T o t a l _ P r o í i t :
sum ( p i n PROD. t i n 1 . . T } < r e v e n u e l p . 11 * S e l 1 lp . 11 -
proricost l pl*Makelp.t| - i n v e o s t I p l * l n v l p . t j J
- sum ( t i n 1. , T > < < a v a i l _ m i n l t | . a v a i l . m a x l t |:
0 . time penalty l t | . 1 0 0 0 0 0 » UseltJ:
pcnilty
Sclllp.tl
conini t l p . t 1
This table implie* that the oommkments can be met only by adding about 21 hours,
mostly in the bst wxrek.
Ahernaiively, wxr m a y v i e w the infea&ibQity in lerms o f an excess o f commitmenfc.
For this purpose subtract a very large penal ty from the objective for each unh that
S e l l [p. tl falls b e b w c o r e n í t [ p . t l ; the penalty ai a funetion o f S e l l [ p . t l is
dcpicted in Figure 17-7.
Since this funetion ha* a brcakpoint at c o r e n i t [ p . t l . with a sk>pe o f 0 t o the right
and a very negative value k> the left, it would seem that the A M P L representation cx>uld be
Rccall, howxrver, A M P L ' s convention that such a funetion takes the value zero at zero.
Figure 17-7 clearly shows that wxr want our penahy funetion t o take a positive value at
zero, s o that it will fali k> zero at c o r e n í t t p . t l and beyond. In fact w e want the fune-
tion k> take a value o f 1 0 0 0 0 0 * c o r e n í t [ p . t ) al zero, and \v>í could express the
funetion properly by adding thisconstant t o the penalty expression:
T h e same thing may be said more concisely by using a second argument that states
explicitly where the piecewise-linear funetion should cvaluate t o z e r o :
This says that the funetion should be zero ai c o r c n i t [ p . t l , as Figure 17-7 shows. In
the completed nnxlel, \V>Í have:
SECT ON 17.2 CCWWCN T V O P ECE AND THREE P E CE TE W S 377
The rest of the mixlel is the same as in Figure l7-5a. Notice that S e l l [ p . t ) appears in
both a linear and a piecewise-linear term within the objective funetion: AMPL automati-
cally recognizes that the sum of these ter nu is also piecewise-linear.
This version. using the same data. pnxluces a solution in which the amounts sold are
ai follows:
T o get by with the given number of hours, commitmcnti to deliver coils are cut by 2500
tons in the first wvek and -143 tons in the founh wvek.
Reversible activities
Almost ali of the linear programs in this lxx>k are formulated in terms of nonnegative
variables. Sometimes a variable makes sense at negative as well as positive values, how-
ever, and in many such cases the associatcd cost is piecewise-linear whh a breakpoint at
zero.
One example is provided by the invenu>ry variables in FI^UÍK: l7-5a. W e have
defined I n v l p . t ] to represem the tons o f product p inventoried at the end of wxrek t .
That is, after wvek L there are I n v [ p . t ] tons o f prixluct p that have been made but not
sold. A negative value of I n v [ p . t ] could thus reaionably be interpreted as represent-
ing tons of pnxluct p that have been sold but not made — *>ns backordered. in elYeet.
The material balance constraints.
s u b j o c L Lo B a l a n ç o ( p i n PROD. L i n 1 . . T } :
Hakolp. t j + I n v l p . t - U = S e l l l p . t l + I n v l p . L l :
This analysis sug^ests that we remove lhe > = 0 from lhe dcclaration o f I n v in our
nuxlel. Then hackordcring might be especiaDy attractive if the sales price were expeeted
to drop in later weeks. like this:
revenue: 1 2 3 4
bands 25 26 23 20
coils 30 35 31 25
When we re-solve with appropriately revised nuxlel and data files, however, the results
are not what we expect:
Then lhe slopes for lhe I n v l p , t ] term in lhe objective are - b a c k c o s t t p ] and
i n v c o s t l p ] , with the brcakpoint at zero, and the correet objective funetion
maximize T o t a l _ P r o £ i t :
sum ( p i n PROD. t i n 1 . . T }
( r e v e n u e l p . t l * S e l l l p . t j - p r o d c o s t lp p M a k e l p . 11
- <<0; - h a c k c o s t l p l . i n v c o s t l p l » I n v l p . t j j
- sum ( t i n 1. . T > < < a v a i l _ m i n l t 1; 0. L i m e p e n a l L y l t j » " J s e l t 1:
In contrast to our first exaniple, the piecewise-linear funetion is subtracted rather than
addcd. The result is still piecewise-linear, though: it's the same as if wv? haJ added the
expression < < 0 ; b a c k c o s t [ p ) , - i n v c o s t ( p l >> Inv(p,t).
When w e make this change, and aJd some hackorder costs to the data, w e get a more
reau>nablc-looking solution. Nevenheless. there remains a tendency to make nothing and
hackorder everything in the laier periods: this & an 4, end e f l e c t ' ' that occurs because the
nnxlel d*xs not account for the eventual pnxluction cost o f keira backordered pait the
lavt perkxl. As a quick f i x , w e can mie out any remaining backorders at the end, by
aJding a constraint that final-\rcek inventory must be nonnegative:
Solving with thiü constraint and with b a c k c o s t values o f I.S for hand and 2 for coils:
a m p l : xzodol ataalplS .modj data otoolpl5. dat; aolvo;
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
20 i t e r a t i o n s . o b j e c t i v e 37 0 7 5 2 . 8 5 7 1
About 800 tons o f coils for weeks 2 and 3 will be delivered a wxrek late under this plan.
or more concisoly a*
The c urrem version o f A M P I . does noi detect that these expressions are piecewise-linear,
so you are unlikely to get satisl*acti>ry results if you try to solve a nnxlel that has expres-
sions like these in its objeetive. T o take advantage o f linear programming techniques that
can be applied for piecewise-linear terms, you need to use the piecewise-linear terminol-
<>sy
« a v a i l _ m i n l Ll : O.Lime p e n a l L y l L j » U.celLl
or equivalently,
r-eL PBDPLK:
r-eL PROJBCTS;
What if we want the fairest assignment instead o f t h e cheapest? Then might minimize
the maximum cost o f any one person's assignmenb:
SECT CN 17.3 OTHER P ECSV/SE L N E / « RJNCTOUS 381
sot PK0PLIS:
SOL PROJBCTS;
param s u p p l y (PKOPLli} > = 0 ; 4 hours each pcrson i s a v a i l a b l e
param demand (PROJUCTS} >= 0 : 4 hours each p r o j o c L r o q u i r e s
v a r M:
var Assign (i in PDDPLlí. j i n PROJüCTS} > = 0. <= limiLli.jl:
m i n i m i z e Max_CosL: M:
s u b j o c L Lo M^def ( i i n PWDPLIí}:
M > = sum ( j i n PROJKCrS} c o s L l i . j j * Assignli.jl:
s u b j o c L Lo S u p p l y ( i i n PK0PLIÍ} í
sum ( j i n PR0JKCTS} A s s i g n l i . j l = supply [11;
s u b j o c L Lo Demand ( j i n PROJBCTS} :
sum ( i i n PBDPLIÍ} A s s i g n l i . j l = demandljl;
m i n i m i z e Max C o s L :
max ( i i n PK0PLH}
sum ( j i n PROJD2TS} cosLli.jj * Assignli.jl:
This funetion is also piecewise-linear, in a sense: it is pieced together from the linear
functions sum { j i n PRCXJBCTS} c o s t [ i . j l • A s s i g n l i . j l for d iflerent people
i . However, h is not piecew se-linear in the individual variables — in mathematical jar-
gon. it is not separable — and hence it cannot be written using the < < . . . > > notaiion.
T h i i ii a case in which piecewise-linearity can only behandlcd by rewriting the nnxlel
a linear program. W e introduo? a n e w variable X t o represent the maximum. Then w e
wrhe constraints toguarantee that X is greater than or equal to each cost o f which it is the
maximum:
v a r M:
m i n i m i z e M a x _ C o s L : M:
s u b j o c L Lo M _ d e f ( i i n PKOPLlí} :
M >= sum ( j i n PROJISCTS} c o s L l i . j j * Assignli.jl:
Because X is being minimi/ed. at the optimal solution it will in fact equal the maximum
o f sum < j i n PROJBCTS) c o s t l i . j l • Assignli.jl over ali i in PEX>PLE.
The other oonstraintv are the same as in any assignment problem, as shown in Figure
17-9.
382 PECEV/SE L NEAR FTO3R6W5 C H í f T Ç R 17
This kind o f reformulation can bc applied to any problem that has a "min-max**
objective. The same idea works for the analogous "max-min" objective, with
m a x i m i z e insteadof m i n i m i z e and w i t h X < = . . . intheconstraints.
where brtiikp&inl-líst and slopt-tisi each consist o f a com ma-separated list o f one or more
items. A n item may be an individual arithmetic expression. or an indexing expression
followxrd by an arithmetic expressk>n. In the latter case, the indexing expression must be
an ordered set: the item ti expanded toa list by evaluating the arithmetic expressk>n once
for each set member (as in the example o f Figure l7-3a).
After any indexed items are expanded. the number o f slopes must be one more than
the number o f brcakpoints. and the brcakpoints must be nondecreasing. The resuhing
piecewise-linear funetion is constnicted by interleaving the slopes and brcakpoints in the
order given. with the first sk>pe to the left o f the first breakpoint. and the bst slope to the
right of the bst breakpoint. By indexing brcakpoints over an empty set, it is possible to
speeify no brcakpoints and one sk>pe, in which case the funetion is linear.
T h e />/-argumenl may have one o f the forms
IYvrtf
(a*%-txpr)
(a)x • expr. yro expr]
The iur-rtf (a reference to a previously dcclarcd variable) or the urg-expr (an arithmetic
expression) specifies the point where the piecewise-linear funetion is to be evaluated.
The itro-expr is an arithmetic expressk>n that specifies a pbce where the funetion & zero;
when the ztro-expr ts omitted, the funetion is avsumcd to be zero at zero.
SECT C N 17.4 Q U C € L N E S F O R P E CE V/SE L N E / F * C P T W Z A T C N 3 8 3
Bibliography
Robcit Fourer. " A Simplex Algorithm f<* Piecewi<e Linear Programming III: Computitkinil
Anahsis And Apphcotions." Mathcniatical Pmgrammmg 53 (1992) pp. 213-235. A sursey o f
conwrskim from p x w w M * krvar to hrvaiprogram*, andai applicatkuw.
Robcit Fourer jmd R<iy IL Marsten. "Solvmg Piecewise Linear Programs: lixperimenfc with a
Simplex Approach." OR.SA Journ.il <«i Computirçg 4 (1992) pp. 16-31. IX-scripton* of varied
apphcationx JLIIJ of experience ínsalsme them.
Spyros KonfcigicrgK. "Practical Piecewise Linear Approximation f<r Monotropic Optmii/ation."
INFORMS J ou mil on Comptfmg 12 (2C10CI>pp. 324-340. Ciuideincs kw ckia<ing the hreakpomts
when apprcuimating a rcinlinear funclkinby a piecWKC linear one.
Excrcises
17-1. Pxxewise linear modek an: xametimes an alternative ki the nonlinear model* described m
Chajrtcr 18. rcplocmc a smo<ith curve by a serie* o f straight line segmenfc. Thi< exercite deak
with th: model shown in Figure 18 4.
<a> Reformulo*: the model of Figure 18 4 sothit itapproximofles each rcml meai term
Cranflri^] / ( 1 - Trans l i , } ] / l í c r l t l i , ) ] )
( c ) IVrmuUtc a mote sophi<ticaled \ersion in which the number o f Ü m r pieom for each t e m i K
given bv a p w m r t e f n s l . P i e i th? hreakpoinfe tci be at ( k / n s l J * l i m i L l i . j 1 for k from 1
t o n s l - 1 . P i e i t h : xlopes so thit the p e c e w i » Imeai finetian cquals t h : <rigiiul ncMihrvai íunc
tkin when T r a n s l i . j 1 K ( k / n s l J * l i m i t l i . j 1 f<r any k from 0 tci n s l - 1 , o r when
Transli,j|is (nsl-1/4J/nsl *limit [i,jl.
Check your model by showing thit you gci the some resuks as in <b) when n s l is 3. Then. by try
irçg higher values cif n s l , determine h o w many linear piecesthe approxnnatxin requires in order tci
determine ali shipment anuiu ms tci wilhin about l(Kv o f the amou nts recomnicnded by the <rigiiul
nanKncw model.
1 7 - 2 . This exercite asks how you might convevt the denund constraint* in the transp<Bta«ion
model o f Figure 3 - l a into the kind o f " s o f t " constraints descri bed in Section 172.
Suppase that mstcad o f a sirçgk- parameter cal k d d e m a n d l j | at each destination j . you an: gi\en
the following four jurameters that describe m m o r e camplicafcd situitkin:
V) ] pcfcncd j u u j u í vh^x-dio }
d 1 i^Uc auxinunth* may tc \hffvd to )
There an: also two penal ty costs for shipment amounts outside o f the p r e f e n e d hmits:
Hecause the total shipped t o j is no longer fixed. a new variable R o c e i v e l j l is introdured lei
represent the amount received at j .
<a> M o d i f y the model o f Figure 3 l a tci use this new information. The modificatkins will m volve
declaring R e c c i v c l j l with the appropriate kiwx-r and upper bound*. adding a three piece
piecewise linear penalty term to the objccti\e function. aixl substituting R c c o i v o l j \ fcir
d e m a r x i l j l in the constraints.
<b) A d d the folkiwirç; demand information tci the dati of Figure 3- 1b:
Ixt dem m i n p o n and d cm m a x ^ p c n be 2 and 4,reStpec(ively. Tind the new optimal sohitian.
In the solutkin. which destiniticim l e c e i w shipments thit an: outside the prefened leseis?
1 7 - 3 . When the diet model of Figure 2-1 n run with the dita o f F ç u n : 2 3, there k rei feasible
solutkin. Thw exerci se asks yau t o use the ideas of Section 17.2 tci fmd s o m e g o o d near feasible
solutkim.
386 P E C E V / S E L NEAR F T O 3 R 6 W 5 C H í f T Ç R 17
(a) Modify éie modcl so that à is pottiik-. at A vcry high pcxulty,ta puichise nure than the speci-
fied maximumaf a food. In th? iesulfai£salutk>n. whidi maximums are exceed cd?
<b) Modify th: modcl sothit it K pomiila, at a very high perulty.to supply niore thin th: specified
nuiumiim of A nutrient. In the resukaig sohitian. which maximums are exceeded?
( c ) Using ex treme ly tirge peiultics. surh as IO 31 nu\ gi\e the sol\er numérica! diffirukics.
H&pcrimenl t o ser haw available solvers bcha\e when you use peralty terms like 10 a ' and 1(Vvi.
1 7 - 4 . In the modcl o f Hxercise 4 4<b). th: chinge in düwsc fiom ene periad to the next w Imülcd
to some number .1/. As am ditemitiw Io iaifXMfliç this limit. suppose that we introduce A new vari-
able D, thit representa the chinge in number of crews (in A\\ shifta) JÁ periad I. This variable may
be positi\e. indicaling an ânciease in crews o\vr the prevkiu* periad. <R negative. indicatirçg A
danease in crews.
f<* each 1 = 1 T. We then est anote cxwts o f c* per ciew added fiam period to period. and c~
pt* ciew dropped fram period to period: os a lesulc th? folkiwirç; cost must be inrluded in the
objcclive f o i each manih i:
if Df <0:
c* if Df>0.
RcfcrmuLite the niodel ai A M P l accordjrçglv. usirçg a piecewise linear funclkin to represent thrs
extra cost.
Solve ming c~ = -20(100 and c* = 1CKKKKI together with th: dita pieviously g i w n . Haw does thrs
salutkincompire to the one from Kxerci*? 4-4(b)?
1 7 - 5 . Th? foDawing "credit scoring" problem appears in many contexto, mchidirçg the ptocew
irçg o f credit caid applicatkim. A set APPL o f peaph? opply f o i a caid. each afKwering a set QUKS
afquestians <*i the applicatkin. "The respomeof person i to questian j i* converto! to a number,
a n s ( i . j l : typical numbers are jears at current addres*. manilly intime, and a homeownership
indicatoi(say. 1 if a home isowned and 0 atherwwe*.
To sununari/e the lespoiwes. th? caid wsuer chooses wx*ighta W t [ j 1, from which a scoie f o i each
person i i n A P P L is aimputol by the bnear fcrmuLi
"The imier abo cIkkkch a c u t o f f . C u t : credit is grantol when an appbcant's scoie is greater thin or
equal to the cutoff. and w cknxrd when the soan? is lew than the cutoff. In thrs way the decisicm
can be made objedi\ely (if not always mcKtwnel>'>.
To ctKKKC the weights and the cutoff. the caid iwuer colleds a simple o f pn?vkHCfly accepted
apphcaticais. some fram people who turned <iut to be good custcmiers, anJ same from people who
never paid theii híDs. If we denote these two calkctiorK o f pe<iple by « t s Q 0 0 D and BAD. then the
ideal weighto and cutoff (for thrs dati) would satisfy
Since the iela«i<Biship between answers to an appkcatian and creditwortimew is imprecise at best.
however. no values af W t [ j ] and C u t can be found to satisfy ali of these inequalitics. Imtcad.
SECT CN 17.4 QUC€LNES FOR PE CE V/SE L NE/F* C P T W Z A T C N 387
lhe ixtuer his ( o chaosc values thai an: m e i e l y lhe b « l potsiblc. in nome xcikc. There are any
number o f m y x l o m o l e such a choicr; hrre, faturai ly, w e o o m i d e r an optimi/alkin apprcuch.
( a ) Supp<*e thit w e define a new varubte D i LI [ i J thil equils lhe differcnce between person i 's
scorc and lhe cukiff:
C l a t f l y lhe undesimbke cases are when: D i f f l i 1 is nego* \v for i in GODD, JLIKJ where il K non-
negat vv for i in BAD. T o d u a i u r a g e lhese cises, w e c a n leD lhe iwuer to niininü/e lhe funclkin
Iir. JClfl : 01 02 RI R2 R3 S2 ?4
-15 1.0 10 15 20 10 B 10
-16 0.0 5 15 40 B 10 B
-17 0.5 10 25 35 B 10 10
-1B 1.5 10 25 30 B 6 10
-19 1.5 5 20 25 B B B
-20 1.0 5 5 30 B B 6
-21 1.0 10 20 30 B 10 10
-22 0.5 10 25 40 B B 10
-23 0.5 10 25 25 B B 14
-24 1.0 10 15 40 B 10 10
-2S 0.0 5 15 15 10 12 10
-26 0.5 10 15 20 B 10 10
-27 1.0 5 10 25 10 B 6
-2B 0.0 5 15 40 B 10 B
-29 1.0 5 15 40 B B 10
-30 1.5 5 20 25 10 10 14 ;
Whal ore lhe ch<Kcn wvvghfc? Usirçg lhese wvighfc. how many o f lhe g o o d cu<tomcrs would be
densed a card. anJ h o w many o f lhe b j i d r i s i s would be granlcd <nc?
Y o u shciuld fmd Ihjí a kit o f lhe bad m l s h a w scores right at lhe cutoff. W h y does Ihrs happen «n
lhe solutkm? H o w nqght you j d j i M lhe culoff to deal wichif?
( f ) T o force s « » e s further a w a y f r o m lhe culoff (in lhe desánrd direction}. it might be preferable to
use lhe folkiwirç; abjeclive,
fiar. fi í n GOOD) r r * x ( 0 , - D í í f m * o £ í f l * t ) •
flua fi í n BAD) r r j x ( f l , D l f f r H « o f f f i â t )
when: o £ f s c t is a positive pirameter whcwe vahie k suppÜed Hxpiun why Ihrs chinge his lhe
detired e f f e c l . Try offset values o f 2 anJ 10 and compare lhe resulfc w i é i thosc in ( e ) .
388 P E C E V / S E L NEAR F T O 3 R 6 W 5 C H í f T Ç R 17
(5) S u p p o » that givirçg a CJLTÜ ki a bad credit rwk K consideied much more undtrsxrabk: than refus
ii^S * card ki a g o o d cnxkl risk. l l o w would youchange the model to t t k e thrs intooccount?
(h> Suppose ÚIJU when someone's apphcotian is occepted. h i s o r her scarc is also used ki suggest JUI
imtoJ credit Imut. Thus it is p j j l x u L u l y mip<*1ant (hot tud credit risks not r e c c i w very Urge
sairvs. l l o w would you add p i c o » t o #ic p í e c e m » linear objective funclkin t e n » ki account for
thisconcem?
17-6. bl Hxercise 18 3 . w e suggest a w a y ki est imole positkin. velocily OJKI occvlerotian values
from impreciso d o u . by mmmú/ins a nonlinear " s u m a f squores" funetion:
£ \h, - ( a n - a ^ - K a t i j ) ] 2 .
/•1
( a ) Substituto #ie s u m o f ahsolute values directlv for the s u m o f sqiures in the model fiam Hxercwe
18 3. firtf with the a b s funetion, ai»J then with A M H / s explicitpiecvwise linear rcitilkin.
I:\plam why neither o f these fcrmuUtkins is bkely to be hanJk-d e f f e d i v e l y by any solver.
<b) T o nuidd thrs situitkin efíeclively. wv introducc v a r ú b l m f . to represent the individual fcrmu
Ias h. - ( a n - a l t i - , A a 2 l j ) whose ahsolute values aiv being t&ken. "Then w e can exprcss the
mirámizatian o f the sum of absolule values as the foOawíng constrai ned optmu/otian problem:
Mm mu A: £ R.\
> 1
Subject ki r i = hf - (atí-all/-%a2lj), j= 1 n
Write an ^ t P L model kw thrs formulatian. usirçg the piecvwise linear notatian for the terms .
( c ) S o l v e for d 0 , a l % and <i 2 using the dita f r o m Exerci*? 18 3. I l o w much diffcrencc is thexv
b d w e c n this estimate aixl the least squires one?
Use d i . c p l a y ki prmt the values for txilh lhe k*ast squarcs and the least ahsolute values sohi*
tkins. W h i l isthe masl obviausquilitatiw diffcxence?
( d ) Yct another pttssitukty i s t o focus c«i the greaiest ahsohiie devstfion. rather thin the sum:
1 7 - 7 . A plarur atmiiut consists o f a set of jtúnis connecled by bar*. For example. in the foi
lawiqg ducranu the jomts are represented by circkrs. and the hirs by lines between two circles:
SECT CN 17.4 QUC€LNES FOR PE CE V/SE L NE/F* CPTWZATCN 389
Comider Ih: problem o f fmdirç; a niinímuni we^ghl struclure to meei certam externai f o c e s . W c
let J be the set <if jcnnts, and BQJXJ be the se* o f admisâtír hirs; f<r the ducra.m abo\e. we could
i i k c J = (1,2,3,4,51,and
B = {< 1 , 2 ) , ( 1 , 3 ) , < 1 , 4 ) , ( 2 , 3 ) , ( 2 , 5 ) , ( 3 , 4 ) , <3,5), ( 4 , 5 ) ) .
The " c r i g i n " aixJ "dest matam" o í a boi are ajtiit rary. T h : bar bc«wccn joints 1 xixi Z for exam-
ple, coukJ be repnrsented in B by either ( l , 2 ) o r ( 2 , l ) . but it necdnot be represenlcd by b<*h.
We can use two dmiemkiiul liuchdean cocrd males lo specify the posítion of each jimt in the
pline. taking some arbitrary point as the origm:
a' hcsi/ontal positian of jomt i x-latisv Io the origm
a\ vertical potitkin of joint i relitive to the <mgin
lx»r the example. if the origm lies exaclly at jomt Z wc might hive
<a'l.a\)=<(12>, ( f l j , a ; > = <0,0>, ( f l J , f l J ) = ( Z IX,
( f l í , a j > = ( 4 , 2>, ( f l j , a ' s ) = <4,0*.
The remai nirçg dali comrst of the etf ernil f o r a » on the jokifc:
f* hcsi/xintal c<mip<ment of the exlemal foice on jomt i
ff vertical component of the exlenul f a c e <m joint i
To resist this force, a xubset S c J o f jamt< k Fued m p»sition. (It can be proved thit fixmg two
joints is sul fiei ent Ia guiranlec a solution.)
The exlemal faces mducc sttesses <m the turs. which we can represent as
F« if > 0 , tenskin on lur ( i % j )
if < 0 , compression of lur ( » J )
A set o f sliesses is in tqwBbrium if the externai f a c e s , fcnáans aixl campfextioiK tu lance at ali
joints, m both the horizontal and wrtical components — except at the fixed joints. That is, for
each jomt A tf 5,
where c't aixl c\ are the casmes of the direction from joint * tojoint l with the hcri/ontil aixl verti
cal oxes.
tí=<a;-a'gyiin
/ , = ?l<a;-a't? + <a;-a]f.
In general, there are mfmitcly many different sets of eqinhhnimi sliesses. liowevcr, it can be
shawn that a given system o f sttesses will be reab/ed m astrueture o f minimum weight if and only
if the cross sectknul arcas o f t h e turs aie propcrtkirul to the obsohile values o f the sttesses. Smce
the wcigfit o f a bar is propatkiiul Io the cross section times lerçgth. we can t&kc the (suitibly
scaled) \svicht of bar (i,/> to be
» # = v \r,\.
"The problem is then lei fiixl a system o f sirenes F t i that meei the eqinhhnimi conditíoiK, axxl thit
nünimi/e the sumof the weights w4|.o\er ali turs ( i , / ) 4 B.
(a> The mdexmg sets for this linear program can be dcclued in as:
390 P E C E V / S E L NEAR F T O 3 R 6 W 5 C H í f T Ç R 17
aat j o i n r . f i ;
aat f l x a d w i t í i i n j o i n r . f i ;
sac b a t e w l t t i l n f i i n j o i n t f i , } i n >ointfl: i o });
lJ<ing l h » e sei decUratxim. fcvmuLUe an AMPl. nicxld f<* the miramum weight stru^ural design
pxthlem. Use die piecewise linear notation cií thr* chapter to n y i ^ c r t the absohilevahie tevn» in
theobjecti\e íunetian.
<b) Now considerin pjJlx~uLira stroclure that has the falk>wing jcnnCs:
.75 © © © ©
Assume thit Iheie K one unit horizortiQy aixl vevlically betueeti joints. axxl thjU the origin is at the
\awct left; thus ia' l % a\) = ( 0 . 2 ) a n d < f l í 5 , f l í 5 ) = (5,0).
Le« there be etfemil forcesof 3.25 aixl 1.75 unifc straight dowmvard <m jcnnls 1 aixl 7. so tha* f[ =
- 3 2 5 . / / = -1.75. aixl otherwise ali fí = 0 and// = 0 . Le« S = {6.15J. RnaDy, let the adnwsible
b * s consist o f ali possible bars thit do not g o dixectly throtçh a joint; for e n m p k , ( 1 , 2 ) or ( 1 , 9 )
or (1.13) waukl be admusible. but ixit (1.3) or (1.12)or (1.14).
Determine ali the dati f<r th: problem thit is needed bv th: fincar program. aixl represent it as
AMPI. dita statements.
( c ) Use AMPL to solve the linear program and to examine the miramum weight structuie that rs
detemiined.
Drsw a d u g r a m o f the optimal structuie. iixlicating the CJXKS SCCIXIIK o f the bars aixl the natureof
the stresses. If there is zero force on a tur. it has a cross seclxin o f zero. aixl may be k-ft out o f
your di agram.
(d) Repeat parfc ( b ) aixl ( c ) for the case in which ali possfck- bars aie adnússible. Is the resultirçg
strurttffe different? Is itany hghter?
5
•a
5
O -í
0) l i
5
E fjfi iVJ!— 3 a
S Í S c S
1 « l i a 3 - f
I S1 2
A
- 'J s ; a-
i § i É 5 1 9 £ a-s 'j
' i i
£ S
- l i
í 25 I l i o JJ
< i
-j e 8
í-g -a3: S-SJ3 J
~ o
a É
O)
3
u
o ' 11 2 S. fr 5* ^ s ^ s
J* c1 *®
»• V
I I
00 2 ! i js o s l
a l i a
SsgI
<3 3 I 2
.9 11 2
c.
3 J « 3 1 s
i
&2
s-iJi
1
l
a s M S .2
I s .2 l - s l
11
á 3
. -j * 1 È -
II if
I i I I2 * a | 0
2!
= á
s t— l á l
<3 * s
i2
"J JX i o d:
yí * ® .2 9 â 1 S-J «i
s 0)
c « w & a £ jj ü
fi
&
ri 1 8 § a H á S
O * 5 1 -SL a o • !
í J i I i .a« i .1 l l
•
c
£ .3
tf l l í i ^ -a ê 1 3 *
-a o
K
3
o I
o á s 'J s
5 3?
>
È e 77 jJ "5
"f!'í O ^
s
lifl
í 1 1
1 |i
O s
2 I M
5 .5
l h
ft a * % as;
s | | o 3 ^ 5 ã S-S
d !
h .2, S l l
!
s a «
2 rá 5-3 ^
S . Í 5 s l a í®
^ • 5 — a 2 o
•s
3
I ?
a 3.2-s í i t 5I f l § I ê i
2 - c ç s
c | | l ! x C a
a -a
í 3
^9 ^ — s s
s a I í 2 s . 5J
= s |« 55 -
j í s 5
S.l i j 5
111
«
0 -
H
I " A l 5.
s.
si
CO -Ti I « a o .3
2 S 3 1 3 -
l . iw 1 l * S
á
A
2 a
a : 8 %
; I %i i i i
2 5 8 TJ i á*
- C vi * ? 2 | g
is!
S 5 3» g a 5 s a - a > ? =
OC !>
S . S ! •=
= 8s *B s 3 S
392 PO*. FTOGRftWS C H í f T E R 13
minimize ToLal_CosL:
sum ( < i . j ) i n L I N K S } cosLli.jl * Ship l i . j l ;
where c o s t I i . j 1 and S h i p [ i . j 1 represent the cost per unit and total units shipped
betwxren cities i and j , with L I N K S being the set o f ali city pairs between which ship-
ment routes exist. T h e constraints are halano? o f flow at each city:
s u b j o c L Lo B a l a n ç o ( k i n C I T 1 B S } :
supply l kj sum ( < i . k j i n L I N K S } Shipli.kl
= d e m a n d l k l «• sum ( < k . j ) i n L I N K S } Shiplk.jl:
SECT CN i a i S O U R C E S CF N C N L N E / R 7 Y 3 9 3
T h e linear network flow model assumes that each unit shipped from city i k> city j
incurs the same shipping c o s t c o s t [ i . j ] . Figure l8-2a shows a typicai plot o f ship-
ping cost versus amount shipped in this case: the plot is a line with slope c o s t I i . j ]
(hence the term linear). The other plots in Fjgure I8-2 show a variety of other ways,
none o f them linear, in which shipping cost could depend on the shipment amount.
In Figure l8-2b the cost also tends to increase linearly whh the amount shipped. but at
certain criticai amounts the cost per unit <that is. the slope of the line) makcs an abrupt
change. This kind o f funetion is callcd piecewise-linear. lt is not linear, strictly speak-
ing. but it is also not smoothly nonlinear. The use o f piecewise-linear objectives is the
topicof Chapter 17.
In Figure l8-2c the funetion itself jumpsabmptly. When nothing is shipped, the ship-
ping cost is zero: but when there is any shipment at ali, the cost is linear staning from a
value greater than zero. In th& caie there is a fixed cost for using the link from i to j ,
plus a variable cost per unit shipped. Again, this is not a funetion that can be handlcd by
linear programming lechniques, but it fc also not a sn*x>th nonlinear funetion. Fixed
costs are most commonly handlcd by use o f integer variables. which are the topic o f
Chapter 20.
T h e remaining plots illustrate the sorts of smooth nonlinear funetions that \v>í want to
consider in this chapter. Figure l8-2d showsa kind of concave cost funetion. T h e incre-
mentai cost for each additional unit shipped (that is. the slope of the plot) is great at first
but beeomes lessas more units are shipped: after a ceriain point the cost is nearly linear.
This is acontinuous aliernativc to the fixed cost funetion of Figure l8-2c. lt could also
be used to approximate the cost for a situatk>n (resembling Figure IH-2b) in which vol-
ume dfecounts become available a* the amount shipped increases.
Figure l8-2e shows a kind of convex cost funetion. The cost is more or less linear for
smaller shipments, but rises steeply as shipment amounts approach some criticai amount
This sort of funetion woukl be used to nnxlel a situai k>n in which the lowzst cost shippcrs
are used first while shipping beeomes progressively more expensive as the number o f
units increases. The criticai amount represents, in effect, an upper bound on the ship-
ments.
These are some of the simplest functional for ms. The funetions that you consider will
depend on the kind of situatk>n that you are trying to nnxlel. Figure l8-2f shows a possi-
bilhy that is neither concave nor convex. combining features o f the prevk>us t w o exam-
ples.
Whereas linear funetions are essentially ali the sameexcept for the choice o f coeíTi-
cients (or slopes), nonlinear funetions can be defined by an infinite variety o f d i f f e r e n t
formulas. Thus in buikling a nonlinear programming model. it is up to you to derive or
specify nonlinear funetions that propor ly represem the situai ion at hand. In the objective
394 PO*. FTOGRftWS CHífTER 13
of the transportation example. for instance. one possibility would bc to replace the prod-
uct c o s t ( i . j ] • S h i p l i . j l by
( c o s L i l i . j l + c o s L2 [ i . j l * Sh i p [ i . j l J / <1 • S h i p l i . j l J
» Shipli.jl
This funetion g r o w s quickly at small shipmcnt levek but leveis o f f k> essentially linear at
larger leveis. Thus it represents one way to implement the curve shown in Figure l8-2d.
Another way to approach the specifieation of a nonlinear objective funetion is to
focus on the slopes o f the pk>ts in Figure 18-2. In the linear case of Figure l&-2a, the
slope o f the plot is constam: that is why \V>Í can use a single parameter c o s t [ i . j 1 to
represent the cost per unit shippcd. In the piecewise-linear case o f Figure IH-2b, the
slope is constam within each interval: w e can express such piecewise-linear functk>ns as
explained in Chapter 17.
In the nonlinear case. however. the sk>pe varies continuously with the amount
shipped. This suggests that \V>Í g o hack to our original linear formulation of the network
flow problem, and turn the parameter c o s t I i . j 1 into a variable C o s t I i . j 1:
minimize ToLai_CosL:
sum ( i i n ORIG. j i n DEST} C o s L l i . j l * S h i p l i . j 1;
These equations are also nonlinear, because they involve division by an expressk>n that
contains a variable. It is easy to see that C o s t [ i . j ] is near c o s 1 1 1 i . j 1 where ship-
ments are near zero, but leveis ofT to c o s t 2 [ i . j ) at sufficiently high shipment leveis.
Thus the concave a>st o f Figure l8-2d is realized provided that the first cost is greater
than the sccond.
Assumptions o f nonlinearity can be found in constraints as w c l l The constraints o f
the network flow model embody only a wvak linearity avsumption. to the eflect that the
total shipped out o f a city is the sum o f the shipments to the other cities. But in the pro-
duetion nnxlel of Figure I -6a, lhe constraint
s u b j e c t Lo Time ( s i n 5TAGB}:
sum ( p i n PROD} ( 1 / r a L e l p . s 1 J * Make[p] <= avail[s];
embodies a strong assumption that the number of hours used in each stage s o f making
each product p gr ows linearly with the levei o f produetion.
3 9 6 N O M . NE/F3 F R D G R A V S C H í f T E R 13
Som crimes nonlincarity arises from a neod nuxlel a situai ion in which a linear func-
tion could not possibty exhibit the desired bchavior.
In a network nuxlel o f trafftc flows, ai one example, it may bc necessary to take con-
gestion into account. The total time to tra verse a shipment link should bc essentially a
oonstant for small shipment amounts, but should increase rapidly knvards infinity as the
capacity of the link isapproachcd. N o linear function this propoty, so we are foiced
to make travei time a nonlinear function o f shipment k>ad in order to get the desircd
effect.
One possibilhy for expressing the travei time is given by the function
t i mel i . j I * ( s e n s l i . j l * S h i p U . j | J / <1 - S h i p l i . j | / c a p l i . j | J
s u b j e c t t o B a l a n c e ( k i n CXT1HS} s
s u p p l y l kl sum ( < i . k j i n L1WKS} S h i p l i . k l
= demarxilkl • Di s e r e p a n c y l kl •
sum {< k. j ) i n L I N K S } S h i p l k . j l ;
One established approach for kecping the discrepancy from bccoming too large is k> add
a penalty cost *> the objective. If ihi* penalty is proportional to the amount o f the dis-
crepancy. then we have a convex piecewise-linear penalty term,
minimize Total_Cost:
sum ( < i . j ) i n L I N K S } c o s t l i . j l * S h i p l i . j l +
sum (k i n C l T I K S } pen * « - 1 . 1 : 0>> D i s c r e p a n c y lk 1 :
minimize ToLal_Cost:
sum ( < i . j ) i n L I N K S } c o s t l i . j l * S h i p l i . j ] +
sum (k i n C l T X K S } pcn * D i s c r c p a n c y l k l A 2 :
Nonlinear objectives that are a sum of squarcs o f some quanthics are common in opti-
mi/aiion problems thai involve approximatk>n t>r daia fitting.
There are many sourccs of nonlinearity in models o f physical activities likeoil refin-
ing, power transmission. and st ruc furai dcsign. More oflen than not, the nonlinear hies in
these models cannot be traced k> the rclaxation o f any linearity assumptions, but are a
oonsequence o f inherently nonlinear relationships that govern forces, volumes, currents
and so lorth. The forms o f the nonlinear functions in physical models may be eaiier to
determine, because they ar s e from cmpirical mcaiurcmcnts and the underlying laws o f
physics< rather thancconomics). On the other hand. the nonlinearities in physical models
tend to involve more complicaicd functional formsand interactionsamong the variables.
A s a simple example, a nnxlel of a natural ga* pi pe line network must iftcorpofatc not
only the shipments betwxren citie* but also the pressures at individual cities, which are
subject to cenain bounds. Thus in additk>n to the flow variables S h i p [ i , j 1 the nnxlel
must define a variable P r e s s [ k ] u> represent the pressure at each city k. lf the pressure
is greater atcity 1 than at city j , then the flow is from i to j and is relaied to the pres-
sure by
where c ( i . j ) & a constant dctcrmincd by the length. diameter, and efficiency o f the
pipe and the propenicsof the gas. Compressors and valves along the pipeline give rise to
dilTerent nonlinear flow rebtk>nships. Other kinds o f nctworks, notably for transm&sion
of ekrctrichy, have their own nonlinear flow relaiionships thai are dictaicd by the physics
o f the situaiion.
l f you know the algebraic form o f a nonlinear expression that you want to include in
your model, you can probably see a way to write it in AMPL. The next two sectk>ns o f
this chapirr consider some o f the speciflc issues and feaiures relevam to declaring vari-
ables for nonlinear programs and to writing nonlinear expressions. Lest you get carricd
away by the ea*e o f writing nonlinear expressk>ns, howevcr, the lavt section o f f e r s some
cautk>nary advice on solving nonlinear programs.
Y o u may specify values for A M P l . variables. Prior *> optimization. these " i n k i a l "
values can bedisplayed and manipulated by AMPl. commands. When you type s o l v e .
they are passcd k> the solver, which may use them av a staning guess at the solutk>n.
After the solver hav finished its work, the initial values are replaced by the computed
optimal ones.
Ali o f lhe AMPl. features for ass^gning vahies to parameters are also available for
variables. A v a r declaration may also specify initial values inan optional : = phrase: for
the transponation example.you can write
Any o f the data statements for parameters can also be used for variables, ai expbined in
Section 9.4.
Ali o f these features for assjgning values to the regular ( " p r i m a i " ) variables also
apply tothe dual variables associated with constraints (Section 12.5). AMPl. interprete an
assignmcnt to a constraint name ai an assignment to the associated dual variable or <in
the terminology more common in nonlincar programming) to the associated Lagrange
multiplier. A f e w solvers. such av MINOS, can make use of initial values for these multi-
plicas.
Y o u can often speed up the work o f t h e solver by suggesting good initial values. This
can be so even for linear programs, but the eftect is much stronger in the nonlincar case.
The choice o f an initial guess may determine what value o f t h e objective is found to be
" o p t i m a l " by the solver, or even whether the solver finds any optimal solution at ali.
These possibilities are discussed further in the bst section of this chapter.
I f you don't give any initial vahie for a variable, then AMPl. will tentatively set it to
zero. If the solver incorporates a routine for determining initial values, then it may re set
the values of any uninitialized variables, while making use o f t h e values of variables that
have been initiali/ed. Otherwise, uninitiali/ed variables will be left at zero. Although
zero is an obviousstarting point. it hav no special significance: for some o f t h e examples
that we will give in Section I8.-1. the solver cannot optimize successfully unless the initial
values are reset away from zero.
SECT C N IA2 NCPl.NE/«VAR/etES 399
s u b j o c L Lo CosL R o l a L i on C < i . j J i n L I N K S } :
CosLli.j | =
( c o s L l l i . j l • c o s L 2 1 i . j J * S h i p l i . j 1J / <1 * Shipli.jlJ;
If the expression to the right o f the = sign ii substituted for every appearance o f
C o s t [ i , j l . the C o s t variables can be eliminatod from the m o d e l and these con-
straints need not be passed to the solver. There are two ways in which you can te 11 AM PI.
to make such substitutions automatically.
First, by changing optk>n s u b s t o u t from its default value o f zero to one, you can
tell AMPL t o look for ali " d e f i n i n g " constraints that have the form shown above: a sin-
gle variable ii> the krft o f an = sign. When lha alternative & employed, AMPL tries to use
av many o f these constraints a* possible to substitute variables out of the mixlel. After
you have typed s o l v e and a nonlinear program has been generaied from a nnxlel and
daia. the constraint* are scanned in the order that they appeared in the nnxlel. A con-
straint is klentifiedas " d e f i n i n g " providedthat
• it has just one variable to the left of an = sign:
• the left-ha nd varia ble's declaration did not specify any restrictions. such ai inte-
gralhy or bounds: and
• the left-hand variable ha* not already appeared in a constraint identified ai defin-
ing.
The expression to the right o f the = sign is then substituted for every appearancv? o f the
left-hand variable in the other constraints. and the defining constraint is dropped. These
mies give A M P l . an eaiy way to avoid circular substitutions. but they do imply that the
naiureand number of substitutions may depend on the ordering o f the constraints.
A s an alternative. if you want to specify explicitly that a cenain collection o f variables
is *> be substituted out, use an = phrase in the declarationsof the variables. For the pre-
cedi ng example, you could wrhe:
Then the variables C o s t l i . j 3 would bereplaced every where by the expression foi k>w-
ing the = sign. l>?claratk>ns o f this kind can appear in any order, subject to the usual
requirement that every variableappearing in an = phrase must be previously defined.
Variables that can be substituted out are not mathematically necessary to the opti-
mi/ation problem. Nevertheless, they often serve an essential descriptive pur pose: by
associating names with nonlinear expressions, they permh more complicaied expressions
to be written understandably. Moreover, even though these variables have been removed
from the problem sent *> the solver, their names remain available for use in browsing
through the results of optimi/ation.
400 NOM. NE/f3 FRDGRAVS C H í f T E R 13
W h e n lhe same nonlinear expression appears more than o n c e in lhe objective and con-
straints. introducing a defined variable t o represem it m a y make the nnxlel more concise
a* w e l l as more readable. A M P L also processes such a substitution efllciently. Ingener-
aiing a represe ntatk>n o f the nonlinear program for the solver, A M P L does not substituir a
copy o f the w h o l e defining expression f o r each occurrence o f a defined variable. Instcad
it breaks the expression ink> a linear and a nonlinear pan. and saves one c o p y o f the non-
linear pari together with a list o f the locations where its value is k> be substituted: only the
terms o f the linear pan are substituted explicitly in muhiple locations. This separate
treaiment o f linear terms is advantagcous for solvers (such a* M I N O S ) that handle the lin-
ear terms specially, but it may be turned o f f by setting option l i n e l i m t o z e r o .
From the solver*sstandpoint. substitutions reduce the number o f constraints and vari-
ables. but tend t o make the constraint and objective expressk>ns m o r e complex. As a
resuh. there are circumstances in which a solver will perform better if defined variables
are not substituted out. W h e n d e v e l o p i n g a new model. you may have t o experiment t o
determine which substitutions g i v e the best results.
ií Plow(i, j] = 0 Lhcn 0 e l s e b A 5 o ( i . j 1 * C O S t [ i . j l * F l o w [ i a j J
These are cenainly not linear, but the first is not smooth (its slope changes abmptly at
z e r o ) and the second fc not even continuou* (its value j u m p s suddenly at zero). If you try
t o use such expressions. A M P L will not complain. and your solver may even return what
it claims to be an optimal solution — but the resuhs could be w r o n g .
Expressions that apply nonsnnx>th functkxns (such as a b s , m i n . and r r « x ) to vari-
ables generally pnxluce nonsnux>th results: the same is tme o f i f - t h e n - e l s e expres-
sions in which a condition involving variables folk>ws i £ . Nevertheless. there are useful
exceptions where a carefully written expression can preserve smix>thness. A s an e x a m -
SECT CN 13.3 N3M- NEAR EXTOSSOUS 401
( a ) * 2 i f . * 5 0 , - x 2 if ^ < 0
<b) l o g ( x ) / ( i - 1 )
pie. consider again the flow-pressure relaiionship f r o m Section 18.1. If the pressure is
greater at city i than at city j , then the f l o w is from i ti> j and is rebted to the pressure
by
If instead the pressure is greater ateity j than ai city i , a similar equation can be written:
But since the constante c ( i . j ] and c t j . i l rcfcr to the same pipe, they are equal.
Thus instead o f defining a separate variable for flow in each direction. \V>Í can let
Flow [ i, j ) be unrestricted in sign. with a positive value indicating flow f r o m i k> j
and a negative value indicating the opposite. Using this variable. the prevk>us pair o f
flow-pressure constraints can be replaced by one:
if a b s ( F l o w [ i , j 1 - 1 ) > 0 . 0 0 0 0 1 Lhcn
l o g ( Flowl i . j I) / ( K l o w l i . j |-1)
o i se
1.5 - Flow[i.jl/2
minimize ToLal_Cost:
suai ( i i n O R I G . j in DEST} C o s t l i . j l * Shipli.jl:
load st_aLlib.dll:
funetion cunjwrnal;
funetion invcumnoxmal;
Your nnxlel could then m a k e use o f these funetions to form expressions such as
cumnorrKil (mean [ i ) , s d e v [ i ) . I n v [ i , t ) } and i n v c u m n o r r w i l { 6 ) . If these
funetions are applicd t o variables. A M P I . also ar ranges for funetion evaluations to be car-
ried out during the solution process.
A funetion declaratk>n specifies a library functk>n's name and <optk>nally) its
required argumentv. There may be any number o f arguments. and even iterated collee-
tions o f arguments. Each function's declaration must appear before its use. For your
convenicnce, a script containing the f u n e t i o n dcvbrations may be supplied along with
the library, s o that a statement such ai i n c l u d e statlib is suíllcient t o provide
access t o ali o f the library's funetions. Documentation for the library w i l l indicate the
funetions available and the numbers and m e a n i n g s o f their arguments.
SECT O N 18.4 P T F A L L S O F WD NL N E A R F T O ^ W W N 3 403
Deter mining the correct l o a d command may involve a number o f details that dcpend
on the type of system you're using and even its speeific configuratk>n. See Section A.22
for further discussk>n of thepossibilitics and the related ÀMPLFUNC option.
I f you are ambitious. you can write and compile your own functk>n librarics. Instmc-
tions and examples are available from the A M P L website.
minimize Total_Cost:
sum ( i i n ORIG. j i n DEST}
r a t e [ i . j 1 * T r a n » [ i , j l / <1 - T r a n s i i . j 1 / l i m i t l i . j 1 J;
A n anempt k> solve using the nnxlel and data ai given proves unsuecessful:
The solver's messagc iscryptic, but strongly suggeas a division by zero while evaluating
the objective. That could only happen if the expression
1 - Transli. j l / l i m i t l i . jl
404 NOt*. NE/« FTOGRftWS CHVTÇR18
s e t ORlG: 4 origins
s e t DEST: * destinations
param s u p p i y (ORIG} >= 0: 4 amounts a v a i l a b l e a t o r i g i n s
param demand (DEST} >= 0: 4 amounts r e q u i r e d a t d e s t i n a t i o n s
check: sum ( i i n ORlG} supply [ i j = sum ( j i n OBST} demand[ j ] :
param r a t e (ORlG, DEST} >= 0 : 4 base shipment c o s t s p e r unit
param l i m i t (ORlG. DE SI*} > 0 : 4 l i m i t on u n i t s shipped
var Trans (i i n ORlG. j in DEST} >= 0 : 4 units to ship
minimize Total_Cost:
sum ( i i n ORIG. j i n DEST}
r a t e ( i . j | * T r a n s l i . j l / <1 - T r a n s i i . j J / l i m i t l i . j J J :
s u b j e c t t o Supply ( i i n O R l G } :
sum ( j i n DESr} T r a n s l i . j l = supplylij;
s u b j e c t t o Demand ( j i n D E S T } :
sum ( i i n ORIG} T r a n s L i . j l = d o m a n d ( j ) ;
is zero at some point If w e use d i s p l a y ii> print the pairs where T r a n s [ i , j 3 equals
limitli.jJ:
can soe the problem. The solver hav allowed T r a n s ( G À R Y , L A F ) to have the value
1000, which equals l i m i t [ G A R Y . L A F ) . A s a resuh. the objective funetion term
evaluates to8000/0. Since the solver is unable to evahiate the objective funetion. it gives
up without finding an optimal solution.
Because the behavior o f a nonlincar optimi/ation algorithm can be sensitive to the
choice o f staning guess, \v\r might hope that the solver will have greater success from a
difTcrcnt stan. Toensure that the comparison is meaningful. we first set
so that status informaiion about variables that was returned by the previous solve will not
be sent hack to help determine a staning point for the next solve. Then AMPl.'s let
c\>mmand may be used to suggcu. for example. a new initial vahie for each
T r a n s I i . j 1 that is half o f l i m i t I i . j 1:
This time the solver runs to oompletion. but there is still something wrong. The objective
is less than - I0 |}1 , or - o o for ali practical purp*>ses. and the solution is described as " c a n -
not be improved'' rather than optimal.
Examining the values o f T r a n s [ i . j ] / l i m i t l i . j ] inthe solution that the solver
hav returned gives a clue to the difTicuhy:
These ratios show that the shipments for several pairs. such as T r a n s [ C L E V . S T L ] ,
significantly exceed their limits. More seriousty. T r a n s [ G A R Y . F R E ] seems to be right
at i i m i t [ G À R Y . F R E ] , since their ratk>is given as I. If w e display them to fui 1 preci-
sion. howvrver, wvr see:
The variable is just slightly larger lhan lhe limit so the cost term has a huge negative
value. I f we graph the entire a>st funetion. as in Figure 18-6, see that indeed the cost
funetion goes o f f l o -c© to the r i g h t o f the singularity ai l i m i t ( G A R Y . FREJ.
T h e source o f error in both mns above isour assumption thai, since the objective goes
to +oo av T r a n s t i . j ) approaches l i m i t l i . j ] from below, the solver will keep
T r a n a I i . j J betwxxrn 0 and l i m i t I i . j 1. At leait for this solver. w e must enforce
such an assumption by giving each T r a n s [ i , j } an explicit upper bound that & sljghtly
less than l i m i t I i . j ] . but closeenough not k> affeet the eventual optimal solutk>n:
These values of the variables are well a way from any singularhy. with
Transli.jl/limit(i. j) being less than 0.96 in every c a i e . ( I f you change the
starting guess to be l i m i t ( i . j ] /2 ai before. you should find that the solution is the
same but the solver needs only about half as many hcraiions to find it.)
T h e immediate lesson here is that nonlinear functions can behave quite badly outsidc
the intended range o f the variables. The inoomplete graph in Figure l8-2e made this cost
funetion loofc misleadingly wvll-behaved. whereas Fjgure 18-6 shows the need for a
bound to keepthe variable a way from the singularhy.
A more general lesson is that difficulties posed by a nonlinear functk>n may lead the
solver ti> faü in a variety o f ways. When developing a nonlinear mixlel. you need to be
alert to bizarre resuhs from the solver, and you may have to do some detective worlc to
trace the problem hack ti> a ílaw in the nnxlel.
Múltiplo local op ti ma
minimize Total_Cost:
num ( i i n QR1Q. j i n DK5JT}
ratc[i .j 1 * Transli. j TO.8 / <1 - T r a n s [ i , j J / l i m i t l i . j l ) :
By raising the amount shipped to the powar 0.8. w e cause the cost funetion to be concave
at lowx^r shipment amounts and convex at higher amounts. in the manner o f Figure l8-2f.
Attempting to solve lha new nnxlel. w » again initially run into technical dilTiculties:
This time our suspicion naiurally centers upon T r a n s ( 1 , j ) A 0 . 8 , the only expression
that w e have changed in the nnxlel. A further chie is provided by the error message's r e f -
erence ti> p o w ' { 0 , 0 . 8 } , which denotes the derivaiive o f the exponential ( p o w a r ) fune-
tion at zero. When T r a n s [ i . j 1 is zero. \ht% functk>n has a well-defined value. but its
derivative with respect to the variable — the sk>pe o f the graph in Figure l 8 - 2 f — is infi-
nite. As a result the partial derivative o f the total cost with respect to any variable at zero
can not be returned to the solver: since the solver requires ali the partial derivatives for its
optimi/ation algorhhm. i t g i v e i up.
T h i i isanother variatk>n on the range vk>lation problem, and again itean be remedied
by imposing some bounds ti> keep the solution away from troublesome points. In this
case, w e m o v e the k>wer bound from zero t o a very small positive number:
W e might also m o v e the staning guess away from zero, but in this example the solver
takes care o f that automatically, since the initial values only suggest a staning point.
With the bounds adjusted. the solver nins normally and repons a solution:
W e can regard each l e - 1 0 a zero, since such a small value is negligible in com par i-
son with the reit o f the solution.
Next w e again try a staning guessat l i m i t [ i , j ] /2, in the hope o f speeding things
up. This is the result:
Not only ti the solution complete ly diíTerent but the optimal vahie is 17% l o w e r ! The
first solutk>n could not tmly have minimi/cd the objeetive over ali solutions that are fea-
sible in the constraints.
Actually both solutions can be considered correet, in the sense that each is lúcally
optimal. That is, each solution a lesscostly than any other nearby solutions. AII o f the
classical methods o f nonlinear optimization, which are the methods considered in this
chapter, are designed ti» seek a local optimum. Stancd from one specified initial guess.
these metfuxls are not guaranteed k» find a solution that is glufníUy optimal. in the sense
o f giving the best objeetive value anx>ng ali solutions that satisfy the constraints. In gen-
eral, finding a global optimum is much harder than finding a local one.
SECT ON 18.4 P T F A L L S O F WD NL NE A R F T O ^ W W N 3 409
Foittinately, there are many caies in which a local optimum is entirely satisfactory.
When the objective and constraint saiisfy certain propenies. any local optimum is also
global: the nxxlel consider ed ai the beginning o f this section is one example. where the
convexity o f the objective, together with the lincarity o f the constraints. guarantces that
the solver will find a global optimum. (Linear programming is an even more special case
with this property: t h a f s w h y in previous chapters \vc never encountcred local optima
that were not gk>hal.)
Even when there is nx>re than one local optimum. a knowlcdge o f t h e situaiion being
nnxlelcd may help you k> identify the global one. Perhaps you can dux>se an initial solu-
tion near to the global optimum. or you can add some constraints that mie out regions
known k> c\>ntain local optima.
Finally, you may be content to find a very good local optimum, even if you don't
have a guarantce that it is global. One straightfor ward approach is to try a series o f start-
ing points systematically. and take the best among the solutions. As a simple ilhistratk>n,
suppose that wxr declare the variables in our example as foi lows:
For each choice o f a l p h a w e get a dilTerent starting guess, and potentially a different
solution. I lere are some resulting objective vahies for a l p h a ranging from 0 to I:
alpha ToLal_CosL
OJO 427568.1
0.1 3667912
02 3667912
03 3667912
0A 3667912
OS 3554382
0J6 356531-5
0.7 3760*33
0.8 3670144
0.9 402795.3
1X1 3658272
The solutk>n that \ve previously found for an a l p h a o f 0.5 is still the best. but in light o f
these results w e are now more inclincd to belicve that it is a very good solution. We
might also observe that. ahhough the reporkrd objective value varies somewhai erratically
with the choice o f staning point — a feature o f nonlinear programs generally — the
second-best value o f T o t a l _ C o s t was found by setting a l p h a to 0/>. This suggests
that a closer search o f a l p h a values around 0.5 might be worthwhile.
S o m e o f the more sophisticafcrd mctluxls for gk>bal optimi/ation atkrmpt to search
through staning points in this way. but with a mi>re elaborate and systematic procedure
for deciding which starting poinfc to try next. Others treat global optimization as more o f
a c o m bina toria! problem. and apply solution methods motivatcd by those for inieger pro-
410 N O M . NE/F3 F R D G R A V S C H í f T E R 13
gramming «Chapter 20). Gk>hal optimi/ation metfuxls are still ai a relatively early stage
o f developmcnt, and are likely t o improve as experience aceumubtes, new idcasare tried,
and avai lable computing powzr further inereases.
Other pitfalls
Bibliography
Roger Flrtchcr, Pmcúcol MrihoeSsof Opúoúzflúon. John Wífcy &. Som ( N e w York. N Y . 1987). A
concwe Jíurvey o f t h e o f y jlix! mc4hods.
Philip IL G i l l WJLIICT Murray and MJJCOJV< l i Wright, Pmrical Opúnú&úun. Ácmleum: Pre»
(New Ycrk. N Y . 1981). TTnxry.aúsorithms amd predica) adviee.
J<*£c Nocvdal jmd S4cphcn J. Wrighl. Numtrical OfXimizutwn Springcr Vcvhg (Ifcncfclbcvg,
1999). A lext <«i mc4hods fer offtimizatian of smooth functions.
S E C T C N 18-4 P T F A L L S O F NONL NE A R F R 3 3 R W W N 3 411
Exercisos
1 8 - 1 . In the lost exampk- of Scrtian 18 A try some mcre stortirçg poinfc ( o see if you can finJ an
even better local lv optimal solution. What is l h e b n l sohitian you can fmd?
What could expiam thw unexpecled ou toa me? T r y the same problem an any nonlinear solver
avaiUbk- Ia you, and rep<rt t h : bch aviar thit you dbftcrve.
<b) Using a different startirçg point if nccexxMy, run your s a h e r ta c o n f i r m that the optimal dmien
skim fc* J0 metrrs o f fence an: ireleed 10 x 10.
( c ) Expcrimcnt with an aiulagaus model fordc*erminíng the dimensiansof a bax a í maximum vol-
ume that can be wrapped by piper o f a given arca.
( d ) Sal\e the « m e problem os in ( c ) , but for wrappmg a cylmder rather than a b a x .
1 8 - 3 . A íallmg abjecl o n a iunieles< plinct has been oh<er\ed la haxe approximately the follow
irçg hrichts ht at (mostly >eme seeond inlervals if.
95 87 76 66 56 47 38 26 15 6 0
A / 1 | 1CK)
Accordirçg to the l i w s o f phy sics <m this planei the heqght o f the abjecl at anv time shaukl be SÍNXTI
bythe fcrmuLi
ht =
when: aQ is the initül height ax is the initial selacity, and <i2 i* the acceleratian due Ia gravity.
But since the abservatians v e t e not made exactly, there exwU na c h o i c e o f a n % a ,, and a 2 thit will
412 NOM. NE/f3 FRDGRAVS CHífTER 13
CMKC ali o f the dati to fit this formula exactly. Imtead. we wish to estimate lhese three valurs by
d n a t i n g them soas to m i a m o s the "sum o f squixcs"
£ -(ao-fl^-Ka^)! 2 .
when: i i anJ AÍ MÜ the ofaervatxtJK from the/th enlry o f the table, anJ n is the number of observa-
tkiro. This expiem i o n m e K u r n th: error between the ideal fcrmuLi anJ the obtened behraor.
(a> Creste an A M R . model thit minimi/es the sum of squires f<r any number n of observations //
aixl h j . This model should hive three varhbles aixl an objective functkin. but no cunslrainfe.
<b) Use A M H . dita stitements to represem th: s m p b ofecrvatxim given above. and sol\e the
lexuking nonlinear program to determine the estimates of aixl <i 2 .
Traffic proctcdt in th: dinxtiun of th: amiws, enteriqg at intersection o, exumg at <L and pxssing
through b o r c o r b o t h . These dita values are gi\en f<r the ruids connecting the intersectians:
To be specific. we imagine thit the times aie in minutes, the capicities an: in cars per minute. aixJ
th: semüivities aie in minutes per (car per minute).
"Tlie foDowing A M H statcmcntscan be used lei represent netwarfcs of th rs kinJ:
aat í n t a t r a ; « t oA d intatraaotíona
<a> Whit is the shortest pith. m minutes, from th: entrance to th: exit of thrs netwcrk? Comtruct a
shutest path model. alongthe finex o f Figuie 15-7. that w r i f i » your m w r r .
<b) What is th: maxoraim traffic flow from entrance to exit m cars per minute, thit the networfc
can sustiin? Construct a maximum flow mcdel along the Imes o f 1'igun: 15 6. thit verifíes your
imwvi.
S E C T C N 18-4 P T F A L L S O F NONL NE A R F R 3 3 R W W N 3 413
(c)Question ( a ) a t a x e was concerncd only with the speed o f «ralfic. And question ( b ) only with the
volume o f traí fie. In nrabty. these q i u n t t e s MC inteire laled. A s the traffic volume on a r<ud
increases f r o m zevo, t h : time required to travei t h : road a k o inenrases.
Travei time « c i t e w x only moderalely when there an: just a few cars. but il mcix-ases very rapidfy
as t h : traffic appmaches capacity. TTius a nonlinear function is needed t o model this phenomenon.
Le« us define T l i . j J .the travei time <*i road ( i . j ) , by the folktvving constraints:
you can vcrify — l h e I n w l tinur <*i a-9c->b-9<i v. only about 7.86 minutes; some drivers woukl
tly to cut through if they weie permiticd.
To fiixJ a sloble solution using A k f f L , w hive to adJ some dita specifyirçg th: postfck- roules
íixm entrance k» e*it:
o u b j a c c t o s c a b í l i c y fr í n 1. . c t o i c a s ) :
sum ín r o u t a t m T U , } 1 >-
(fluir* { ( ! , ) ) i n r o a d f l ) T [ i , J ] • x r i , J l ) / efcraxgfc;
Show that in the stablc solution f<r a throughput o f 4.(1 a littk- more than of th: dri\ers cut
through. aixl th- average travei time increases lo about 8 2 7 minutes. Thus traffic would hive been
faster if the rend from c Io h hid ne\er been binh! ("Thrs ptrnamcnan v. known as Braess's para
dox. in honor of a íraffic anilyst who noticed thit when a ceitiin hnk was added to M i n i c f l ' * r<ud
syslem. traffic seemed to gct w o n e . )
<f) By trvirçg throughput values both grealer thin aixl l r « than J0. devekip a graph of the stablc
tnvcl time as a íufKlxm o f throtçhpul. Irxlicate. on th- graph. kw which throi^ghputs the stablc
time is greater than the optimál time.
<g) Suppose now that youha\e been hired to aiuly/e th: possiiility of apeniqg an odditional wind
irçg rend, directly from d to <L with tra\el time 5 minutes,capacsty lO.andsensitivity 1.5. Woifcing
with the models devckiped above. write an anilysis o f the oomequencex o f making this chinge. as
a funclkin ofthe throughput value.
1 8 - 5 . Rdum to th- model constrirtcd m (e> of the prevxius exercite. This exercite asks about
rcducing the number of variables by substitutirçg some out. as explaxned m Section 182.
<a> Set the option s h o w _ s L a L s to 1. and solve the problem. From the extra output you get. vcrify
thit there are 10 variables.
Next repeat the sc*sx>n with option c u b s L o u L set Io 1. Vcrify from the resuking messiges thit
some o f th- varnbles are clmüiutcd by suhstãulxin. Which of the varubk-s must these be?
<b) Rather thin sctting s u b s L o u L , you can specify thit a variable is Io be sufotituled out by plae
irçg an appropmte = phrase inits v a r dcrlaration. Mcxlify your model from <a) to u<e this feature,
aixl vcrify thit the icsulfc aiv th- ^une.
( c ) There is a lang expressiem for a v e n g e travei time thit appears twice «n thrs modcL Define a
new variable A v g Io stind for thrs expnrssion. Vcrify thit A l ü i k o substitutes thrs variable out
when you solve the rcsultirçg model andthit th- lesult K th- same as befoie.
18-6. In MotStBng <ir\S Qpúnúzflúixi wilh (USO. JuJith Ijebman. Lean l-isck»n. I.mus Scflnge
aixl AlUn Waren describe the folkiwirç; problem m designir^ a sleel tink to hold anuiumu. The
derision varubk-s are
S E C T C N 18-4 PTFALLSOF NONL NE AR F R 3 3 R W W N 3 4 1 5
It is desired ki nunmu/r th: cost of the tink. which has thrcc components: msulitktn cosi, which
depcrcJs on th: thickness; the cosi af th: sleel veweL which dependx on th: prmsuic; ai*l the cost
of a reco ixl cm atum pracew forcoaling th: animcmii. which dependx <m txith temperai ure aixJ msu
iJkin thickness. A cambinslian of engineerirçg anJ econonuc oanâdcrationc has yielded the foi
lowirçg formula*:
C, = 4CK)/n9
C r = l ( K K ) + 2 2 < / > - 14-7) 1,2
C * = 144< 80 - T)/!
<b) l>smg your preferred fcmiuLukin. determine th: parameters o f t h e least co<t tink.
( c ) Increasmg th: factor 144 «n C K causes a prop<Hk»rul inciease in the recondenuilkin CXKL Try
severa! Luger values. and describe in general lemis how the fcitil cosi menrases as a funetion af the
inmrase m this factcr.
1 8 - 7 . A sociil accountnc nutri x n a table thil shows the fkrws from each « d o r m an ecommiy
to each other sector. Ilere is simple f i w sector exampk\ with b link entries mdicatirçg flow s known
tobe zero:
UiB Hi H2 PI P2 U-Cll
UiE 15 * 130 ao 220
H1 1
H2 1
PI 15 130 20 ISO
P2 25 40 55 105
If the nialrix wcwc estimaled perfeetly, it would be balancnt üich row sum (the flow out of a see
tor) would equal the ctnesporcJmg cohimn sum (the flow in). As A practical maltcr. hawever,
t here an: se v eral d ifíi cul ti es:
Nonlinear programming can be used to adjust thrs malrix by finJmg the balinced matríx that rs
cbsest, insome sen*e. lei the one g i w n .
IxiTA sei S of «ctarx, let EjCLS be the subset of xectcrs f<r which we haw estimaled fcitil f b w s ,
aixl let Ea£SXS contiin ali sectcr juirs ( i , j) for whidi there an: knciwn esto males. The gi\en
d i a vahies are:
4 1 6 N O M . NE/F3 F R D G R A V S C H í f T E R 13
Ix*t SA£SxScortam ali raw column pairs <i, j ) fcir which there should be entries m t h : nutrix —
this includcs entries thit cortam ? instcad af a numbir. W e W M t to determine adjiMed entries A,y,
f<* each ( i , j ) c S A . thit are truly tularced:
T = y i
The cxrcles represent jaints. and the OTTOWS ate pipes. Jaints 1 aixl 2 an: saurces a f f l o w . xixi jaint
9 k a sink destmatian kw f l o w . but f l o w through a pipe can be in either directian. Awaciated
with each jaint J an amount h\ to be withdrawn finam the fkiw atthit jaint. and anelevatkin t-:
1 2 3 4 5 6 7 8 9 10
Our decisian variables are the f l a w s F , ( through the pipes iram i t o / , with a positive vahie lepre
sentirçg f l o w in the cfcrectian af the arrow, and a nccativc value rcpiesentirçg f b w in the appu<itc
directian. Naturally. f b w in must cqu&l f l o w out phis the amount withdrawn at e v e r y j:iinC cxcx-pt
f<* the saurces and the sink.
The "head k » « " af a pipe is a measure o f t h e etiergy jequned to m o se a fiou- through ü. In our
sitiutian. the head IcKxforthe pipe f r o m i to/isprap<rtk>rul to the sqiure o f t h e f b w rate:
= «'.tf if F u > a
S E C T C N 18-4 PTFALLSOF NONL NE AR F R 3 3 R W W N 3 417
where K = 4.96407 x 10 is a conwrsion constai*. and c.. is a foclcir compuled fram the diimcter,
friclkin. and length o f the pipe:
from to CH
1 3 6.36685
2 4 28.8937
3 10 28.8937
3 5 636685
3 8 433406
4 10 28.8937
4 6 28.8937
5 6 57.7874
5 7 433406
6 7 28.8937
8 4 28.8937
8 9 705 25\
For t w o jciints i jnd j at the « m e e l e v a i on, th: pfcwurc drop for f b w from i to / is e q u i l to the
hüid ICKX. Both pressure and head ICKS are measured in f c e l so thit after correcting kw chífereiKvs
inelevation betueen the joints w e ha\e the relitxm:
iTiully. w e wish tomaintain th? prcssuie at txith the sources and the sinkat 20CI f c e l
( a ) rormulate a general Abi H . model for thw sitiutkin. OIKJ put t o l h e r dita stilements kn the dita
given above.
<b) There K no objective funclkin heie, but you can still empkiy a nonlinear s o h e r to seek a feasi
bk" solution. By setting the optkin s h o w _ _ s t a t s to l . e o n f i r m thu th: number o f varábles equak
the number o f eqiutkim. s o that there aie nci "degrces o f f i e e d o m " m the solution. ( I h K does not
giuranlee thu there is just one solutkin. howrver.)
Check thit your solver findsa solution to the equations. anJ diaplay the iesuks.
Copyright C 2CKD byRohert Fourcr, Dftvkl M . G « y AIKJ B r i » W.Kcrnish.in
19
Complementarity Problems
A variety o f physical and economic phenomena are most naturally modelcd by say ing
that cenain pairs o f inequality constraints must be campiemenhuy, in the sense that at
least one must hoki with cquality. These conditions may in principie be accompanicd by
an objective ftmction, but are more c o m m o n l y used t o construct complenurniarity pru!>-
lems for which a feasible sohition t% sought. Indeed. optimi/ation may be viewxrd as a
special c a i e o f complementarity, since the standard optimality conditions for linear and
smooéi nonlinear optimi/atk>n are c o m p l e m e n u r i t y problems. Other kinds o f c o m p l e -
mentarity problems d o not arise from optimi/ation, h o w e v e r , or cannot be conveniently
f o r m u l a i e d o r solvcd ai optimi/ation problems.
T h e A M P L operator c o m p l e m e n t a permits complementarity c\>nditk>ns t o be speci-
f i e d directly in constraint decbrations. Complementarity models can thereby be for mu-
latcd in a natural w a y , and instancesof such m o d e l s are easily sent t o special solvers f o r
complementarity probleim.
T o motivate the syntax o f c o m p l e m e n t s , w e begin by describing h o w it w\>uld be
used t o model a f e w simple e c o n o m i c equilibrium problems, some eqüivalem to linear
programsand some not. W e then give a general definition o f the c o r n p l e m e n t s opera -
tor for pairs o f inequalhies and for more general " m i x e d " complementarity conditions
via double inequalities. Where approprbte in these sections, w e also comment on an
A M P L interface to the PAT1I solver for " s q u a r e " mixcd complementarity problems. In a
final sectk>n, w e describe h o w complementarity constraints are acvommodatcd in severa!
o f A M P l / s existing features, including presolve, constraint-name suffixes, and generic
synonyms for constraints.
419
420 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19
s e L PROD; A produets
s e t ACT; * activities
s u b j e c t t o Dcmand ( i i n PttDD}:
sum ( j i n ACT} i o l i . j l * L e v e l l j l >= d e m a n d [ i ] :
Figure 19-1:froduetioncocUminimizationmixlel(ecorunin.:r>cd).
bounded variables are handled though an extension to lhe concept of complementar ity.
We then describe a further extension ii> price-dependem demands thai is not motivatcd by
optimi/ation or eqüivalem to any linear program. We oonckide by brieíly describing
other complementarity models and applications.
In Section 2.4 w e observed that the form o f a diet nnxlel also applies to a nnxlel of
pnxluetion economics. The decision variables may be taken as the leveis o f prtxluction
aetivities. so that the objective is the lotai produetion cost,
where c o s t I j 1 and L e v e i I j ] are the cost per unit and the levei of activity j . The
constraints say that the totais o f the product outputs must be at least the product demands:
s u b j e c t t o Dcmarxi ( i i n PttDD}:
num ( j i n fiCT} i o l i . j l * L e v e i ( j 1 >= d e m a n d l i j :
with i o [ i . j l being the amount o f product i produced per unit of activity j , and
deatandll) being the total quantity o f product i demanded. Figures 19-1 and 19-2
show this 4 'economic" nnxlel and some daia for it.
Minimum-cost produetion leveis are easily computcd by a linear programming solver:
ampl: aolvo;
CPLttX 8 . 0 . 0 : o p t i m a l s o l u t i o n ; o b j e c t i v e 6808640.SS3
3 d u a l s i m p l e x i t e r a t i o n s <0 i n pha.se IJ
SECT CN 19.1 SOURC£SCFOOVR^VBVT/«7Y 421
ACT: cost :=
Pl 24S0 Pia 12 90
P2 1B50 P2a 37 00 P2b 2 ISO
P3 2200 P3c 2370
P4 217 0 ;
PROD: dcmand : =
AAl 70000
AC1 B0000
BC 1 90000
BC2 70000
NA2 4 00000
?i>\3 B00000 :
param i o ( Lr J :
AAl AC1 BC1 BC2 N A2 NA3 : =
Pl GO 20 10 15 93 B 2 95
Pia B 0 20 20 11B0 770
P2 B 10 15 10 94 5 440
P2a 40 40 35 10 27 B 430
P2B 15 35 15 15 11B2 315
P3 70 30 15 15 B9G 4 00
P3C 25 40 30 30 1029 370
P4 GO 20 15 10 1397 450 :
a m p l : diaplay Lavai;
L e v e i 1*1 : =
Pl 0
Pia 1555.3
P2 0
P2a 0
P2b 0
P3 147.4G5
P3c 1BB9.4
P4 0
Recai 1 ( from Scction 12.5) that there are a b o dual or marginal values — or " p r i c e s ' ' —
avsociatcd with the constraints:
s u b j e c t t o P r i Compl ( i i n PttDD} :
P r i c e [ i J >= 0 c c c n p l c m e n t s
sum ( j i n A C T } i o l i . j l * Levelljl >= domandlil;
At equilibrium prices. this total vahie can not exceed the activity's cost per unit
c o s t l j ). Moreover, there is a complementarity between this relationship and the levei
o f activity j : where cost exceeds total value the activity must be zero, or equivalently,
where the activity is positive the lotai value must equal the cost. Again this relationship
can be expressed in A M P L with the c o m p l e m e n t a operator:
s u b j e c t t o L e v Compl ( j i n A C r } :
L e v e i l j 1 >= 0 c c c n p l c m e n t s
sum ( i i n PROD} P r i c e l i J * ioli.jl <=CQStljl;
s e t PROD; A producLs
s e t ACT; A activities
param c o s t ( A C T } > 0 ; * c o s t p e r u n i t o £ each a c t i v i t y
param dcmarxi (PROD} >= 0: 4 u n i Ls o í dcmarxd f o r e a c h p r o d u c t
param i o (PROD. ACT} >= 0: 4 u n i Lc o í e a c h p r o d u c t i r e m
* 1 u n i t o£ e a c h a c t i v i t y
var Price (i i n PttOD}:
var Levei (j i n ACT} :
s u b j e c t t o P r i _ C o m p l ( i i n PttOD} :
P r i c e [ i 1 >= 0 c c m p l c m e n t s
sum ( j i n ACT} i o l i . j l * L e v e l l j l >= d e m a n d [ i J :
s u b j e c t t o Lev_Compl ( j i n A C T } :
L e v e i [ j 1 >= 0 c c m p l c m e n t s
sum ( i i n PROD} P r i c e [ i ] * i o l i . j l <= costljl:
a m p l : xsodal ocon.aod;
a m p l : data ocon.dat;
a m p l : option aolvor path;
ampl: aolvo;
PaLh v 4 . 5 : S o l u t i o n í o u n d .
7 i t e r a t i o n s ( 0 í o r c r a s h j ; 33 p i v o t s .
20 f u n e t i o n . 8 g r a d i e n t e v a l u a t i o n s .
a m p l : diaplay SUE ( j in ACT) coet[j) • Lovol[j);
s u m ( j i n A C T } c o s t l j |* L e v e i l j | = 6808640
Suppose now that w e extend our models by placing bounds on the activity leveis:
l e v e l _ s n i n l j 1 < = L e v e i I j 1 < = l e v e l _ r n a x [ j ] . The equivalence between the
optimi/ation problem and a square complementârity problem can be maintained. pro-
vided that the complementârity relationship for the activities isgenerali/cd toa " m i x e d "
form. Where an activity's cost is greater than ifc total value <per unhX the activity *s levei
must be aí its lower bound (much av befoce). Where an activity's levei is Ixtween às
bounds, its cost must equal its total value. And an activity' scost may also be less than its
total value, provided that its levei is aí its upper bound. These three rcbtk>nships are
summari/cd by another form o f t h e c o m p l e m e n t a operator:
s u b j e c t t o L e v Compl ( j i n A C T } :
l e v e l _ m i n l j | < = L e v e i l j | <= l e v e i m a x l j l c c m p l e m e n t s
c o s t l j l - sum ( i i n PROD} P r i c e l i l * i o l i . j l ;
424 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19
T h e resultsare the same as for the L P that is derived from our previous example (Figure
19-1) by adding the bounds a b o v e *> the variables.
SECTCN 19.1 SOURC£SCFOOVR^VBVT/«7Y 425
s « t PROD; 4 prodix:Ls
s e t ACT; 4 activities
param c o s L { A C T } > 0 ; 4 c o s t p e r u n i t o£ e a c h a c t i v i t y
param i o (PROD. ACT} >= 0: 4 u n i Ls o í o a c h p r o d u c t Irem
4 1 unit o £ each a c t i v i t y
s u b j e c t t o P r i _ C o m p l ( i i n PttDD} :
P r i c e [ i 1 >= 0 cccnplcments
sum ( j i n A C r } i o ( i . j | * L e v e l l j l
> = d c m z e r o l i ) - d e n u r a t e ( i l * P r i c e ( i J;
s u b j e c t t o Lev_Compl ( j i n A C T } :
L e v e i ( j 1 >= 0 cccnplcments
sum ( i i n PROD} P r i c e [ i ] * i o ( i . j | <=cost(j|:
l f complementa ri ty problcms only arosc from linear programs, they woukl be of very
limited interest. T h e idea o f an cconomic equilibrium can be gcncrali/cd. however, to
pcobleim that have no L P equivalcnts. Rather than taking the demands k> be fixed. for
example. it makcs sense k> vicw the demand for each product ai a dccrcaiing funetion o f
its price.
T h e simplestcaie fc a decreasing linear demand. which could be expressed in AMPI.
ai
ampl: aolvo;
PaLh v«J.S: S o l u t i o n £ound.
11 i t e r a t i o n s <3 í o r c r a s h j ; 11 p i v o t s .
12 £ u n c t i o n . 12 g r a d i e n t e v a l u a t i o n s .
426 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19
The halance between dcmands and priccs now tends to push down the equilibrium pro-
duetion leveis.
Because the P r i c e l i ] variables appear on both sides oi" the c o m p l e r » e n t s opera-
tor in thii nnxlel. there is no eqüivalem linear program. There does exiit an eqüivalem
nonlinear optimi/ation nnxlel. but it is not a s c a i y to derive and may be harder to solve ai
weD.
• if the left side < = or the right side > = o f the ihuMe-inequality holds with
cqualhy. then the expression isgreater than or equal toO:
• if the right side < = or the left side > = o f the double-inequality holds with
cqualhy. then the expression is leis than or equal toO:
• if neither side o f the double'inequality holds with equal ity, then the ex pirs-
sion equal s 0.
In the special case where the double-inequaLty ha* the form 0 < = body < = Infinity,
these conditions reduce tothose for complementarity o f a pair o f single inequalhies.
For completeness. the special c a i e in which the left-hand side equals the right-hand
side o f t h e double inequality may be written using one o f the forms
A M P L ' * built-in sulTixes for vahies related t o a problem and ifc solution extend t o
complementarity constraints, but with t w o colleetions o f sutllxes — o f the form
cmime. l*suf and cmime.TLsuf — corresponding t o the left and right operands o f c c r n -
p i ê r » e n t s , respectively. Thus after e c o n 2 . r > c d (Figure I 9 - 4 ) has been solved, f o r
example, can use the f o l l o w i n g d i s p l a y command t o kx>k at values associated with
the constraint L e v _ C o m p l :
a u i m e . s l a c k fc defined t o be
SECT CN 19 3 WCFK P t f ã V r T H O O W L E V B V T A R T Y OottstrfcNtS 429
Presolve
if presolve can deduce that êxpt\ is strictly positive for ali feasible points — in other
words. that it hav a positive lowzr bound — it can replace the constraint by expr2 = 0.
Similarly, in a constraint o f t h e f o r m
P r e s o l v e e l i m i n a L e s 1G c o n s L r a i n L s and 2 v a r i a b l e s .
P r e s o l v e r e s o l v e s 2 o£ 14 c c c r o l e m c n L a r i L y c o n d i L i o n s .
AdjusLed problem:
12 v a r i a b l e s , a l i linear
12 c o n s L r a i n L s , a l i l i n e a r : G2 n o n z e r o s
12 c o m p l e m e n t a r i t y c o n d i L i o n s among L h e c o n s L r a i n L s :
12 1 i n e a r . 0 n o n l i n e a r .
0 objecLives.
PaLh v 4 . S : S o l u L i o n í o u n d .
7 i L e r a L i o ns ( 1 £ o r c r a s h j ; 30 p i v o L s .
B íuncLion. B gradienL evaluaLions.
a m p l : diaplay ( i in PROD)
ampl? (aua{j in ACT) io[ i , j ) • lovol xsdn[j), daaand [i))/
: sum ( j i n A C T } i o l i . j 1 * l e v o l _ m i n l j 1 d c m a n d l i l :=
AAl G9B20 70000
AC1 45B00 B0000
BC 1 37 300 90000
BC 2 29700 70000
NA2 1BS4 920 4e*05
NA 3 B43700 Be* 05
W e see that for products NA2 and N A 3 . the total output exceeds demand even at the k>w-
est activity leveis. I lence in the constraint
s u b j e c L Lo P r i Compl ( i i n PttDD} :
P r i c e l i J >= 0 cccnplemenLs
sum ( j i n A C T } " i o l i . j l * L e v e l l j l >= domandl i l ;
Ceneric synonyms
F o r each complementarity constraint emime, the left and right arguments t o the c o m p l e -
r n e n t s operator are the ordinary constraints named ename. L and auune. R. This is c o n -
firmed by using the synonym terminology t o expand the complementarity constraint
P r i _ C o r » p l [ ' A A l ' 1 and the corresponding t w o ordinary constraints from the e x a m p l e
above:
where ixir is the name o f a differenl variable for each constraint. ( W h e r e an exprcssion
more complicated than a single variable appears on both skles o f c o m p l e r » e n t s , this
involves the intxoduction o f an auxiliary variable and an equalhy constraint defining the
variable *> equal one o f the expressions.) By using s o l e x p a n d in place o f expand,
you can see the form in which A M P L has sent a complcmentarity constraint k> the solver:
Bibliography
Ridiard W . Cottb, Jorçg Shi Pang. and Richard Is. Stone, Thr tintar Compltmtniarày Problem,
Academic Pnrw (San D i e g a C A . 1992). Anencyrlopcdic account of linear complementarity prob
I a m with a nice o\erview of how these problem* a i » .
SECT CN 19 3 w o r k p t f ã v n h o o w l e v b v t a r t y oottstrfcnts 433
Stcvcn P. D irk sc anJ Michacl C. ferris, "MCP1JB: A Colleclion af Nonlincar Mixed Compkvncn
Urity Problems." <)ptnni/ati<in Mcthids and Software 5 . - (1995) pp. 319-315. A n extensive sur
vcy o f nonlinear complementar*y. includirçg probk*m descriptions and mathcmatical formulatians.
Mídiacl C . Icrris aixl Jong Shi Parçg, "Hrçgincvring xixi liconamic Appbcatiansof Complementar
itv Problems." SI A M Review 39. 4 <1997>pp. 6<W-713. A variety of «•npk-mentirity test p rob
lems. originally written in the <iAMS mcxlchnc Unciiagc but now in manv cases translated Io
AMPl..
Excrcises
1 9 - 1 . Th: cconomics exampk- in Seclkin 19.1 used a demand funclkin thit was linear «n the
pricv. Construcl a ixinlinear dcmanJ functuBi thit has each o f the charxcleristics described below.
Define aconvspondirçg cxmpk-mentirity prabk*m. using the dati from Figuiv 19 2 as much as p«s
sitie.
tJse a solver such as PA I II to cxmpute an equilkrium solutkin. Compare this sohitian to those for
the constint dcmanJ and linear ck-uiand akcnutivcsshown in Section 19.1.
(a) For pricv i near /ero the demand rs near dem z c r o [ i 1 anJ is dccrcasinç at a rale near
d e m r a L e [ i 1. After pricv i has inenrased suhstintially. howvver. txith the danand M\d the n t e
o f decnrase o f the dcmanJ apprcuch /ero.
<b) For pricv i near /ero the dcmanJ is approximatcly constai* at d a n z c r o l i l . but as pricv i
appnuchcs d c m l i m l i 1 the demand drops quickly to /ero.
<c) IX*mand for i octuallv ris es with pricv, until it xvachrs a value d e a m a x l i l at a pricv o f
d e n v a r g [ i l . Then dcmanJ falls with pricv.
19-2. I"<* each scvnjLho in the pivvious prabk*m. cxperimvnt wieh differenl stulinc pomts for the
1x5vo 1 and P r i c c values. Determine whether there appvarsa unique cquilkrium point
1 9 - 3 . A himatri.x pw* between pbyers A anJ H is defmed by two m by n " p a y o f f " matrievs,
whase elements we denote by a-. anJ h-j. In one rounJ af the game. pbyer A his a choicv o f m
akerrutives and ptiyer H a choicv o f n jltcrnatiws. If A pbys (etiaoses) i anJ H plays then A
anJ 11 winamounts d, anJ h-^ nrspectiwly; negatiw winnings aiv interprctcd as lasses.
We can alkiw kw " m i x e d " stralegies in which A pbys i with probafaifity p;4 anJ H pbys j wiéi
pxihibility p \ Then the expecled vahie o f pbyer A's wmrangs is:
S <J«7 X P ? * if A p b y s i
/•i
2 > . / X Pt* « T B p l i y s /
im I
A " p u r ê " strategy is the special case in which each p l a w has one prohibility equil to 1 anJ the
rest cqtnl toO.
A juir af strategies is sakl to ivpxvsent a Nash rquiShrium if neiéicr p l a w can improw his
expected pajxiff by chai^ing only his own stralegy.
434 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19
(a) Show thit the rcqum.nu.iil kw a Nash cquilfcrium cqmvalem to the folktwing
campkvncfltarity like cxmditicvis:
kw ali i surh thit p* > O. A ' s cxpected retum when plaving i equils A ' * maximum
cxpected return o v e r ali pottfck- p l i y s
kw ali j such that p* > 0 . B's e í p c c t d return when playirçg j cquak B ' s maximum
eJLpcctxl return o v e r ali pottfck- p l i y s
<b) T o bui kl a complementarity problem m A M P I wtiCKC solution k a Nash cquilihríunu t h : param
eters icprcscnting t h : p a y o f f mstriccs can be defined bv t h : f o D o w i n g p a r a m decliraticim:
( d ) Test your model by opplying it to the "rock sciwors j u p e r " game in which both pliyers h i v e
t h : p a y o f f matrix
0 1 -1
-1 0 1
1 -1 o
Confirm that an c q u f l l w i u m is found where each p l a w chcKwcs betwecn ali Éirec p b y s with eqiul
pxitubilily.
( c ) S t i o w thit the game kw which buthpliycrs h i v e the p a y o f f matríx
-3 1 3 - 1
2 3 - 1 - 5
ha< several equilíbrio, at leost one of which u*es mixed strategies and one o f which u*es purê
stralegies.
Runnmg a Stahvr such AS PATll will only return one equilfcrium solution. T o find more, experi
ment with chingirçg the initial solutkin <r fixing some of the variables to 0 <r 1.
SECT C N 19 3 WCFK PtfãVrTHOOWLEVBVTARTY OottstrfcNtS 435
A - 10 3 £ - 4 6
2 9 7 5
( a ) tJ<e A sol ser such AS PATH to find A Nxsh equilkrium. V e r i f y thit it is a nu ved strategy. w i i i
A ' s protubilities being 1/2 kw Ixith standard* and H's protubililies being 3/7 and Ul kv standard*
1 jmd 2,icspec1ively.
W h y K A mixed strategy ncit appropiiile for this appliratkin?
<b) Y o u can sec what hippcns when c o m j u n v A decides <m standard 1 by wsuins the folkiwirç;
command*:
a n p l : íLx Play A [ 1] 1/
a n p l : solvo/
prafloiua, cúnfltraint CaffplÀIl] .L:
a l i v a r i a b l a s alior.inatad, tout uppar bound - -1 < 0
lixplam h o w AM H / s presolve phise could deduce thit t h : cximplemeiHarity problem his no feasi
ble solutkin in thw case.
( c ) T h r a u g i further expcrimentation. show thit é i e i e are no Mish eqinkhria kw this situitkin thit
i nv ol sv o nly pu re strates ies.
Copyright C 20<B by Robert Tourci, Dfcvid M . G « y AIKJ B r i » W.Kcrnish.in
20
Integer Linear Programs
437
438 MTtGER L NEAR F T O 3 R W S CHÉFTCR20
from the user in formulation and in choice o f options. As a result, the size o f problem
that you can solve w i l l be more limitcd for integer programs than for linear ones.
Thfc chapter first describes AMP1. dcclarations o f ordinary integer variables, and then
introducvrs the use o f /ero-one <or binary) variables for nnxleling logical conditions. A
concluding section ofTers some advice on formulating and solving integer programs
effectively.
ampl: aolvo;
M1N0S S . S : o p t i m a l s o l u t i o n í o u n d .
13 i t c r a t i o n s . o b j o c t i v e 1 1 8 . 0 S 9 4 0 3 2
a m p l : diaplay Buy;
Buy 1*1 : =
BKKK S. 36061
C1LK 2
KIS11 2
JJAM 10
MCiJ 10
MTL 10
SPG 9.3060S
TUR 2
As you can see, the MINCXS solver d*xs not handle integrality constraints. It has ignored
them and returned the same optimal value as before.
T o get the integer optimum, w e switch to a solver that dcxs accommodate intcgrality:
SECT CN20.2 Z E TO O P C V / « ABLES A f © L 0 5 CA- C O N D TONS 4 39
a m p l : diaplay Buy;
Buy l *1 :
BKKF 9
CHK 2
F1S11 2
HAM e
MCH 10
MTL 10
SPG 7
TUR 2
Comparing ihis solution to the previous one, w e see a f e w fetfures typical o f integer pro-
gramming. The minimum cost has nciea&od from $118.06 t o $ l 19.30: because integral-
ity is an addhional constraint on the values o f the variables, it can only make the objee-
tive less favor able. The amounts o f the different foods in the diet have also changed. but
in unpredictable ways. The two foods that had fractional amounts in the original opti-
mum, BEEF and SPG, have increased from 536061 to 9 and decreased from 930605 to
7, respectively: also, HAMhas dropped from the upper limit of 10 k> 8. Clearly, you can-
not always deduce the integer optimum by rounding the non-inieger optimum to the elos-
est integer values.
one variables to discourage shipments o f small amounts: the same techniques can be
adaptcd many other k>gical conditions as welL
T o provide a convenient basis for compar&on. WÊ focus on the tons shipped from
each origin to each destination. summed over ali products. The optimal values of these
total shipments are determined by a linear programming solver as follows:
a m p l : c o d o l j r u l t i .xaod;
a m p l : data jaulti.dat;
ampl: aolvo;
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
41 i t e r a t i o n s . o b j e c t i v e 199500
The quanthy 623 appears often inthis sohition, asa consequence of the multicommodity
constraints:
s u b j e c t t o M u l t i ( i i n ORIG. j i n D E S T } :
sum ( p i n PROD} T r a n s l i . j . p l <= l i m i t l i . j l :
In the data for our example. l i m i t I i . j ] is 623 for ali i and j : its six appearances in
the solution correspond to the six routes on which the muhicommodity limk constraint is
tight Other routes have positive shipments ai k>w as 100: the four instances of 0 indicate
routes that are not used.
Even though ali of the shipment amounts happen to be integers in this solution.
would be willing *> ship fractional amounts. Thus \v>í will not declare the T r a n s vari-
ables to be integer, but will instead extend the mixlel by using /ero-one integer variables.
Fixed costs
One way to discourage small shipments is to add a " f i x e d " cost for each origin-
destination route that is actually used. K>r this purpose rename the c o s t parameter
v c o s t . and declare another parameter f c o s t to represent the fixed assessmcnt for using
the route from i to j :
A M P L acceptsthis objective, but treats it merely " n o t linear'' in the sense o f Chapter
18. so that you are unlikely to get acceptable resuhs trying to minimize it.
A s a more practical ahernative, w e may associate a n e w variable U s e l i , j 3 with
each route from i to j , as foDows: U s e [ i . j ) takes the value I if
is positive, and isO other wise. Then the fixed cost associated with the route from i to j
is f c o s t l i . j l * U s e [ i . j J, a linear t e r m T o declare these n e w variables in A M P L ,
can say that they are i n t e g e r with bounds > = 0 and < = 1 : equivalcntly can use
the keyword b i n a r y :
minimize Total_Cost:
sum ( i i n ORIG. j i n DKST. p i n PROD}
vcostli.j.pl * Transli.j.pl
+ sum ( i i n ORIG. j i n DKST} f c o s t l i . j l * Useli.jl:
Since the model hai a combinatk>n o f continuous (non-integer) and integer variables. it
yields what is known ai a 4 'mixed-integer*' program.
T o complete the nuxlel. need to add constraints k> assure that T r a n s and U s e are
related in the intended way. This is the " c l e v e r " pan o f the formulation: w e simply
m o d i f y the X u l t i constraints cifcrd above so that they incorporate the U s e variables:
s u b j e c t t o Mui t i ( i i n ORIG. j i n D K S T } :
sum ( p i n PROD} T r a n s l i . j . p l <= l i m i t l i . j l * Useli.jl:
Since this total o f shipments from i to j is a sum o f nonnegative variables. h must equal
0. O n the other hand. when U s e l i . j ] is I. the constraint reduces k>
which is the multicommodity limit as before. Although there is nothing in the constraint
to directly prevent sum { p i n P R O D ) T r a n s l i . j . p ] from being 0 when U s e l i . j ]
is I, so long ai f c o s t l i . j ] is positive this combina tion can never occur in an optimal
solution. Thus U s e l i . j ] will be 1 if and only if sum { p i n P R O D ) T r a n s [ i . j . p ]
is positive, which ti what wc want The complete nuxlel is shown in Figure 20-1a.
442 NTEGERLNEARFTO3RWS O V F T C R 20
s « L ORIQ: * origins
m l DEST: * desLinaLions
s e t PttDD: 4 products
c h o c k ( p i n PROD}:
sum ( i i n O R I G } s u p p l y l i . p l = sum ( j i n DEST} demandlj.pl:
minimize ToLal_CosL:
sum ( i i n O R I G . j i n DEST. p i n PROD} v c o s L l i . j . p l * Transli.j.pl
• sum ( i i n O R I G . j i n DEST} £ c o s L ( i . j j * U s e [ i . j | :
s u b j o c L L o S u p p l y ( i i n ORIG. p i n PROD}:
sum ( j i n D ESI'} T r a n s l i . j . p l = s u p p l y l i . p j :
s u b j o c L t o Mui L i ( i i n O R I G . j i n D E S T } :
sum ( p i n PROD} T r a n s l i . j . p l <= l i m i L l i . j l * Useli.jl:
T o s h o w how this nnxlel might be solved, w e add a table o f fixed costs tothe sampkr
data < Figure 2 0 - I b ) :
If \v\r apply the same solver as before, the integraüty restrictions on the U s e variables are
ignored:
S O t O R I G í = GARY CLEV P I T T :
s o t DEST : = FRA DBT LAN WIN S1'L FRB L A F
s e t PROD : = b a n d s c o i l s p l a L e :
param v c o s t :! =
a m p l : diaplay Uaa;
U s e [ * . *1
: Clíl* FRA FRE LAF LAN STL WIN
CLEV 1 0.44 0.52 0.36 0 . G4 0.88 0.32
GARY 0 0 1 0.24 0 1 0
PITT 0.84 1 0.36 1 0.16 1 0.28
444 MTtGER L NEAR F T O 3 R W S CHÉFTCR20
As you can see. the total variable oo&t is the same a* before. and U s e assumes a variety o f
fractional vahies. This sohition tells us nothing new. and there is no simpkr way to con-
vert it into a gtxxl integer solution. An integer programming solver & cssential to get any
practical resuhs in \h't% shuation.
Switching to an appropriate solver. we find that the tnie optimum with fixed costs is
ai foliows:
a m p l : diaplay Uaaj
Use l * .
: DKT FRA FRK LAF LAN SVL WIN :=
CLKV 1 1 0 1 1 1 1
GARY 0 0 1 0 1 1 0
PlTf 1 1 1 1 0 1 0
Imposing the integer constraints has increaied the total cost from $223.501 to $229,850;
but the number of unused routes has increased. toseven. ai wv had hoped.
Zero-or-minimum restrictions
Ahhough the fixcd-cost solution uses fewer routes. there are still some on which the
amounts shipped are relatively low. As a practical matter. it may be that even the vari-
able costs are not applicable unless some minimum number of tons is shipped. Suppose.
therefore. that wxr declare a parameter m i n l o â d k> represem the minimum number of
tons that may be shipped on a route. We coukl add a constraint tosay that the shipments
on each route. summed over ali pnxlucts. must be at leait m i n l o a d :
But this would force the shipments on every route to be ai leait m i n l o a d . which is not
what we have in mind. We want the tons shipped to be either zero. or ai leait m i n l o a d .
T o say thisdirectly. we might write:
But the current version o f A M PI. does not accept logical operators in constraints.
T h e desired zero-or-minimum restrictions can be imposcd by employing the variables
U s e t i . j 1. much ai in the previous example:
s u b j e c L Lo M i n ^ S h i p ( i i n ORIG. j i n DBST} :
sum ( p i n PROD} T r a n s l i . j . p l >= m i n l o a d * Useli.jl:
Comparing this to the previous solution. we see that although there are still seven unused
routes. they are not the same ones: a substantial rearrangement o f the solution has been
necessary to mect the minimum-shipment requirement. The total cost has gone up by
about 1 . 4 % * aiesult.
Cardinaiity restrictions
Dcspite the constraints we have addcd so far. origin ? I T T still serves 6 destinaiions.
while CLEV serves 5 and GARY serves 3. W e would like to explichly add a further
rcstriction that each origin can ship to at most maxserve destinatk>ns. where
max s e r v e is a parameter to the nnxlel. This can be viewvrd ai a rcstriction on the size,
or cardinaiity, o f a certain set Indeed. it could in principie be wrhten in the form of an
AMPL constraint as follows:
Such a declaration will be rejected. however, because AMPL currently does not allow
constrainti to use sets that are defined in ter mi o f variables.
446 MTtGER L NEAR F T O 3 R W S CHÉFTCR20
s e t ORIG: 4 origins
s e t DIÍST; 4 destinations
s e t PttDD; 4 products
c h o c k ( p i n PROD}:
sum ( i i n O R I G } s u p p l y l i . p l = sum ( j i n DIÍST} demandlj.pl;
minimize Total_Cost:
sum ( i i n O R I G . j i n DIÍST. p i n PROD} v c o s t ( i . j . p l * Transli. j.pl
+ sum ( i i n O R I G . j i n DIÍST} í c o s t ( i . j l * U s e [ i . j l ;
s u b j e c t t o S u p p l y ( i i n ORIG. p i n PROD}:
sum ( j i n DKST} T r a n s l i . j . p l = s u p p l y l i . p l ;
s u b j e c t t o Max S e r v e ( i i n O R I G } :
sum ( j i n DKST} Use l i . j | < = m a x s e r v e ;
s u b j e c t t o Mui t i ( i i n O R I G . j i n D I Í S T } :
sum ( p i n PROD} T r a n s l i . j . p l <= l i m i t l i . j l * Useli.jl;
s u b j e c t t o M i n _ S h i p ( i i n ORIG. j i n DlíSr} :
sum ( p i n PttDD} T r a n s l i . j . p l >= m i n l o a d * Useli.jl;
s u b j e c t t o Max S e r v e ( i i n O R I G } :
sum ( j i n D l í S r } U s e l i . j l <= m a x s e r v e ;
s o t O R I G í = GARY CLKV P I T T :
s e t DEST : = FRA DBT LAN WIN SVL FRK LAF
s o t PROD : = b a n d s c o i l s p l a L o :
param v c o s L :=
param m i n l o a d := 37S :
param m a x s e r v e := S ;
ampl: aolvo/
CPLKX B . 0 . 0 : o p t i m a l i n t e g e r solution: objoctivc 23SG2S
392 M1P s i m p l e x i t c r a t i o n s
3G b r a n c h - a n d - b o u r x i n a d e s
448 MTtGER L NEAR F T O 3 R W S CHÉFTCR20
At the cost o f a further I . { % increase in the objective, rearrangcmcnts have been made so
that G A R Y can serve W I K , bringing the number o f destinaiions served by P I T T down to
five.
N o t i c e that this section*s three integer solutk>ns have served W I K from each o f the
three difterent origins — a gtxxl example o f h o w sohitions to integer programs can j u m p
around in response to small changes in the restrictk>ns.
" r e l a x a l i o n " that results when lhe remaining integer restrictions are dropped. You may
be able to aisist in this straiegy by reformulating the nnxlel so that the solution o f a relax-
ation will be closer to the sohition o f the aisociated integer problem. In the multicom-
nnxlity transponation nnxlel, for example. if U s e [ i . j ] is 0 then each of the individual
variables T r a n s ( i . j . p ] must be 0, while if U s e [ i . j J ii I then T r a n s [ i . j . p ]
can not be larger than either s u p p l y [ i . p ] or d e m a n d [ j . p ] . This suggests that w e
add the foilowing constraints:
Although these constraints do not rule out any previously admissible integer solutions.
they tend fc> force U s e [ i . j ] to be closer to I for any solution of the relaxaiion that uses
the route from i lo j . A s a result, the relaxation is mi>re accurate. and may help the
solver to find the optimum integer solution more quickly: this advantage may outweigh
the extra cost o f handling more constraints. Tradeoffs o f this kind are mixst ofien
observed for problems substantially larger than theexamples in thts section. however.
A s this example suggests. the choice of a formulation is much more criticai in integer
than in linear programming. For large problems. solution times can change dramatk:ally
in response lo simple rcformulstions. The effect of a reformulation can be hard Io pre-
dict. howxrver: it depends on the structure of your nnxlel and data. and on the detaik of
the strategy used by your solver. Generally you will need lo do some experimentation to
see what works best.
Y o u can also try lo help a solver by changing some of the default settings that deter-
mine how it initially processes a problem and how it searches for inieger solutions. Many
of these senings can be manipulaied from within A M P L ai explained in the separate
instructions for using particular solvers.
Finally. a solver may provide optk>ns for stopping prematurely. returning an integer
solution that ha* been deiermined to bring the objeetive value to within a small percent-
age of optimalhy. In some cases, such a solutk>n is found rebtively early in the sohition
pnxess: you may save a great deal of computation time by not insiiting that the solver g o
on to find a provably optimal integer sohition.
In summary, experimentation is usually necessary to solve integer or mixed-integer
linear programs. Your chances of succe^s are greatest if you approach the use of integer
variables with caution. and if you are willing tokeep trying alternative formulations. set-
tings and strategies until you get an acceptable result.
Bibliography
lilhs L. Johnson. Michacl M. K<KÜVV.I and üwe 11 Suhl. "Solving (V 1 Infcrgcr Progrjunmmg Prub
Icmx Armng from I.ãige Scale PUnnirçg Modek." Opcraturns Rcse-irch A3 (1985) pp. 803-S19.
A c w e studv m which prepmcrssing. refcrmulitkin. jrnd .ilgorithmic stntegies wne brought lo
büir cm th: salutkin af a diffíruk clav* af mltrger hneju programs.
450 MTtGER L NEAR F T O 3 R W S CHÉFTCR20
Alexandcr Schrij\er. Thtory tjf tintar and Inkrga- Pro^mmniin^ John W i l e y &. Sons ( N e w Y < r k .
N Y . 1986). A guide «o the fundimentils o f lhe subject. wiéi a puticulirly thcrough collectian o f
referem».
Excrcises
20-2. Rctum to the multicammo<fity transp<Blatian problem of Figures «i 1 aixJ 2 . Use appro
paste integer varâbles fc> imp<tsc each o f the restricliom described b e b w . (Treat each jurt sepa
rately: don't try to put ali the lestriclians in ane modeL) S a h e the resukmg integer p f q g n m , axxl
cammefit m general temts o n how the solution charçges AS a resuk of the lestriclians. Also solve
the conespandirçg linear program with the integrality restricliom reiixed. aixl c o n i f r e the LP sohi
t k m t o the integer one.
(a> Require the anwiunt shipped o n each origin destiiutkin link to be a múltipla o f 1CK) tons. To
accammodite thrs restriction, alktw demorei to be *itcsfied only t o the neaiest 100 — for example.
sina- demand f<* baixis at FRK is 225 tons. allow eüher 330 <* 300 tons to be shipped fc> FRK.
<b) Require each destination except SYL lo be servedby at most t w o origins.
( c ) Require the number of origin destirutkin links used Io be as small as passible. l e g l d l e » o f
CXKt
( d ) Require eachorigm thit supplies producl p t o destirutkin j to ship either nothirçg. <r at least the
lesser of d e m a n d l j . p l and 150 tans.
SECT .ON 20 3 P R A C T C A L OONS CGRATONS N NTEGER F B X R W W N3 451
2 0 - 3 . lanplqycc schcduhrçg problems ore a common source of integer programs. because it may
not makc sen se (o schcduk- a fracli<m o f a person.
(a) Sohv th: prabtan of Exercite 4-4<b) with th: requí remei* thit the variables >'ir. representas
th: numbers af crews empbjed on shift x in period i, must ali be integer. Confirm thit th: optimal
inicgcrsalulkin just "raunds up" the linear programming salutkin to the next highest integer.
<b) Sniulul v attcmpt to firel an integer sohitian for the pfdblem of lixercwe 4 w h e r e mwnfci
ries hive been atklcd to the fcrmuLukin. Compare th: difficultv of this problem to th: one in (a).
Is the optimal integer sohitian the xunc xs the rouixlcd up linear programming salutxin in this
case?
(c) Solve th: schcdubrç; problem of Figures 16-4 aixl 165 with th: nxjuirement that an integer
numftxx of emplayees be assigned to each shift. Show that this solution K better than the ane
obtáftxJ by rounding up.
(d) Suppose that the number of supervisor* lequired is 1/10 the number of emplayees. rounded «o
the ne.iest whole number. Salve the schcdulmg problem again f<r supervisor*. Does th: integer
psogrim appear Io be hirder oreasier to solve in this cose? Is the impro\ement over the rounck*d
upsalutkin mure or less pronounced?
2 0 - 4 . The socolled knapsack problem arises in many conteUs. In ás simplest form. you stirt
with a se« of abjecls. each havirçg a known weighl aixl a known value. The problem is to decide
which items to pi* into your knapsad. You want these items to hive as gicof a tolil value as p<n«
sfcle. but their weighl carnal excrcd a ceitiin presrt limit
(a) The dita kw the simple kiupsick problem cauld be written in A M P L » foik»ws:
fl*t O E J E C ? S ;
parair. walgJit ( O E J E C ? S ) > 0 ;
parasr. v a l u o { O E J B C ? S ) > 0 ;
Using these declmions, fcrmuLite an AMH. model for th: krupsxck problcm.
tJse your model to salw the krupsick problem for abjccts of th: following wvights and values,
subjecl to a weighl Imütaf 10C9:
o b j a c r. a b c d a f g h i }
«Ndgfat 55 50 <0 35 30 30 15 15 10 5
valua 1000 B00 750 700 600 550 250 200 200 150
<b) Suppose insteod that you want to fill xcvenl íckntcal knapsacks. as specified by this extra
parameter:
larmulJc an A M R model for this sitiutkin. Dan't farget to add a canstraint thit each abjecl can
onlygo into ane krupsick!
Using the dita from (aK sol\c for 2 knapsacks af weight SmÉ 50. Ilow does the sokitian diffcr
from your prevxms « i c ?
(c) Superficial ly, the precedi r^g krupsick problem resembles an assignmenl problem; we haw a
colk-clkin af objccls and a calk-clxin of knapsicks. and w wanl to make an optimal assignmenl
fram members of the fermer to members af the latter. Wh at rs the cssentul diffeience betwcen the
kinds af assignment problems described in Scclian 152. and the knapsack problem described «n
<b>?
452 MTtGER L NEAR F T O 3 R W S CHÉFTCR20
(d) Modify the fcrmuLuktn iram (a) so that il accommodilcs a volume hmit k* th: knapsack as
wellas a wx-ight fimit. Sol\e again usirçg the following volumes:
objàct a b e d a f g h i }
voluirx» 3 3 3 2 2 2 2 1 1 1
How cki the loiil «cighC NO lume axxl value of this solutkin compre to those of th- solution you
found in (a)?
(e) How can the media sek-ctk>n problem of lixercise 2(V 1 bo viewed as a knapsack problem like
th- one in (d)?
<f) Suppose thit you can pul up Io 3 of each abject m the knapsack. instead of just 1. Revise the
model of (a) Io accommodale this posskility. axxl re solve with the same dati. How does th- opé
mil sokitian charle?
<g) Review the roll cutting problem described m E x e i c i » 2-6. Gi\en a supply of wide rolls. orders
kw namrwcr rolls. axxl a collectian of cuttirçg jutlerns. we seek a cambmatian of palterns that fills
ali orders usirçg the least material.
When this probk-m is solved. th- algorithm returns a "duil value" «JiesporxJmg to each ordered
roll WKlth. It is passiblc Io intcrpn.-t the d u i l value as the s i v i n g in w i d e r o l K thit y o u might
achie\e for each extra I U J T O W roll thit you obtain; kw exampk-. a value of 0.5 kw a 50" roll woukl
inJicale that you might sive 5 wide xxtlK if youcould abtiin 10 extra 50" rolls.
It is natural to ask: Of ali the jxUlems of iurrow rolls that fit within one wideroD, which his the
gSMtcst total ( d u a l ) v a l u e ? H x p l u n h i w thrs can be regarded as a k m p s i c k prubk-m.
lx»r the problem of Hxercise - 6 ( a ) . th- wide rolls aie 110": «n the sohitian usirçg the six palterns
given. the dual values f<r the ordered widths are:
30" 0.0
40" 03
50" 1J0
55' 0.0
75' IJO
What is th- maximum value pitlem? Show thit it is not one of th- ones given. and thit ackJmg it
alkfws you Io get a betler solutkin.
2 0 - 5 . Rarall th- mukiperkid model of production that was introdu.-ed in Sectkin 4 2 . Add /ero
one variables axxl apprapriitc constraints lo the formulatuBi from Figure to impose each af the
restrictkins described bekiw. (Tnrat each part scjxiratch .) Solve with the dita af Iiguie «1-5. aixl
canfirm that the sohitian praperlv cfceys the restrictkins.
(a) Require for each prodirt pand week t , that citheT none af the produz is made that week.or at
laist 2500 tens are made.
<b) Requm: that only ane producl be made in any ane week.
(c) Require thit each producl be made in at mast two wex-ks out af any three week period. Assume
thit anly bands were nude in "week - 1 " aixl thit txith bands aixl cails wcre made m "wa-k 0 " .
Copyright O 2 K B by Robcrt Fourer, David M.Gwy and B r i » W . Kernighin
A
AMPL Reference Manual
4S3
454 A M = L F E F E F E N C C WAMJ/C AFFENDXA
aat p r o d ; Ü pro<tiotfi
O ! -
a rcl ll
not !
or
prod pro4uc t
A.2 S e t m e m b e r s
A set contains z e r o <* m o r e elemento or memhers, each of which is an a d e i e d hst of one o r
m o * componente. liach member o f a set must b e dntinet. A l i memhers must ha\e the sinie num
ber of cxmp<ments: t h * comman number k called the sct's dimemion.
A fiteral set n written as a c o m n u separated hst o f memhers. betueen braces ( and } . If the
set K one dimensional the members an: simply numeric constants <r literal strings. <r any expres-
sion* that evaliute to numbers o r strirçgs:
{t,t*l,t*2)
l x » r a multidimemioiul set. each member must be written as a parenthesi/ed comma sepiraled hst
o f the above:
The value o f a numeric member v. the result o f round ing ifc decimal represematien to a ftoatirçg*
p « n t number. Numeric members thit appear differenl but round to the same f k i J m g point num
biT. surh as 1 and 0 . 01122. are considered the « n i e .
S E C T - O N A. 4 E X F P E S S CNS 455
A.3 I n d e x i n g e x p r e s s i o n s a n d s u b s c r i p t s
Most en ti ti es in A M H . can bc defined in colk-ctkins indexed over a sei indivsduil items are
sdected by apjicixlxn^ JL hracketcd subscript to th: rume of the entity. Th: rarçe aí passible sub
scripts is inüicatcdby an indrxing txpnrxàon «n the entity's dcclaration. Reductian opentax,surh
AS num. also use indexing expressions to speeify sets o\er which aperatians are iterated.
A subscript is o list of symbohcor numeric expressions. sepiratcd by co minas xixi cnclcrsed in
squ.re bradeis, AS in s u p p l y [ i l And c o s L l j , p l k J 1, " 0 + " 1. lixch subscripting expression
must evaluite to A number cr a fitcral. Theresultirçgvalue or sequence of values must gise A mem
ber of arek-vont onedimrnsiona] or imjkidâncfisiana] indexing sei
An indexirç; expression K aconuno separated hst of sei expremiom, folkiwed opéanaOy by a
colon And A kigicol "suchthit" expn.-ssicm.All enclctscdin traces:
kdâJàKg-.
{ uxp/- tiu )
f ux(»- Uu : iáxfl/ )
ua/V -})s::
uxpj
dxM/ny-Mfti\ht/ i n ux(»
u*i»-Hu , ux(M
liurh set expression may be preceded by a dummy member and the key word i n . A dummy mem
bir fer a one dimensionAl set is an un bound nome. that is.a rume rcit currentlv defined. A dummy
member for a multidimcnsioiul set rs a oamma sepiratcd IzsC enclased in porentheses, of expres-
skins cr untxiund nomes; the list must include at least eme unhounJ name.
A dununv member introduces eme cr more dununv Índices (the unbounJ rumes m its compo
ncnts>. wherse xcoprx* cr rarçesof defmitkin. beginjust ifter the following srxpr, an mdex'sscope
runs through the lest of the indexing expression. to the end of the dccliratktn usirçg the indexirç;
expression. cr to the end of the operand thit uses the indexing expresskm. When a dununv mem
biT his one cr m o r expression ccmípcmcnK the dununv mdices in the dununv member range over
A süce of the sei i-e.. they Assume AII values fer which the dummy member is in the set.
{A) * a fiar.
{A, B) « a l i p a i r a , ema from A , ona fr<tt. E
{i i n A, J In E ) * ttu> fiJir^
(1 i n A, B) * O i * safra
fi i n A, c r i ] ) « a l i p a i r a , o n * from A , ona Zxctt. c r i ]
fi in K ( ) , * ) in D) í l from A and 1 ( i t a a l f a p a i r ) from D
fi i n A: p í i ] > 0 ) B a l i i i n A auoh tftat p r i ] i a p o s i t i v a
fi i n A , } in C í i ] : i <- J ) B Í a n d } must ba numorie
fi in K in D: i )) * ali paira w i t h i in A and in D
* (aair* v a l u a o f i ) a n d i <- J
The ciptionol : Itxpr in An indexing expression selects only the members thit satisfy the logical
expression anJ exchides the othcrs. The lexpr tj-picalh,- in\x»lves one cr more dununv indiccrs of
the indexing expressiem.
A.4 Expressions
Varkius items can be cumbmcd in AXtPt/s arithmetic and logical expiesskins. An expression
thit may not contAin w i j h l e s is denoted cexpr*nd is sometimes calk-d a "constint expression".
456 A W L F E F E F B ^ S VAWJXL AFFSNDXA
e\en éiough it may invohe dummy Índices. A logical expression. ck-noted Uxprn may not cortam
v.ri ables when * k partof a crxpr. Set expressions an: ck-noted srxpr.
Table A-1 summari/es th? arithmetic. logical aixl set operators; the type column mdi cates
whether the operator produces an arithmetic value (A k a logical value <1. K or a set value (S).
Arithmetic expressions are foraied from th: usual arithmetic operators, tiuill in funclkim. aixl
arithmetic reduetion operators like sum:
tf/V:
/mmbtf
yarkMâ
txpt a/Mf-op éxpr a/l/h-op • - l%wfl • / rrod d í v * ••
NAíi/y-t\'f uttary-op fc • -
baUÍ-lni )
í£ /«xpr than éxftr f a l a * /Jyv /
ir<}Mt}fst<\f bnktltex udMlkfã- t\t t* auir. prod tr^x rr.ín
C )
Huilt m íuiKtkim are li«ted in Table A 2.
Th: arithmetic rediKtkin operators are used in expresskiro like
out. f i í n Prod) o ^ f l t r i ] • tQkX*[l]
The scope of the intkxing expresskin extends (o the end of the expr. If th: operation v. o\er an
empty sei the resuk is the identity value f<* theoperation: 0 for num. 1 for p r o d . I n í i n i L y fcir
miix aixl - ln£ i n i Ly f<* max.
S E C T - O N A. 4 E X F P E S S CNS 457
Lqgieal exprewbffi appev w h n c a value o f " t m e " or " f a l s e " is required: in c h o c k siae
ments, the "surh t h i t " jurls af indexing expressions (falktwing lhe calcm). axxl in i f lexpr L h c n
« . e l . e e ... n p r e w b f f i . Numcric values lhal appear in any cif éiese contexts are implkritly c o a c t d
lo logical values: 0 k interpreted as false. aixl ali other numeric values as true.
Jfjpr:
/i/w
/JIJV <t.w\(\uetxpi comftast-op » < < • - - - •-<>>>«
á/j^w Jb^Af-op Itxpj logk-op fc o r | | ar*l l l
not Uxpr
M/mh// iXl UifH
mrmbtt M C In
Í/JIJV with In nsyv
uxp not within ãáxpr
Afi/jyw r.vswAvi^ r» axifitfi cr fora 1 1
C Atr^r )
The i n operalcr lesls se< membership. lis left operand is a potentul set member. i.e., an
expression or ccmma se jurai cd hsl cif exprewioiK enclased in jurendieses, with lhe number o f
expressions equal lo lhe dimension of lhe righl opevand, which must be a set expresskin. The
w i t h i n optxalcr texto whether eme set is ccmiiined m m A e r . The two set cípcranjs must hive
lhe same dimension.
The logical nrductxin operalcrs e x i s t s aixl í o r a l 1 are lhe iCciuted counterparts of o r axxl
and. When appbed over an empty set. e x i s Ls retome false and í o r a l 1 «.-turns true.
Set expressiems yield sets.
unyv:
{ / MtMÍHf f , AVMAV/... / Y )
uqu ui-op uxpr ut-op h union diZi fiyiwliff intar eroou
t\Mttímt bcikxJtcx uxp <snkím* ts u i i o n cr i n t * r
étyf . . txpr / b y I
fl<ato2 ktíUxtox mtmbtr
if láxpr than ux(» oi a a ux(n
t Máxpr )
kutnal
kltflltíté-UI
Atdtxl/tx
Components of memfaos can be artátrary ccmsiant eiprewiom. Section AJ6J describes inlervtJ/S
aixl infinile sen.
When used as híiury opcrafcirs. u n i o n and i n t e r denote lhe birury set operalkins of unian
aixl interseet km. These Key words may also be used as reductkin operators.
The . . operalcr constructs sets. The defauk b y cliuse is b y 1. In general, et . ,e2 b y ey
means lhe numbers
e, + + 2rs r, +
rcmnJed to set members. (The ixiiilkin [*J denotes lhe flcxirof .Y.thil is, the Urges! integer £ x . )
The s e t o í operalcr is a set construction operalcr: memher is either an expression cr a
comma se jurai cd hst of expressiems enckised in jurenlheses. The resultirçg set consists o f ali lhe
memhen obuined by iteratirç; over the indtxinR expression: lhe dimension of lhe resulliqg expres-
skinis the numK*r of components in member.
458 A W L F E F E F B ^ S VAWJXL AFFSNDXA
T h : bink «n arithmetic funetions are Hsled in Tabk- A-2. T h : funclkin a l i a s tikes as its
argument the xunie of a modcl entity and returns its aliax, a Ktenl value described in Scrtian A
"The funetions r o u n d ( x . n) and t r u n c ( x , n )eonvert x Io a decimal slrirçg and round <r truncale
it Io n places jitst the decimal point ( o r t o - n places beíore the decimal poinl if n < 0 ) : similarly,
p r e c i s i o n ( . r . n) jounds x t o n signifiirant decinul digits. For r o u n d and L r u n c , a missirçg n
is taken as d thus providmg the usuil rouncing <r truncatkin Io an intBgcr.
Sevevml buik xn random number gencratian funclkins are available. as bsted in Tabk- A<3. AH
are based on a uri form ranJom number generalor with a veiy kii^g period. A n initial seed n canbc
specified with the -js/i command line argument (A.23) or option r a n d n o e d . whik- - s <r
S E C T - O N A. 4 E X F P E S S CNS 459
o p L i o n r a n i i o c d ' * instruas AMPI. Co chocise xixi prinC a sced. (Jivxnc no - s argument is the
sane is specify ing - s l .
1 m n d 2 24 < Jreturnsan integer in Che rance |0, Given the same sccd an expression of
Che form í l o o r + l r a r x i 2 2 4 ( ) f n ) will yiekJ the same value <*i mcist computers when n\
aixl n me integer exprewbffi of nrasonahle magnitude. ir., \n\ < 2l~24 and |*J| < 2 ' . f<r
machines that correctly compute A bit fkiatirçg point integer products and quotients: A £ 47 f<r
mo st machines of current interest
Functions thit operate <BI sete are described «n Section A.6.
In almas t ali contexfs in a model <r command where a literal string could be used. it is also
possible to use a string exprewbn, enckised in puvntheses. Strings an: created by concatenation
and from the bink m string and regular expression functions bstcdin Table A-4.
The strirçg concateiution operatce & concalenales its arguments into a sinck: string: iC his
ptxedence bekiw ali arichmetic operators. Numeric operands are conwrtcd to full precision deci
mal strings as though by print-f formal %.g (A. 16).
i u i vav^r. s aad /
nuir* U ) oco «eu i lo ãurter. enur d vaapçaa^ leuiiu/ aãd tejibâ^ whac
>fu:c Axs >jeVJ a vabd deian al âuater
nuir.O(i) lealiᣠwhae >fuce. a/«J ittcipei a» nmeh a» possfcle cá1 a. a auav
ber. bu ifc» a«:< error
i c h a r (i) Uaiocde vake OÍfr*:6iu dxiaaa* ia -an^ i
citar (/t) va i^iefurve^uixooí dura:ca- io2tar
lanqth IÍ) feqthof MTI^ *
flU2>fitkT ( Í , « , * ) dkjeiacr vctr-tx iuf c4s slmxluç ai pcrjuco m.úk cxnnedL «c>* oi
fiprlnr. t tf, <xpribi<+) 1-raut acoccda^toíomnâ xouç f**
^ poMU.-o cá rc pAx cipre u ia i. cc O d £i< kmnd
flubu , / s , /«yx') %cb>ccae íccihe ^ a extxrrcaee of ic/vU* ciprev^o /«• ia i
qau/*,/*(>!) %cb>ccae /^/x' ícral «xecntâee% cá r ^ J i u ia i
Thrre is no miphcit con\ersion o f strings ( o numbers, but num(.t) aixl num0(.0 pciforni
cxpbcit con\ersior*s. Dolh ignore leading jmd traibrçg while spjce; num eomplains if whatremains
is not a valid number. whereas numD conveits as much as it can. returning 0 if it sees nc» numeric
ps: fix.
T h : maLch. s u h . and g s u b funclkins accept strirçgs represei* ing regular expressions as lheir
sccond wguments. AMPl- a-gular expresskins are similar ( o stindird Unix regular expresskins.
As ide from ceitain /ntlacharacltns, any fileral characler cm a *:gular expression thit matches an
occurrence of itself in éie targel string. The inetachiraclcr K a reguUr n p f t w i o n thit
matches any characler. A list of characters enckised in brackets is a regular expression thit
matches any characler in lhe Irst, and lists may be abhreviitcd: [ a - z O - 9 1 matches any kiux-rcase
Idler ordigit. A list o f chararters thit begins with the characler " and is cnckised m brackcls is a
reguUr expression thai malchcs any chmctcr m l m the list: l " 0 - 9 1 malches any nondigá. If r
is a regular expression. then v * nulches 0 or m o R occurrences o f r, r + malches 1 <r nwre occur-
rences. and r? malches 0 or 1 occurrence. "r maichcs r only if r occurs at lhe beginning of the
slring. and r $ malches r only at the end of the strirçg. Parei* hes cs are used fer groupirçg and |
means "<r**; r , | r2 malches r , or r2. The special meaning o f a inelachiraclcr can be lumed off
by precediVQ it by abacksksh.
In the Kphccmcnt piltern (thirdargument) fer suband g s u b , & staixJs fer the whale matched
slring. as does \ 0. while \ L. \2 . _ \ 9 stand for th: string matched by th: first. sccond. .... nmth
parenthesi/cd expresskin in the paltern.
Optkins ( A . 14.1) are named string vahies, some of which affccl various AMPL commndc
( A . 14 The current value of optkin apname is denoted $opnamt.
In varnble, canstraint and objecti\c declaratians. piecewise linear terms have one of the foi
lowiiç forms:
where btrakpainls is a list o f hreakpoints aixl xlopts a hst of sbpes. l:ach such list is a comma
scparaled hst of cexpr\ each optianally preceded by an indexing expression (whose seape co\ers
just the cexpry. The indexing expression must ^iccify a sei thil is manifestly ordered (see AJ6.2)I,
or it can be of the speciil form
{if Usps)
which causes the txpr Io be omitted if the Itxpr is false. IncommarxR the nwre general forms
are also alkiwed. and varúbk-s may appear in expresskins in the bíctÁpuãrts and daprx.
After the lists of skipes aixJ hreakpoints are cxfended (by indexing over an>- indexing expres
sionsX the number o f sbpes must beone nwre thin the number of breakpoint*. and the hreakpoines
must be in non decreasing numeric order. (There is no requirement on the order of the sbpes.)
AMH. inlerprets the resuk as the piecewise linear funclkin f i x ) defined as folkiws. Ixl
l^/^/i. aixl 1 á i á n - 1. denote the skipes and hreakpoints. respeclively. aixl let
SEC7CNA.6 S E T CECLAPATCNS 461
bn = -*o and bu = Then f{0>=(l arxi f<r b._, £ x £ fc^/hxs slope le.,/'<*) =
lx»r #ie ferms hiving just one argument (either a vambk- »ur <r a constai* expresskin ixpr\ the
resuk rs /<»wr) cr The form with two operands rs interpn.-<ed » / ( l i a r ) - fiexpr}. T7ns
adJs aconstintthit makesthe ivsuk vanish when the ivir equils the expr.
When piecewise linear terms appear in an otherwise linear constraint cr otjectiw, AMH. col
Iccls two <r mofe piecewise linear terms involving the sime variable infci a single term.
where namt is an alphinumeric rume that hxs not previously been assigned to an entity by a decla
rstion. aBas is optional literal indexing is an opticinil irxiexing exprembn, and tnliiy is oneof
the keywcrds
flâC
pararr.
var
are
minimiza
maximiza
cub^cr. t o
noda
In addition. se\eral other constructs are technically entity declarations. but atc described later:
these include e n v i r o n . p r o b l e m . s u í £ i x and L a b l c .
The trtky may be omitted. in which case ssub j © c L Lo is assumed. l h e body of variou* dec
Ijralkim consists of other. mostly optkinil. phrases that foDow the initial jurt. liach declaration
ends with a semico km.
Deckratxim may appear in any crder. excvpt thit each rume must be dcclued before it is used.
As with piecewisc linear terms, a special ferm of indexing expression is allowcd for variable.
constraint and objeeli declarations:
{if Ujyv)
If the kigical expression Itxpr is true. then a smiple (unsubscripted) entity results; otherwise the
entitv is excluJed from the model and subsequent altempts to lefevencc it cause an emir messige.
lx»r example. this declaration includes the variible T e s t in the model if the parameter L e s L i n g
has been gi\en a vahie greater thin 1OCI:
param rautin?;
var ivaflc f i f tiaatinq > 100) > - 0;
Ui J^AV/ÍA-.VA*:
FL%»C A-.'JVMaÜas^i MY.VAÀY,?.,, Oil/tfoMéi,^ ;
aurlkau:
dírr«an *
w i t h i n ux(»
- «A/V
d a f A U l t Itf^f
Tlie dimension of the set is eithex the constai* positive integer /i, <r the dimension cif srxpt\ <r 1 by
defauk. Th: phrase w i t h i n arxpr xqwres the set being decliied to be a subset of sxxpr. Sevcral
w i t h i n phrases may be given. Uie = phrase specifíes a vahie ícr the set: it miphes thit the set
will ncit be gi\en a value Kater in adati seclkin (A. 12.1) <r a command such as l e t ( A . 18.9). The
d e f a u l t phrase specifies a default value f<* the set. to be used if no value r< gi\en in a dita sec
tkin. Hie = aixl d e f a u l t phrases are mutually exchisi\e. If neüher is gi\x-n axxl the set is not
defined by a dJa statement lefeiences to the set duiing niodel gcneratkin cause an errar mcssige.
Íor hxsfc»rx~al nrasons. : = is current ly a xynanym kw = m decliratkins of sets and paximeters. but
this use of : = is deprecated.
The xexpriti a = d e f a u l t phsisc can be ( }, the empty set. which then his the dimension
implied by any dimen or w i t h i n phrases in the dcclaratian. <r 1 if nane ispiesent In other can
texts. ( } denotes the empty set.
Recursi\e definüxins of iixlexed sets an: allawed. so lang as the atsigned values can be com
puted in asequence thit anly lefeiences prevxtush' camputed values. Ibr example.
flat no<V»fi;
flac zxcü wittiin rcddo e r a s a nadas ;
parair. onax_iear - c a r d í n o d a o ) - 1 ; «s c a r d ( f l ) - mxr.bar o f alamantíi í n fi
flac utqp ffl í n 1. . m * x _ i t « r ) d í i r * » 2 -
íf o -- 1
tiion Ateu
âlfiâ fltapífl-1] unícn fl%»coJ {X í n nodao,
( i , X ) ín a t * p r « - l ] , < * , } ) i * <i,J);
The function c a r d operotes an any fiflte set: cardí.tr.tprj returns the number of members in
stxpr. If srxpr is an indexing exprcssion, th: fuxentheses may he amitted. For example,
c a r d ( f i i n A: x í i ] >- 4 ) )
card f i i n A: x í i ] >-
The funclkin a r i t y returns th- arity af its set argument: the function i n d e x a r i t y returns
the arity ofits argumenta indexing set.
SECTCNA.6 S E T CECLAPATCNS 463
A runicd ene dimensional set nu\ ha\e on order associoted wiéi it. Declirotkins f<r ordered
sets inchide ene of lhe ph rases
o r d a r a d / b y / r a v a r a a d / nx(» f
c i r c u l a r / by / ravaraad / f
The keyword c i r c u l a r indicotes OIJU the set is orderedond wrops aroureJ. i r . . its first member is
th? successorof âs hst. orei its list member is the predecessor of ás first.
Sets of dimension two or higher may not eurrently be o r d e r e d «circular.
If set S o r d e r e d b y T <r c i r c u l a r b y T . then set T must itself be on crdered set thit
contiins S, orei S inherits the order o f T. If the <rderin£ phrase is b y r w c r s c d T , then S still
inhaits its order fromT.bul inreverse erder.
If S is o r d e r e d or c i r c u l a r ond rei crdering b y sxxpr is specified. then one o f two cases
applies. If the members o f S aie expSátfy specified by a = [memhrr-Usâ > expression in the
model <r by a hst of members m a dito section. S odopts the ordcriiç o f this hst. If S is atficrwice
computed from an assigned cr defouk srxpr in th: model A M H . will retiin the order of monifcstly
osdered sets <expliined below) and is othcrwice fiee to pick an orbitrory («der.
Funetion* of ordered sets an: summori/ed inToble A-5.
If S is on expiesskin f<r an crdered set of n members. <r is the ^h member of & orei kix inte
ger expression, then n e x t ( f .5.AJ is member j + k Of S if 1 £ j + À £ n. orei on error other
WKCL If S is c i r c u l a r , then n e x L < « \ S . JtJ is member 1 + ( ( / + * - 1) mod n) of S. The
funetion nexLw ( n e x L wilh urajuround) is the sime as n e x t , except thot * treots oll crdered sets
as c i r c u l a r : pcov(,r.S.kJ r n e x L ( r , S . - A j . ond p r o v w t r . S . J l J r nexLw ( r . S. -JtJ.
Severa! obhrevutkins ore olkiued If A is not given. it is tikcn as 1. If txith Á orei S on: omit
tal. then f must be o dununv index in the scope o f on indexing expiesskin thit runs o\er 5. f<r
exompk- as in [ t in .
I i s e olher funetions apply to ordered sets: f i r s L (5J returns the first member of S. l a s L (5J
the lxsc member </. 5"J returns the ^h member of S. o r d ( « \ S ) arei o r d O <«\Sj the ordirul posi-
tkin of member t in S. If tr is not m & then o r d O returns 0. whereas o r d aimploins o f on error.
A$iin. o r d ( r ) = o r d ( r . S) orei o r d O ( r ) = o r d O ( r . S) if r ic m dununv index in the scope
o f on indexing expression for S.
Some sets ore monifestly ordered. such as orithmetic progressions. intervols. subsets o f ordered
sets. i f expiessioits whose L h e n ond e l s e cliuses on: b<ith crdered sets. orei set diffeiences <but
not symmetricdifferences) whose k-ft operareJs are ordered.
Torconvenicnce in specifyiqg crdered sets orei prototypes f<r imported funetkins ( A 2 2 ) , there
an: severa! kmds o f infinite sets. Itcrotirçg over infinite sets is forftâddcrv. but one con check mem
bashíp in them ond use them to speeify set <rderings. The nictst mturol infinite set is the intervol.
which may beclosed. apen, o r h i l f open orei which folkius storelord mothemoticol reititkin. There
an? intervols of real (fkiotirçg point) numbers ond of mlegers, introduced by the keywords
inLerval i n L e g e r iespecti\ely:
464 AM=L FEFEFENCC WAMJ/C AFFENDXA
pr*v(/,S,Jt) a^caterA p c ^ t t f e t e í r e a r a t a - s i a s a S
prav(^S) «IK.MÉ^-I
p»v(/) prc oot*. atenta- c*fv:c fcrt>hichf i* d u a m »a>lcA
p r a v w S , *) a^eaÉerA poaáboflMbefoc aca.to• < .V.
prevw S) ..r^^oa^ tersuo o4pravt*, S»
pravw(tf) i>i'4fujçr tcrsua c>í pravts»
firflC(S) fNKÉbffOfS
laar. (S) laaavaÉercrfS
ord(*,S) auators u S
ord ( / ) crdi^il poaáBoaotf scextoar / ia fcr » I Í A il hduaium i a d a
ordQ (/, S) crdUul pceáBoaotf j c j í o «• ia .V; 0 ií pcc%cac
ordQ (/) Himc ^ ord</ \
card(S) auaita-crfavafcciMA^S
a r í t y (S) a « > oí.V i f S * a d ^ u. foraxe » á h _SECS
irrtaxaríey (£) uri» c-ícati» A'% víc
c a r d . ar í t y . u a d í n d a x a r ír.y akoaççiycouacrdcicd *a%
ATV t \di.
l n t o r v a l i a , J>] = (a: a £ x £ b ) .
í n t u r v a i ( a , b } - (a: a < a £ b ) .
l n t a r v a l i a , b ) - (a: a £ a < b ) .
í n t a i v a l ( a , b ) - (a: a < x < b ) .
í n t a g a r [ a , b ] - (x: a £ a £ b aad a c /).
í n t a g a r ( a , b } r (x: a < x £ b aad X C /).
í n t a g a r í a , b ) r (x: a £ x < b aad X C /).
í n t a g a r ( a , b ) r (x: a < x < b aad A C J)
where a and b dcnole aitoifrary v i l h m e t c expiewkim. ai»J / denotes lhe set of integen. In func
tion prototypes (A.22) aixl éic dccUratxm phrases
í n iMêftúi
w í t h í n léttotoi
ordarad by / ravarcad /
c i r c u l a r b y / r a v a r c a d / AtHérral
aurlbau:
binary
i n caçar
flynfcollc
féb/> éxpr
ín léxpr
- êxpr
d a f a u l c éxpr
rdap:
< <- - -- !- <> > >-
C h e c k statements supplv assertkins tohelp verify thit c o m x t dali have been reador generated;
they h i v e the syntix
A.72 Infinity
fl*t A ;
parair. 12>{A) d a f a u l t Infinity;
parair. I i > f A ) d a f a u l t - I n f i n i t y ;
v a r V f i i n A ) > - U > t i ] , < - lTt>[i] ;
cumpuncnls o f V fc»r which no L b value rs gi\x*n in a dati sedion an: unhouixled helow and c o m
punents for which no Ub value is gi\en an: unbounded abo\e. One can smuLulv arrange for
optionil lower and upper constraint bounJs. O n compulers with 1E££ arithmetic (most modem
syslems) I n f i n i t y i s the It&J-.oo value.
Optum.il aüríbutes of varuble cfcclarations may be sejurated by commas; these attribules mchide
MJ/lh/M:
binary
intaqar
flynto^l íc
>- éXfif
<- éXfif
: - éXfif
d a f a u l t /xyv
- «/v
CG*fí foíUxtoXiy, <(}*UtCi)M €X(H
c o v a r ^tcUxMx.y, <tf*uiti)*i
OÍ>} bKÍfAtefC.y, ífhy<ti\t €X(H
in Í«/V
fluffix Mfrwm* txpt
usirçg the plxeholder t o COTO (see A.9 and A.10). H i e scope o f indtxinR is Iniufcd to the
phrase. and nuv have th? speciil form
fif Ujifv)
which contributes the coefficient only i í the Itxpr is true. A c o v c r phrase is equivak-nt to a
c o e i í phrase in which the rxpr is 1.
Ares are special network variables. dcclued with the keywcrd a r e instead of v a r . They may
contribute coefficients to n o d e constrainls ( A . 9 ) viioptkiml attríbule phrases of the f<rm
írocr. kíkU
to fndtxlnx^
Hiese phrases an: aiulogous in syntix to the c o e i £ phrase. except that th: fiml «rxpr is optional;
omittirç; it isthe « m e jk specifyirçg 1-
In some nonlinear models. it is convenient tc» define named values thit contríbute somehiw to
the constraints objerti\es. I x * exampk",
aat A ;
var v f A ) ;
var w f A ) ;
flufcjact to C fi in A ) : w [ i ] - wiyv;
"The Key word s u b j o c t L o in a constraint decliration may be omitted but is usiully best retained
kw clarity. The optional : = initialJtual specifies an initul guess f<r the dual varuble (Lagvaqgc
mukipher) avsociated with the constraint. A g i i n . d o í a u l t anJ : = clauses are mutually exclu •
sive. anJ d e f a u l t is kw initul values not given in a dati section. Constraint declarations must
specify a constraint in one of lhe following forms:
To emble cohinimvrse cocfficient generation f<r the constraint oneof lhe exprx may tnve a n e o f
the following ferms:
tQ_ccxr# • txpr
txpr • to_oa«r/a
Terms kw thês constraint thai are specified in a v a r decliration ( A . 8 ) an? placed al lhe kication o f
TO COTO.
Nodes are special constraints lhal may sen d flow to or receive flow from ares. Thevr declara
tions begin with lhe keywcrd n o d e instead of s u b j o c t t o . Purê transshipmenl nodes do not
have a constraint body: they must hive " f l o w m " equil to " f l o w o u t " . Other nodes an: sources or
sinks; they specify constraints in one o f lhe forms abo\e. except lhal they may not mention
t o _ COTo. and exact ly one expr must have one of lhe following forms:
SECT E0NA.9 C C N S T R A N T CECLAPATCNS 469
n o t _ í n • /jyv
nat_o\:t: • áxpr
êx(fí • nat_jin
/i/v • n a t j à u t
nat_in
nat_o\:t:
The keyword n c t - _ i n is rephced by an expression w p i w « i m lhe nei f b w inki lhe nade: the
tams contribuled la lhe nade constraint by Lo phrasm of a r e decliratxins ( A ^ y . minus lhe l e r a »
contríbuled by írccn phrases. Tlie treatment o f n e t _ o u l K m l o g o u s ; il is lhe negatne o f
noL_ in.
T h : opticiial xufix iniikiDziJjon phrases each hase lhe form
/•Y|V
' A • ifttfttii ít^At^W '
S U f C i x Mfrwm* éxpi
in which consâr\ and consâr2 consisl o f 1,2, cr 3 expie*sk»ns scpiralcd h, the opcrafcirs <=, > = <r
=. In constrx and f a w / r j fcigelher, there musi be a fcilil of two explicit mequabty opcrstORf, wiéi
= countrçg as two. A complcmentarity constraint is satisficd if txith consíri aixl conxü'2 hold axxl
at k-ast one inequility is light. i r . . satisficd as an cquility. If one of conar\ <* conxü'2 in volves
Iwo mcquabtics. then the cunslraint must hive one o f the f o r a »
In ali of these cases, lhe constraint require* lhe mequabtic* Io hold. with
tx(>/4 i O i f /a/w, -
£ 0 1 ! /A/Wj - / i f v ,
m/v, - O i f «rpr, < <a/Wj < /i/w,
cfaiüjaikfa:
maximiza /u/mt aiias^ htétxfog^ f : tx(H*uk>* f f utfflx-toliktii&ikMi f ;
m i n i m i z a ttam/ alias ^ f : tx(H*ssk>* f f sáfflx-MikM&ikMis f ;
éx-(ueískm-.
C • /Jl^Z
co_£oma
which is positive if txith aie sotisfied as stricl inequilities. 0 if the complcroenUrity constraint is
sdisfied exactly. and negati\e if at least eme of cunsir, <r conxtr2 >* viobted. For constraints o f
th: form«rxpr x < = txpr2 < = rxpry c c c n p l c m e n L s exprÁ,the . s l a c k value is
so in ali cases, the . s l a c k value is 0 if the eomplemenlarity constraint holds exactly aixl is nega
tive if one of the requisite ineqiuüties is vkiLUed.
Suffix dccliratxins introduz new suffixes. which may be assigned values m subsequent decla-
rations. l e L commands and funetion invocations (with OUT orguments. A 2 2 ) . Suffixdecliralxins
begin with the keyword s u f f i x :
472 A W L F E F E F B ^ S VAWJXL AFFSNDXA
Mffl x d* d üiaíkM*:
flUCClX KtíHV tiüas^ a n r t b M à ;
Oil/lbiái*:
binary
ín caçar
flynfcollc
>- éXfif
< - éxpr
diria km
dUéctio*'.
IX
OUT
iKtxrr
LQCJiL
At most one dbtcúan may be specified; AMPl. assumes UJOUT if no direcúan is gi\en. These
direclions an: from a solver's perspective: 1ÍJ suffix values an: input to the soher; OlTV suffíx val-
ue* an: astigned b) the sol\er; 1N3UT values an: b<ith 1ÍJ anJ OUT; anJ LOCAL values an: not
scen by the solver.
Symbolic suffixes are dechxed with the s y m b o i i c attribute; appending num to the name o f
a symbolic suffix gives the mme of an astociated numeric suffix; solvers see the astociated
numeric value. If xymsuf is a symbolic sufí"ix. optkin xymmf_table connects xymaif with
xynxuf_ num as folkiws. liich line o f $xymsiif _ t a b l e shoukJ begin with a numeric fimit value.
SECTCNA.12 S T A N D A F D DAT A F CFWAT 473
folkiuvd by a string value ondoptkinil comments. ali sejurated by whi te space. T h : numeric fimil
values must i n c n w e with each line. The string value with th: g n a t o t numeric Imiit value less
thin cr equil fci the . value is the associited strirçg value. If the . suf/ximr num
value is less than the Imút value m the first line cif $.S>VJI.UJ/"_ t a b l e . then the . synxsuf _num
value is used as the . xymsuf value.
A. 11.2 Statuses
Some solsers mainlam a ta.u.tand distmguish among btisãc aixJ various kmds o f nnnhaâc v i i <
obles and constraints. AMPL s built in symbolic suffix . s s t a t u s pemüts solvers fct return tusis
infcrmatkin Io AMPL and in a subsequent s o l v e ( A . 18.1). Io be gi\en the prcviousfy optimal
basis. which sometimes leadsto solving the upditcd problem faster.
AMPL'* drojVrcstcre status ( A . 18.6) o f constraints and its futonfix status ( A 18.7) o f varubles
is reflected in the bink xn symbohc suffu . a s t a t u s . The built m symbolic suffix . s t a t u s is
dcriwd from . a s t a t u s .md . s s t a t u s : if the variable cr constraint. ímy x. is in the current
pxiblem. x. s t a t u s = x. s s t a t u s ; otherwise x. s t a t u s = . r . a s t a t u s . A MM. assigns
x . a s t a t u s _ n u m = 0 i f . r i s in the current problem. so the rule for deternünirçg . s t a t u s is
Statements dcfmmg sets con*ist of the keywcrd s e t , the set rume. an optional : = . and the
members. A one dimensional set is most easily specified by bstmg its members. optionally sepa
rated by ccmunas. The sirçgle cr double quoles of a litexil string may be omitted if the string is
alphinumcric but does not ^lecify a number.
A n ohjtcí m a dita sectkm may be a number or acharacter string. A s m a model a chiracter
strmg may be specified by surrciurxlmg it with quoles (• or * X Since so naay strmgs appear m
d Ja. however. A M P L alkiws dita stitements lo drop the quoles around any string that ccmsists only
474 A W L F E F E F B ^ S VAWJXL AFFSNDXA
o f characters thit may occur in JL ninie or number. unless quotes an: needed Io distinguxsh a strirçg
from a number.
T h : general form o f a set dita statement is
ut-ètHa-uoHmâM-.
flat Ul-ncmt U!-S{t*€ hi-í{m< ... ;
ui-t{M< :
ui-ltmf&i.v <#< MtMbt/.iist
uhimttfitÈÊt^ mtmk*/-êMi m/mbts-iahlé ...
H i e sei-name must be th: name of an individuilly declared s e i th: subscripted name o f a set
from an indexed collection. The optkinil tempLUe has th: ferm
/•/-.vavaW.V :
( »VW ffi • ÀVrtt^ / ff!\ffi • ÍV rtt, . . . )
iV f^ffi • tirtWl
where th: number o f ítmpl-iír/m must equal the dimension o f the named set. If no template is
given. a tempUte o f ali * 's is assumed.
There arctwo ferms ofjsrt sptt\ list formal and tible fermat. The list formatof st! spte rs
KMnbxrJi/:
Mtmh/tiífM mtmbií-ii/m ...
Mrmb/t Ürm:
tihfiCi <.+>)«i ...
H i e number of ohjtcls m a mtmhtr item must match the number o f * *s in the pnxedmg tempUte.
which may not hive : as a itn\pl iitrm: the ahjea% an: substüuted kw the from left to right to
pxiduce a member thit is added to the set bemg specified. In the special case that the tempUte
contiins no * ' s . the nirmhtr-Iisi shciuld beempty. while the tempLUe itself specifies one member
tobe added.
The tible formai of stri-xpec looLs like this:
mámbâf-iablí:
(t*r) 4 ,r l-kttidtf Aw.v.V/ ...
rmt-ühél 1 1 1
ftr*.M>*l 1 1 1
/•AttftA-/:
: ob)tci otytei ...
There must be at least one / htadtr% at Icast one objrcl in each row ItiM. aixl as many l'headtr\
aixl row IchtTs as * *s and : ' s m the pnxeding tempUte. If the p r e c e d i t e m p L U e invohes any
: 'x, there must he as many : *s as l-htoderx-, otherwise if the optional < t r j appears. the initul * s
are treated as :*s. and if ( L r J does not appear. the fmal * 's an: treated as :*x. I:ach table entry
shown as ± must be either a <w a - sytnbol. I:arh - entry is igmred. while each «- entry'*
rmlahrk are substituled for the tempLUe's * • s in sequence. aixl the abjeclx in the i»htadrrs
ccnesponding to the • are substüuted kw the : 's to produee a set member.
S E C T . O N A. 12 S T A N D A F D DAT A F CFWAT 475
T o define a c<«np<iui»J set. one can hsi ali m e n b e n . Kach member is a paienthcsiod.
comma se jurai cd bsl o f componente, and successive members hase an optkinil comma betueen
them. Alternai w l y , one can describe the members of a two dimensional set by a table <r sequence
o f tibles. In such a table. the row 1 abeis aie f<r the first subscript, the cohimns for the second;
" « • " stands f o r a pair thit occurs in the set. and f<r a pair thit does not. Hiccolonintroduces
a table. anJ is mand&tcry in this contcxt. If ( L r J paxedes thccokin. the table is transposed. inler
chingirçg the roles o f lOWS anJ columns.
In general, a .coL siUemenl in volves a sequence o f 1D and 21) am L tibles. 11) tibk*s stirt with
either a new template (after which a : = is optional) or with : = ai one, m which case the prcvkius
tcmpLUc is retiined. The defauk (mitul) template is ( * . . . . . * J. thit is. as many * 's as the srt's
dimcnskin. 2D tables start with an optional new template. followcd by : <r ( L r J anJ an optional
colon. folloued by a list of column Ubeks and a : =. Templates contiining no * 's stanJ f<r them
sdses. Theeffecl of ( L r J persiste until a new template appears.
For ínJcurd sete. each componcnt set must be gi\en in a scpiratc dati statement. It rs not nec
essary to specify subset members in the same crder as in their parenl set.
There are two forms o f the siUemenl thit specifies parameter dati <r variable initial values.
The first form is anakigous lo the sei dita siUemenl:
(Kiiam-í{M< :
penam - .vw piai t KAW - Üu
pa/am-ympku*^ • kMt vaiu*-labli ...
with the acklitkin o f an optional p<v<mi <StftiuSi thit will be described bekiw. The ptimni mn* is
usually the rume o f a parameter dccbued m the modcl but may also be the name o f a variable or
constraint; the keyword v a r may be used instead of param to make the distinction clear.
The p a r a m stitcmcnTs templales have the same conlent as in the sei dati stilcmcnt. but are
given in brackets (like subscripts) rather thin parenlheses:
"The IYiiut Ua is like the previously defined mtmhtnJixl. except that it also specifies a parameter
or variable value:
íüÍM ÜU :
I Í/AW • ÀV ÍT I Í/AW • I VAI ...
iti}ttt • Av iM '
db/ta <.+>)«i ... é**ry
The objects aie substüutcd f<r *'s in the templale Io define a sei member. and the p.ramctcr or
v.riablc ínJcurd by this sei member is assigned the value associilcd with the tnüy (see below).
476 A W L F E F E F B ^ S VAWJXL AFFSNDXA
The »Vilue lahSe is bkr the jreviously defined memher iabte*except thil its IWÍÍ)* an? values ratfier
thin • - < * - :
iktaèêf.
: ok)tci ok)tei ...
twmk*/
MUl/fg
ééfàttij-symbol
The named jurameters musl ali have lhe same dimension. lf the optional sei ntw* is specified, its
membership is also defined by this statement Hach iviíwf item consists o f an ojUionil tempLue
folktuvd by a hst o f <fcjects anJ a list of values:
i aí at • Àv ít'
/tfnpJa.*^ ahya ... miry mtry ...
An milül lemplate o f ali *'s (as many as lhe common dimension of the mmed jurameters) is
atsumed. and a template remains in effect until a new one appcarx. The objects must becquil in
numbcr to lhe number of *'s «n lhe current tempLue: when subsüulcd kw the *'s m the current
tempLue. Ihey define a set member. lf a set is being defined. Ihrs member is added t o à. The
parameters inJexed by this member an? assigned lhe values associited with lhe subsequent eatrys*
which obey lhe same rufes as lhe lahle enü-y* previa usly described. Values are assigned in lhe
oaler in which lhe jurameters' names appeared al lhe beginning o f the stUemenl: the number o f
entrys must equal lhe number of mmed parameters.
A p a r a m diix statement's ojUionil d e f a u l t phrase his the form
SECT .ON A. 13 DATABftSE A C C E S S A f © TAELES 477
{Ki/um-d<f<M}/:
da f a u l t tMMhtr
Ií this phrase is presert, any p n m e t e r rumed but not cxplicitly assigned a value in the statement is
given th: valueof/iupiArr.
A dati item may be specified as " . " rather than an cxpbcil value. This is normally tikcn as a
missing value. aixl a reference Io it in the model would cause an emir m e » a g e . If there is a
d e f a u l L vahie. herweser. each nus sins value is detemuned Iram that default. A defauk vahie
may be specified eãher threiugh a defauk phrase in aparameter's decliratxin m the niexld ( A . 7 ) , o r
from an eiptiemal phrase
dafault /
thit folkiws the parameter's name in the dita statement. In the latter case. r must be a numeric
constam.
Default vahie symbols may appear in both 1D and 2D tables. The drfiiuli xymbol is i i í i a D y a
de* <. >. A stack o f defauk value symbols is maintained. with the current symbol at the top. The
d e f a u l L i ^ m stilcmcnt (which is recogni/cd only m a dati scctiem) pushes a new symbol tmfci
the stick.and rK>def a u l Lssyrn pushes a " n o symbol" irxlicator orto the stack. The statement
daíauitflym;
ICKSI one other hindler must be instilled <r l o a d e d (A.22). T h : buik in set JUWDLKRS n m »
th? current ly avaiL&ble hindlers. aixl #ie symbolic parameter h a r x i l c r _ l i b (. JJANDLBRS >
tdls which shored 12>nry eachhaixlk-r come from.
Table decliratxins have lhe form
kíhii • é* d üJOíkM*:
CABIA UHB •/MUI^ I AV.VA IW^ , | ( MWAV.\,( J//AT* :
key-sptc, dtito't{M<, dam-íp**, ... ;
ifl Oifl is one of I N . CXfT. <r XílDirr: IM means mfci AMPL, OUT means out o f AMPL. and 1W0UT
means frith. INOlTT is a^umed if in oul is not gi\en. The optional siríng»lisi gises lhe rumes o f
dn\ers. files, and driver* specific options thit are used to access exlemal dita; lhe contents depend
onthe hindler used fer lhe tible and perhaps onlhe opera* ng syslem.
The key-spec in a L a b l e declaration speeifies key cohimns thit uniquely identfv the d J a Io
be occevsed:
M-itom* at n/n
in which armw is one of < - >. or < - > ; it points in the direction that the Blfcrmation is mo\ed.
from the key cohimns to the AMPL set (by r o a d U i b l o K from the set to the cohimns (by wr i L c
L a b l c ) . <r both. dcpendmg cm inaus. liach kry-cal-spec namesa colunui m the extenul table and
ossociotes a dummy index with it. A key cal spec o f the form
bs-nam*
uses key-name f<r both purposes, and a key--cal -spec o f the form
intxiduces key name as the dummy index and doía calnan\e as the name of the column in the
extenul médium; daia cal mn* may be a name. qixiled string. or parenthesurd string exprevskin.
Kach tiaia spec rumes a dati cohimn m the externai table. In the simples! case. the extenul
nane and the AMPL rume are the same. If noC however, an externai name can be associited with
an interna] rume with the syntax
àa/a-spn:
(Kitam-Ktíftv " ÍAVAV ^ÍV-AVAW
liich daia • spec optional ly ends with one of 1ÍJ. OUT. or I N 3 U T . which overrides the defauk table
direction and indicates whether r e a d L a b l o should read the column into AMPI- (1ÍJ <r líJDirr),
and whether w r i Lo L a b l e should write the column Io the externai médium (Ol/T or IWOl/T).
Speciil syntix permits use of an indexing expie-csion Io describe one <r more columns of dita:
ktíUxtoX êXQMiA-àêSC
road c a b i a JMbu/tp.'^ •
w r i c a c a b i a /abb/wmt Mbu/fa',^ ;
í r c i u d a /J.Vvwm<-
causes the indicated file to be interpolated. Ilere. and in subsequent contexto where a fUmame
appears. if filmam* invoUcs semico kins. quites, white i f a c v . o f rein printirçg characters. it mustbe
given as a literal i r „ 'fSrnamt' cr "filrnamf. In contexts other than i n c l u d e . filmam* nua,-
also be a juxcnthesizcd string expression ( A . « U ) . i n c l u d e aimmands may be nested; they an:
recqgnized in both model and d ala nicxle. The sequences
(nadai; i n c l u í a JtUtaMM
dar.a; i n c i u d a füfxí/ms
may be abbreviated
[rodai fUt/tam*
dar. a fik*amê
levei i r . , ncsting o f d a L a aixl cccimands cxmuiLirxJs speeify 015 f i b and jLppearirçg within a
campou nd command.
SEC7CNA.1S R H J F E C T O N CF NFUT AND OUTPUT 481
A M P l mamtiins th? valurs of a variety o f opiinns thit mlkience the bchivktr o f ccmimands
axxl solsers. Optkins rescmble th- "environment variibles" of th- Windows xixi Uni» operai ng
sysleTOs: in fact AMH. inherus its mkul options from the envaonmentx of these systems. A M H .
supplies its owndcfaults formam' options,howeser. if éiey an? ixil mherited in this way.
T h : o p t i o n command provides a way to examine and chinge optkins. It has one of the
ferms
o p t i o n réctirtakm^ ;
option qfNMfftrf I *\<í}n* f f , C(mam* f t\túh* f ... / rtàbttúfí*^ ;
"Tlie first f<mi prmts ali options thit hase been chinged <r whuse defauk may he provided by
AMH.. In the sccond form. if an twilut is present. it is assigned to opnamt'. othaxvise th- value (a
character string) current ly avsociated with opmnyr is printed. A n op/xw\r is an optkin name
optionaDy preceded by an environment name ( A . 18.8) and a period. T h : option name also may be
a rume pattern. which is a rume contiinirçg one orrnore In a name paliem, a * stinds foran
artvtrary sequence. possiily empty. of mme characters. and Ihus may malch mukipk- rumes; for
ciampk-
option *col
lists ali options whose mmes contiin lhe strirçg " c o l " . Specific environment or optkin nimes
may also he given by parenlhesi/ed slring expressions.
A n trwilur is a while sjuce sejxirated sequence of one <r nwre literais, numbers. parenth-si/ed
slring expremiom, and references l o c^iticms of lhe form $opnar>k* <» imt% in which apnamr
contiins nci *'s; m general $apnamr means lhe current vahie of optkin opnamr* and $$op/xw\r
means lhe defauk vahie. L e , lh- value inherited from lh- operaling syslcm. if any. <* provided by
A M H . The quotes arouixl a fileral may be omitled if what rciiuans is a name or number. "Tlie dis
pli>ed option values an: ina format thit could be read asan o p t i o n command.
3* 3* ^WíVtüyw^
< pi*™** (íccr%)MccumiâJ»
in which fUmame n w hi\e any of lhe forms lhal can appear in d a t a axxl c o n n a n d r . commands
( A . 14 >. "Tlie file is opeix-d lhe firsl time a command specifies fúmtwur in a redirection: lhe f i m
ferm of irdò-tcúon causes the file to be o\erwritlen upon firsl being opened. while lhe seaind form
causes outpul lo be appended Io lhe currenl contcnts. "Tlie form < fúm\n\t is used only for input
from lhe r o a d command (A.17). Qnce open. fiítnamt remam s opefi until a r c s e t or unlc*s
exphcitK closed by a c i o n e command:
cloao filmam**^ ;
482 A W L F E F E F B ^ S VAWJXL AFFSNDXA
As long as ftimamt semains qpen. outyut fcrms o f rr<£irclit>n causes oulput lei be appended to dic
file's cunenl contents. A c i o s o command without a fílenimc d o « c s ali open files and pipes. A
CL a s e command may specify acomma separated IKI of fitai ames. T h : variinl
rttKwa flitnamt ;
d i a p l a y / ktcUxMx: / néènttítm^ ;
prínt / taA-jÁt* : / aifUu u à i u a i o ^ ^ ;
príntí / ktcUxMx : / fml , 4/yJll/ ;
If indrxin% is presenl, its scope exlcnds K> lhe end o f lhe command and il causes one evecutum o f
Ih: command for each member m lhe indexing set. The formal strirçg fml is Kte a p r i n L Í ftrmat
string m lheC!" programnürçg linguaje aixi isexplamcd rncre fuDy faelaw.
An is a (possibly emply. o n i n u sepiratcd) lisl of expnrssions and itera/rd-ar^Iias: on
iifjuirrf wjtJisi his one o f lhe forms
where rxpr is an artxtrary expresskin. l h e rxpr* can also invohe simple or subscripted variable.
constraint. and objective nimes: a constraint name feptrsenls lhe consIraint'scurrent duil value. A
tVisptunUa is described below.
The optkinil rrdinrcibn (A.15) causes oulput lei he sent to a File instead o f appearirçg on lhe
stuxJard oulput.
The p r i n L command prints the items in its at^Ha on one line. xcpmted by xjucex and temii
nJed by a newline: lhe sejuralcr may be charçged with (ipticm p r i n t _ s c p a r a L o r . Literais an:
qixited cwily if they woukl hive lo be qixiled in dati mode. By default numeric expresskins are
printed tc» full precision. but this can be chinged with optkin p r i n t _ p r e c i s i o n or option
p r i n t _ r o u r x t as described below.
The p r i n L Í commaixl prints the items in its <u-gfixi asdiclated by its formal string fml. k
bdia\vx kke lhe p r i n L Í functkin in C. Mosl cluracters in the formal strirçg are printed vcitutim.
Comersion specifications an: an exception. They siait with a % aixl end wiéi a formal letter. as
summari/rd in Table A 10. Between lhe % and lhe formal letter there may he any o f for left
justificatKMi: which forces asign; 0 , t o pid with leadirç; zeros: a mmmium fiekl wxllh: aperkid:
aixl a precision giving lhe maximum number of characters t o b e printed from a strirçg <r digits tobe
psnted after lhe decimal point for %í and %e <r significant digits for %g <r mmmium number o f
digits for %d. Field widths aixl pieciskins are either decimal numbers m ' , which is replaced by
lhe vahie of the next item m lhe liach conversion specificalkin consumes eme or (when * s
are mvolved) rncre items from lhe argfixl aixl formais lhe lxsi item it consumes. With %-g.a prcci
s k > n o f 0 ( % . Og <r %.g)specifies lhe xhoitextdecimal strirçg Ihil rounds lei lhe value being formal
laJ. l h e standard C escape s e q u e m » an: alforued: (alcit or KrlIX. \b «backsjuce). \ í (form
feedy. \ n (newline), \ r (carriige return). \L (hiri/xintal tib), \ v (vertical tib>, \xJ and \ x á f .
SECT .ON A. 16 PR NT N 3 AND D 3=LAY CO VMANOS 483
%u u k ^ t t d dcaaul
ufr^sed a:ul aotiboA, «» jfcrü kaáiug O
%x ufr^aaJbCAaJeaaul.iM^ atada f . IcjJl^* OX
%X i^raúdhCA*icaaul.u%ia$ A£CDEF. aéitoaf fcad^ QX
si^lechracicr
\q if»<o jpfucçrutcN t« du
when: Jdenoles a hcxadccoiul digit. and \J, and Vfafe/, when: íf denotes an octol digit for-
mal %q pnnts a string value with dita seclkin quotmg rules: fcrmal fcO alwaysquotes the string.
The .cprint_£ funclkin (A.4.2) (comais its argument list accoxling to a format slrirçg thit uses
the same convcrsion specificalions.
The d i . c p l a y command formate vario us entities in tables or lists. as apprciprutc. Its disparg
liM is similjr to an <ux5.iá f o r p r i n L o r o r i n t _ £ , except thit an item to be dispiiycd can also b e a
set expression cr the unsubscripled rume of an indexed parameter. vaiiibk-. constraint. cr set: fur-
themwre iterated ^j^ií.tf seanncit be nested, i r , éieyare restricted Io the forms
ktíUxtoX tx(n
ÍXCUAMX ( tx(nüu )
c fl\*li flplay_pri a ion preciso fcr_diíç>lay .taJ cflvdiflplay <0 * ÍUI pccrtra)
c aul i flplay_rcx:nd rc« fcr _diflplayuadcflvdiflplay ( • * r» íull prccMtt)
di£ç>layJLeol u u i n m c k % i r a 1I> table tobe drfdi>cdoúe dercâi perbae
di£ç>lay_apfl dr-p] j» .£r.olLCcauna-jc tulac*< Sdiflplay_apfla%a:ro
if > a auAtnuniliU ocdunar.iaa2I>tirada*
disç>lay_praciflicm prccrtra fer d i a p l a y axnâuad »hea $dií^lay^o\mdi%fic«auna-*:
disç>lay_round plice% fua d c c m i l fcr d i s p l a y axruruad to
d i sç> 1 ay__t r an cpofi a t r ^ p o * : tabk> dron»> - colunar. < $ d i flplay_tranchos*
displayjtfidch au Ainun I ue le^ifc fer p r i n t aaddiflplaycorauaàt
a x p » n d _ p r a c i aion prccrtra fcraxpjcid ccvruruadnhca Saxpjnd_rcA:nd r» se* aunerje
axp»nd_ro\:nd phees çu* « f c c m i l fcr a > ç a n d oxrunxfcJ to n x a d
g\ittar_widt2i vcf^â-íxü ter., ca*. colunar, for d i a p l a y oxnauad
Commands d i s p l a y xixi c c v d i . c p l a y are variints thil emit tables in a more regular for-
mal than d o e » d i s p l a y : cach line o f a latile stuls with s subscripts and ends wilh K items. ali sep
arated by commas. _ d i s p l a y and c s v d i s p l a y d i f f e r in lhe txbk: headers they e m i t The
hoidcr for _ d i s s p l a y consists o f a line stirting with . d i s p l a y arxl f o l l o w c d b y Ihree integers .s,
Jt, and n (lhe number o f tiblc lines Ihil follcnv lhe header). each precedcd b ) a sjuce. If
$ c i s v d i . c p l a y h o a d e r is 1, c s v d i . s p l a y precedes the dila values by a header line Irstrçg lhe
Á inJices and/i expressiems by rume. If $ c s v d i . c p l a y hoader O.lhisheader hne m cniiMed.
a/f.
COKyOfiêM-Hf
bcdttittx+W «m(NsWAWf
( OfgUli )
flolva nélrêctkM+t ;
ll causes A M P l to write lhe current trans Laled problem lo temporary files in cfirectory $TMPDIR
(unless lhe current o p i i u i u t i o a problem has not changed since a prevkius wr i L e conunanJ). to
invake a sal\er, anJ to attempt to read optimal primai and dual variables from lhe solver. If thrs
suoceeds, lhe optimal varúbk* values beco me availabk- for prinlmg and other uses. The optionxl
ndir*ctàon is fer lhe solver's slanJardoutput
The current value o f the . s o l v e r option determines lhe saher lhal is m\xiked. Appendirçg
•_oopt' l o $ s o l v e r gives the name af an ciptian which. if defmed with a nonempty string.
determines (by the firsl letter of lhe string)the styleof temp<rary problem files written: atherwise.
AMH. uses its generic hnury output fcroial <st>k" b ) . For example. if $ s o l v e r is s u p e r s o l ,
then $ s u p e r s o l _ o o p L , if nonempty. determines the output style. The command-fine option
• - o ? • ( A .23) shows asummary o f the currently supported ciutpul styles.
A M P l pxsses two conunanJ Hne aigunients to the solver: the siub o f lhe lemporary files. anJ
the literal slring -AMPL. AMH. expects lhe sal ser to write dual and primai variable values to file
siub. s o l . preceded by commentary that if appropriale, reporte lhe objerti\e value to
486 A W L F E F E F B ^ S VAWJXL AFFSNDXA
o p t i o n incaoar_rr^i:Xarfl 0 ;
suppre*ses this prmtirçg. M M solvers also supply a numerie relum code n o l v e _ r c n u l t_nian.
which his a ctnesporxlmg symbolic value noive. renult thit is deri\ed from
n o l v e _ r e . n u l t _ n u m aixl $ . n o l v o _ r e . n u l t _ U i b l e anakigously ( o symbolic suffix values
( A . 11.1).
By default A à f l . permutes variables aixJ constraints so sohers see the nonbncar ones firsl.
Some solsers require this. but with other solvers. occasionally it is useful to suppnrss these permu
tjíkins by settirçg option n l p e r m u t e suitjftily. It rs the sum of
1 UifX*£ttLfCOCCfrttllXw
2 io f e o u e vjrubks
4 BOfeo-aLfcctycarto.
fiolucíon /ilrtwm/ ;
Th rs causes A M H . to read primai and diul varubk- values from filtnamt* as th<nigh written by a
sol ser durirçgcxccutkinofa . n o i v o command.
w r i CA ÍAV,VYV - kí&h* ;
in which the optkirul oulopj IUlut must adhcre to th- qucitir^ ruk-s for a fiíenamt. Uouiop: UJLÍ**
is present. w r i t e sets $ o u t o p t Io oumpl \\)íut. Whetfier or not outopi wilut is present. w r i L c
th-n writes the transloted problemas $ o u t q p t dxtates: the first let ter of $ o u L q p t gi\es th- out
put style ( A . 18.1 y, arxl th- rest is used as a " s t u b " t o fonn th- rumes of the files that aie created.
Ixir example. if $outqpt is "b/tmp/dicL", th- write «nunand will creste file
/ t m p / d i e t . n l , and if $ a u x £ i l e n so diclales (A.lS.^y, auxiliiry files / t m p / d i e t . r o w ,
/ t m p / d i e t . c o l , arxl so forth. The . n o i v e command as ruk-s for initial guesses. bounds. suf
fixes, e t c , apply.
The . n o i v e arxl w r i t e commanch may cause AMPL to write auxilúry files. For the n o i v e
command. appendirçg _ a u x f i l e . n to $.nol v e r gives the name o f an option thit go\ems the aux*
ib*>- files written: fer th- w r i t e cuuaiiand, $ a u x £ i l e . n p l ^ s this role. The auxilúry fik-s
488 A W L F E F E F B ^ S VAWJXL AFFSNDXA
T a b l e A - 1 2 : Au xi b ary files.
shown in Table A - 1 2 an? written only if the governirçg option's value c o n t a m the inJicatcd i r y L-t
ter. If a I r y letlef is capitab/cd the corresponding auxiliiry file is written only if the problem is
nonlinear.
T h : ccmunand
d a i a ca KomtÜsj ;
ddetes each non\e in mmtrl'isL lestoring any pievious meanmg non\e h i d . provided no other enti-
úrs depend on/uwie. i r . . i f x r c í na/m* ( A 1 9 . 2 ) reporte no dependente.
Th: comoand
purga ;
replaces any existing dccbration of the specified entity w i l h the gi\en one. provided eilher that the
entitv h » no dependente <* that the new dcc Ural ion daes not change the riuracter o f t h e entity (its
i m d such as s o L o r p a r a m . aixJ its number of subscripts). A r o d o c l a r c can be appbcd to
stitements beginnmg with any o f t h e fo Ilow mg:
dalaca ehaeX
when: conür-or -obj- nanv is lhe possfcly subscripted rume o f a constraint <r objecti \e. The
d r o p c o m o m d instruets A M H . not to trans mil the mdicated cfltity (in w r i t e .md s o l v e com
moreis): the r c s l o r c command cancek the effect of a correq>onding d r o p c o m m n d If
contir-or -obj- nanur is not subscripted but is the rume o f an indexed collection of constraints or
objectives d r o p aixl r c s L o r e affect ali members of the collection.
Tbe o b j e c L i v e command arranges thit only the rumed objectíw is jussed to the solver.
Issmng an o b j e c L i v e command is equivak-nt to droppmg ali objectives, then xestcriqg the
n^ned objecti \r.
where Inmamr is the possfclv subscripted nimeof a vxiable. The f i x command instruas A M H .
to treat the indicated varuble (in w r i t e and s o l v e commands) as though fixed at its current
value, i r „ as a constint: the u n f i x command cancels the effect o f a ctnesponJing í i x a i m
manJ. If wimomr is not subscripted but is the rume o f an indexed collection of varubkrs. f i x arxl
un f i x affect ali members of the collection.
A n optiorul : = expr may appear befcie the temunatorçg semicolcm. in which case the expres
sionis assigned Io the vamble beirçg fixed cr un fixed as though assigned by l e L ( A 18.9).
declares a new problem arxl specifies the variables. constraints. and objcctives that are m i t Other
v.riahles appearirçg in the specified constraints ar»J objecti\es an: fixed (but can be imfixed by the
u n f i x command). The new problem becomes the current pfOblevn. Inrtulh the current problem
is I n i L i a l . The iirn\S'isl in a problem dccliratkin is a comma sejuratcd hst o f possfcly sub
soipted rumes of varúbles. constraints. and objecti \es. each optionallv preceded by indexing.
Suffix iniúüiizoiions are anakigous to tfiace in constraint decliratxirts. except thit they appear
before the colon.
The c o m o m d
probiarr. ttom/ ;
probiarr. H à i u t i k * ^ ;
prints the current problem name. Drof^restore and fix/unfix cxmimand* apply c«il>' to the cuficflt
psublem. Varabk- value*. like parameters. are global; just the rut^unfixed status of a variable
depenJs on the problem. Smülirly. the dropAestcue stitu* of a constraint depenJs on the problem
(as d i redun.-d c<r*t*>. The current problem does noi restricl the l c L c<mimand ( A . 18.9).
When a problem isdcciired. it can optionallv iqiecify an environment amociated with the prob
lem: the t-nvimn phrase has the ferm
a n v i r o n Í^MWW/
to specify that the probk*m'x «nüul environment is «vnvxwir, which must bear a suhscript if the
environment K inJeurd. Otherwi*e a new unmdexcd enviroimienl with the same name as the prob
lem K created. anJ it inherits the then ciirrentenvironmcnt (set of optkin values).
In o p L i o n command*. unatkimed (conwmtional) optkin names icfex to optkin* m thecurnrnt
envirormient and the rcitilkin tnvnanit .opnanur nrfers to %4)pn<v)\ir in environment rnvnanit. The
declaration
a n v i r o n Í^MWW/ ktdoJnx^ ;
d o" lares environment tn\v*wk- (or indexed set of environment*. if irxSrxinR is present). If there i*
noindrxin%, tnvnamt becx«iies the current environment fer the current problem.
For pfeviouxly c k c l j v d environments. the commanJ
a n v í r o n tKsmtmt ;
make* the mdicated envirormient current anJ the commanJ
a n v l r o n fndtxlnx^ : - » A-.-.VMe, ;
copies environment tnvnanur, K> «vnvumr, where rnv/xw* and rnv/xw\r, must he subscripted if
dtrlared with inSrxinR*. The initial environment i* callcd I n i L i a i .
racat ;
cau*es AMPI. to forçet ali model declarations and dita anJ to ckise ali files opened by redirection.
while retammg the current option settrçgs.
r a c a t cf>tíonc ;
cau*es A MM. to lextcae ali optkin* to their initial statc. It igmres the current $OPriOMS_l?J anJ
$OPTIONS_INOUT: the fik-s they name can be inrluJed manually. if desired.
racat data ;
cau*es A M H . to forget ali assignmcnts read in dati rnode anJ alkiws readinc dita kw a difíerent
pxiblem in*tince.
r a c a t d a t a /MW-AIW ;
cau*es AMPI. to kwgci any dita read kw the entities m nome list; «munas between names are
optkinil.
S E C T . O N A. 19 EXAW N W3 p / o c a s 491
If the fatfler f o r m mentions the current problem. it has the same e f f c c l as t h : first ferm. rc.c«t
p r o b l e m does not affecl the problem's cnvnxinmcnL
updata d a t a ;
permito ali d&ta t o be updited once in subsequent dita scctions: current values may be oxefwritten,
but no values an: disrarded.
updata d a t a AY-mt-Uss ;
chinges the value o f the possibly indexed set. parameter <r vambk- n w r t o the value o f the
expiem ion. If /*i/>k* is a s e t o r parameter. its decl.ralkin must not specify a = phrase.
The command
amigns the cones porcling suífix value. if permstted. .S<mte sufrix values an: d e m e d and carnal be
amigned: altempting Io cki so CJUSCS an e m i r memage.
The comoiand
fihOW « M M U t i + i tiètotakN*^ ;
lists ali model entities if mn\tD& is not present. Il shows each /*i/>k*'s dccUralxin if it his one. o r
else lists model emities o f t h e kind indicalcd by the firsl letlers of each namer:
T h : ccmunand x r e f shows entities thit depend directly or írxlnvclh, <m specified entities:
a>ç*and )itd*xkrtébtakm^ ;
"The ikrmltà cin assume the same forms alkiued m problem declaration*. If it is evnpty. ali non
dxippcd constraints jmd objeeli\es are expinded. The variant
shows how constraints anJ objecti\es appear to the solver. I( o más constraints and varubkrs elmu
nJed by presolve unless they are expbcitly specified m lhe iitn
B o A the e x p a n d and s o l e x p a n d commands pemüt varubkrs to appear in the ikvuBa: fcir
each. the ccmimands show the linear coefficienfc of the variable in the rebvafll (non dropped anJ.
kw s o l e x p a n d . not chmmated by presolve) constraints anJ objeclives. and indicates " «- n o n -
l i n e a r " when the vombk- also participates nonlinearly in a constraint <r objective.
The options e x p a n d p r e c i s i o n and e x p a n d r o u n d control printmg of numbers by
e x p a n d . By default they are prmted to ósignificant figures.
A M P L provides a number of generic nanies that can be used to access model entities without
using model specific names. Some of these names an: described m Table A 13; the complete cur-
rent list is on the AMPl. website.
These synonyms and sets can be used in d i s p l a y anJ other commands. They piesent the
modeler's view <before presolve). Similar automatically updated entities with __ changed to
(Le., _ c n v a r s . v a r names. _ s v a r . etc.) gi\e the solver's view. i r . , the view after presolve.
There an: exceptions, houever, due to the way complevnentirity constraints an: handled (A.9.1):
none of _ c v a r , _ s c c o n r v a m e . s n c c o n s exists.
The command
chacX;
Several commands permit «Biditicíial execution of and kioping ovei lists of AM PI. commands:
i f iixfif tJum
l f IfXfV tfcan «-m^ a l a *
for loo/Mom*^ <md
t+tfi-zzr. ifjofMfame^ ofN-wMJ* f <mdi ) opi->tkilé ;
braaX Imímom*^ ;
c c n t í n u a bofmomê^ ;
In thew statements, imd is ei th cr a singlc, possibly empty, command thai ends wilh a semicokm or
a sequence of zero <r mc«c ccmimands enckised in traces. Irxpr is a logical expression. hopncJ/«r
is an optionil loop nune (which must be unbound before the syntictic start of the loop), which
goes out o f scope after synlactic end o f the loop. If piesent. an ops while condition hxs one of the
fsrms
494 A W L F E F E F B ^ S VAWJXL AFFSNDXA
w M l a Uxpr
uncil kxpr
braaX ctouttM.lfl ;
braaX A l i ;
tomirute. respecti\ely. the current comnandr: conuiuuxl or A\\ cccnnandr. cammMlds, if any. arxl
othcrwisc acl as a q u i t conunarxJ.
I.oops arxl if then else strixlures are treasured up until syntactically complete. Hecause e l s e
cliuses are optkinil. AMH. must look ahead one token to check for their presence. A t th: outer
most levei one must thus issue a nuII commmd (just a semicokm) cr some other commarxl ordec-
l^atkin to execute an outermost " c i s e less" i í stilcmcnt. (In this record. erxl of fik* mipbesan
implicit null statement)
A semicolon is taken to appear at the end of comn—ld files that end with a compound com
maixl with opticnal finil parts mèssing:
A M P L hxs three pairs o f prompts whise text can be chaqgcd thrcii^gh option settirçgs. The
defauk scttings are:
p r c m p t l appears when a new statement is expected. and p r c m p t 2 when the prevkius input line
isnot yeta complete command (fer exampk*. if the semicolon at the endis missirç).
In dati mode. the values o f d a t a p r o m p t l arxl d a t a p r c m p t 2 an: used instead. When a
new finei is begun in the mkldle of an i í , í o r cr r e p e a L statement the vahies of c m d p r c m p t 1
arxl cnxiprompL2 are used. with U i e p k d by the approprúte commarxl rume: for example:
anpl: f o r (t in tia*) (
for {. . . ) { ? arr.pl: if t <-6
for {. . . ) { ? airç>l? th*n lot cxdn(tj 3/
if . . . tfcan ( . . . ) ? anpl: olso lot cxdn(tj r- 4/
forf. . . ) ( ? arr.pl: ) /
anpl:
SEC7CNA.21 OCWFUTATOU«- E W F O W E N T 495
It is pottthlc t o stcp through commarxJs in an A M R . script one command at a time. Singk- step
mo de is erubk-d by
option flínglo_flr.i4> * ;
where n isa positive integer: it spccifies that ií th: inseri lc\el is at niost /J. AMPL shiuld betia\e as
thii^gh c o n n a n d r . « C R mserted before each ccmunand: it shiuld read c a m m n d t from the
stuxlard mput until cr>d <r other end o f file signal (control D <«i Unix. control / <*i Windows).
Some speciil commarxJs may appear in th rs made:
The .nhel 1 command provides a tcinporary escape to th- Operating system, if such is permit-
ted. to run commands.
l h e first version runs con\n\i/\i ünr. which is contiined in a literal string. In th- sccond version,
A M H . invokes an aptTataig-system sh-lL arxl control returns fc> AMPl- when thit shell termmates.
Hcfcae invoking the shelL A M H . writes a hst of current options and therr values to th- File <if any)
nxued by optkin . n h e l l _ « n v _ £ i l c . The rume of the shell program is dc4ermined by option
SHELL.
cd ;
c d rttt* -áiit<h>r) ;
T h : q u i t command causes AMPI.Io stop withoul writing any files implied by Ç o u L q p U and
lhe e n d command causes AMPL lo bchave AS th<nigh il hxs Rached lhe end of lhe current input
file. wilhoul reveiling l o model mode. A l lhe lop levei of c o m m n d interpreta* on. either command
tomirules an AMPI.session. The comnund e x i t Á asynonym kw q u i t , b u l il can retira a sla
tus Io lhe surroundirçg environmenl:
axit tXpítÍSiiSK;
AMPI. ha< buik xn parameters lhal recard various CPU aixl elapsed limes, os sfciwn in Table
A-14. M c k ! currenl operatii^ syslems kecp separale Irack o f Iwo kinJs o f CWJ lime: xystrm lime
spenl by lhe operai ing time onbehilf o f a procew.e.g^ f<r reodinc and UTÍIÍI^S files, aixl iixtr lime
spenl by lhe procvm ilself outside of lhe operatii^ sjslem. Usually lhe syslem time K murh
smalker than lhe user time; when not. fircJmg out why not sometimes suggests ways to improve
performance. Because secing sepirate syxtem aixl user times can be helpful when performance
scems p<mr. AMPI. provides bmk xn parameters for h:ith soits of times, as well as f<r thexr sums.
AMPI. runs h:ith sohers and shell commanJs as separale processes, so il provides sepaxite parame
ters to recctó lhe times t&lcn b>- each soil of process. as well as for lhe AMPL process ilself.
A.21.5 Logging
dcclorotians read iram alher files are also copicd ( o lhe kig file, and if l o g ^ d a L a is 1, then dita
scctkin* rad from other files an: capied to the kigfik- as welL
in which mmr is the name of the funetion. and chmain-xper amount* t» a funetkin protatypc:
ckfMaírt-ifM*:
àtmühtHu
A donuúnliu i* a <pc»\-**ih empty. a n u i u sepiratcd) hst of set expressions, asterisks ( • s). ákee
tkm word* (1W. Ot/r. or IWOUT), direction word* followed by set expressions, aixl ikrmled*
domain-Las:
An iltralg&damainJisl i* eqüivalem tci one repetitkm of its dnmainlisi kw each member m the
irxS*xin% s e i and the ckimam of dummy variables appearirçg m the indtxinR extends o ser thit
donviin Ua. The direction wcvds indica*: which way informatian f b w s : into the funetkin (1ÍJ). out
o f the funetkin (CX/rK txith. with I N the defauk. In a funetkin invocstiofl, OUT arguments are
as*igned values specified by the funetion at the end of the command invokirç; the funetkin.
Omittirç; the optkinil (damainspte) in the í u n c L i o n darlaratian i* the suite as specifying
<. . . >. U i e funetkin must be invoked with at l » t <w exactly as many arguments as there are set*
in the dwuún spte (after ikrraird dmuún• /isto hive been expanded). dependi ng <«i whcther or not
the daman-spec ends with . . . . A M P L checks that each argument corresponding to a set in the
donviin ü.c he< in thit s e i A * by itself m a d/wuin Bti signifies no domain checking kw the cor-
respondi r$ arg ument
A funetkin whose return value is notof interest can he invoked with a c a l 1 commaixJ:
c a l l fMK/wnr ( a/filu );
Typt can be s y m b o l i c <* rar>dcm or txith; s y m b o l i c means the funetkin return* a literal
(string) vahie rather than a numeric value. xixi r a n d o m indica«es that the "funetkin" may rvturn
498 A W L F E F E F B ^ S VAWJXL AFFSNDXA
different vahies for t h : sime arguments. i r . . A M P l . shoukl assume that cach invocation cif the íune
tion returns a different value.
T h : cammandc
load Ukfiamti^ ;
unload UhwMri^ ;
raload UhwMri^ ;
kud. unkud.or xekud shired lliraáes (from which funetkins and tibk- hareJk-rs an: imp<rtcd): Ub
ntimrs is a o n i n u separated hst of hhrory rumes. W h e n at least one Uhnanur is mentioned in the
l o a d jrnd u n l o a d commands, $AMPLPUNC is modified to reflect the full path rumes of the cur-
xently ktaded Ikraries. The r e l o a d command first unkuds its arguments. then kiods them. This
can chinge the order of ktaded Iftirories and affect the visfcility of imported furetkins: the first
nane wins. With no arguments. l o a d kuds ali the li>raries currently «n $ A M P L P U N C ; u n l o a d
unkuds ali currently kudcdfifararies.and r c l o a d rektads them (which is useful if some htve
ba-n recompi k-d
The k r ) W0ld o i p « indicates that this is mpiprfunetian* which meons A M H . shoukl start a sep
arai; process for evaluatanc the funetion. liich time a funetion value is needed A M H . writes a line
o f argumente t o the funetion process. then reads a line contam ing the íunctu*i value fiam the pro
cess. ( O f course. this is only patsible on systems thit a l b w mui à pie processes.) A lii.vq is a
sequence o f one o r m o t e adjacent literais o r parenthesprd string expressions. which A M P L con
catenates xixi pisses to the operating system ( i r . . t o $SiJI£LL) as the description o f the process to
be mvoked. In the absence o f a / i r » ? , A M P L passes a single literal, whose value is the rume o f the
funetion. If the optiorul f o r m a L fmx is present. fmi must be a krrnat. suitable for p r i n t - f , thit
tdls A M H . how to format each hne it sends to the funetion process. If rei fhu is specified. A M H .
uses spaces lo separale the arguments it passes to the pipe funetion.
Isir example:
a n p l : dimpléy 11(2/3);
f 1 ( 2 / 3 ) - xQ.6666666666666666?
a n p l : dimpléy gl('ébc')t
ç l ( ' a 2 > e ' ) - XXaix:
pxiduce lhe slrirçg p * « e d fci lhe operatin£ syslem as lhe description o f lhe process Io be staited.
Thus for lhe four pipe functkins above. the syslem sees lhe aimmands
aw* * { p r i n t ($l*$2)/2)'
avfc ' { p r i n t f -x*fl\n-, S I ) '
avA ' { p r i n t f -XXU\n», S I ) '
eat
respecti\ely. Tunclkin c a l ilhislrales lhe optional f ornvaL fhil phnsc. If fhiJ results in a strirçg
Ihil ckies not end in A new line. A!VIM. appends A new line chiractex. If no fnü is given. oich
numeric argument isoonveited l o l h e sJurlcsi decinul siring lhatrounds lo lhe argument value.
Caution: "The hne rctumcd by A pipe funclkin must be A compk-le hne. i r . . mm< end with A
ntwlinr chiracter, and lhe pipe funclkin process must flush its buffers lo pre\enl deadkick. (Pipe
functuíis ck» ncil wcrk with most standard IJnix programs, because lhey tkin'1 flush output at lhe
end o f each hne.)
lmp<rled functuíis nuv be mvoked with c<m\vntonal functuíial notalion, AS illustraled above.
In additian. keraled arguments aie alkiued. More precisely. if f is an imp<ned funetion. an invo
catian af f has lhe form f ( a r ^ ü a ] in which ai^Ha is H for lhe p r i n L and p r i n t f commands
— a possiily emplv. « n i n u scjxiralcd list o f expresskins and
The a n u i u n d
racat funetion ;
ckises ali pipe functkins, causirçg lhem lo he restirtcd if invoked agoin. If an functkin is rumed
cxpbcitly. only thai functuii is clcised.
anpl *-? *
The inituli/jLlkin of some oplkins may be dctemiined by command line arguments. The ' - ? '
axgumcrU produces a listir^g o f lhese options anJ their cxaiuiund line cquivakmts.
Sometimes it is c<«i\xmient lo hive option settrçgs a-membeied ocrnss AMPL sesskins. UnJer
operalii^ syslcms from which AMPL can inherit cnvxronnicnl variables as described above. lhe
500 AWL FEFEFB^S VAWJXL AFFSNDXA
options 0PTI0NS_IW, 0PTl0NS_lWDirr, and OPTlONS_OUT provide one way (o tk» this. If
$0PTIC01S ?J is nonempty in the inherited environmcnt. it names a file (meant tc> conlim
o p t i o n aimmands) that AMPl- reads before processais command fine arguments or entering its
ccmmand emironment OFTIONS_INOUT is sinülar (o 0PTl0NS_IW; AMH. reads File
$0PTIC01SNOUT (if nonempty) after $0PTI0NS_XW. At the end of exeaition, if
$OPTIONS_INOUT is nonempty, AMPL writes the current option settiiçs to File
$OPTIONS_XMDUT. If nonempty, $OPTIONS_0UT is treated like $OPriOWS_INOOT at the
end of execution.
The command fine argument - v prints the \ersion of the AMH. conunanJ being used; thrs rs
also availabk- as option v e r s i o n .
The command fine option -R (recogni/ed cml>' as the first command line (ipticm and not men
tkined «n the - ? bstmg of options) puts AMH. into a restricled "ser\er mode." in which it declines
to execute cd anJ s h e l 1 cxmimands. fcvbids changes to options TMPOIK, anml i n c l ude. anJ
PATH (<r the search pith for the operating system being used). disallows pipe fuiKtkins. anJ
restricts names in o p L i o n . s o l v e r anJ fik- nxfcnxlians to be alphanumeric (so they can only
write to the current dkectory, which. <m Unix systevnS at least, canncit be changed). By mvoking
AMH- iram ashell script that suitiblv adjusts current direclory anJ enviranmcnl variables befcae it
invofc.es ampl -R. one can control the directcvy m which AàtPL operates and the initial entrem
ment thit itsces.
On systems where imported funetion Ubraries can be used. the command line option - i l i h x
specifies Kbraries of imported funetians ( A 2 2 ) and tibk- hanJk-rs (A.13) that AMH- sfciuld leud
initjJh . If -i/ib.sckics ncitappear. AMH- assumes -i$AMPLl'LMC. Here Hhs isa string. perhaps
extenJing over se\eral lines. with the name of one hhrary <r dinxtorv per line. For a direct<rv,
AMH- kxiks for Ifcrarv «ampl f une. d l l in that dinxlory. If Hbx is empty and «anrol lune. d l 1
appears in the current directcrv. AXtH. kiads « a m p l f u n c . d l l initially. If hhrar\
ampl L a b l . d l l is mstalled in what the operating system considers to be a standard placv. AMH.
also Cries to kiad this Ifcrarv. which can provide "standird" datibase handlers and funetians.
Copyright O 2003 by R<*>crt Four», DavidM. Oay and Hrian W. Kernighin
Index
.. str arithmetic progressâon a c o s h function 113,458
; str acmicalan stUcment tenmrutor actise set methods 279,486
' . . . ' .«vqiKites activity model 43
« < jMverroffmewag» adverti sirç;model 21,450
/*--.*/ oommcnt 10.453 aggregrted model 55,88
* cxponentiation 111, 456 Ahuja, RavinJra K. 347
- ín sd djjutihk 156-157. 475 airlinecrew schedulmg 362
>, » output xedircction 220,239,251,273, Alatone. Aiime 20
481 algebraic modeling language xvü.xxi
: = at tribute 131,398.466.468 a l i a s funclkin 458
= attributc <J£W>defined variables ampl
= attributc 74, 118- 12a 211,462,465 ccmmand line 203, 499
$ column rume abbreviation 230 da La prompt 144
~ column name operator 177, 184-185, 188. ampl : prompt 5, 165,204,485
190,478 ampl ? prompt 165, 204,485
- ? command fins argument 499-500 A M PI. web jug e str w ww. ampl ecm
c.. .> d Mm specificatkm 196-197, 479 ampl _ i n c l ude optkin 479
defauk symbol 120, 153, 156-157, 228. amp 1_ L ime parameter 251, 496
477 AMPLKUNC Opéan 498,500
{ > , empty set 74,146, 16Z 26Z 264, 341, and optxatcr 114,456
456-457,462 are
* m o p L i o n command 205,481 declaraticn 334-311,353,467
< input xedixcction 163,165,481,485 kiss along 326
« . . . » , piecewise linear expression 367, argu ment str co mmand h ne argu ment
3€0,376, 38(K-38Z 460 arithmetic
% p r i n t £ convcrsion characler 239, 482 expression 61, 76, 111-114,456
- > readAvritc status 189, 193,478 functions. tible of 113,458
< - nradAvrite status 175, 177,182, 193 kigical set operators, table of 456
< - > sradAvritesMut 193,478 operators 456
- stanJard mput filename 165, 283. 485, 495 operators. tible of 112
Sc string concatenstion operator 27X1,459 progression 59,75,457
: = versus = initial values 21 1 xeduction operators 456
to logical con\ersk»n 123,457
a b e fcinrtion 113,140,3»,458 a r i L y function 462. 464
Access ditahxse 1TO, 174-175, 178. 19Z 194 Asonofsky, JuliusS. 20
Access filenune extension. .mdb 199-200 arrav stranc dimenskirul sei jurameter
AciermaraTs function 126 ASCII filerume extension, . Lab 201, 477
a c o s function 113, 458 ASCI 1 set 87,461
S01
502 NDEX
Drud. A m e u i e x p a n d _ r o u n d 481
. d u a l w d i u l value i i x p o non L i a i fun e t cm 459
dual exponcntution * » 111,456
value 17. 22.4a 66-67. 161 243-245, expnrstion
259.262. 266. 47a 482 anthmeO: 61.76.111-114,456
variable 398 astignabk- 185
variables 162.243,468,472,4X5 constar* 455.457,461
variables. mitul values of 185, 468. 4 7 1 mdexmg 9,79-82,99-10(1 l i a 138,455
477,486 linear 132-131,139,383
d u a l _ l n i t i a l g u o z z c r . option 486 kípcal 8 a 99, 114-116,455,457
dummv index 31, 47, 79,92. 94-95, 99, 138. meticharaclers. regular 460
181. 188, 190-191. 197, 455, 463 nonlmear 114. 133. 40<V-403
scope of 47,321 regular 273,460
Dutta, (joutam 20 sei 455,457
Dutton. John M . 2CI simplificationof 46. 13a 134. 139
stnng 194, 197,273,459
expies*km < < . . . » , piecewise Imcar 367,
KBCDIC set 87. 464 369, 376. 38(V-381 460
cconomic
arulyst* 42,415
equilftirium model 419,422 l aftiaa Tibur 20
e o x i t o p t k i n 252 farto rial 126
eâher/ar constraint 59 feasibility tolerance 281
limlm. Cjrace R. xxi fcasiblc solutkim 4,35
empty l e r m , MichaelC. 433
key specifícatkin 182 Iibonacci numbers 126
sei. indexiiç over 82.146 file inelmxin ser m o d e l . d a t a . i n c l u d e ,
strmg 205,234,252,272 cccnmands
tible entry 173, 187 file output ser output redirectum
cntfáy set ( } 74,146,162,262,261, 341, file, temperarv 485
456-457,462 file
end effect 67, 379 b l e n d . m o d 38
e n d aimmand 204. 496 c u t 2 . m o d 313
c n v i r o n command 490 c u t . d a t 309
environmcnt c u t . m o d 306
<$>«ions 490 d i e t 2 . d a t 34
variables 205,481 d i e t . d a t 33
variables. table of 484 d i e t . n o d 32
environmcnt. I n i L i a i 316.490 d i e t u . d a t 82
env nx» nmen t*. ninurd 316-317 d i e t u . m o d 78
cquahty corotraint 21, 30, 130 e c o n 2 .mod 421
etfuüfcrium stress model 388 e c o n . d a t 421
links on. Warren 39 e c o r m i n . m o d 420
e m » mestages 1183,85,94.116.119,146, e c o n . m o d 423
160,207,211, 224, 2 5 1 338 e c o n n l . m o d 425
\ escape s e q u e r v e s . p r i n t í 482 í e n c e .mod 411
cvaluatkm. order o f 100. 111. 131 467, 473 i o c o l l . m o â 356
lixcel ^readsheet 174,176. 196 i o c o l 2 . o o d 358
lixcel filename c U c r n u a . x i s 199-200 i o r o w .mod 355
e x i s L s cípcrafc.r 115.456-157 m i r m a x . m o d 381
«ix i t ccmunand 496 m u l t i c . mod 103
ctxp fcinctkin 113,458 m u l t i . d a t 58
exparxd ccmunand 13,247-248.492 m u l t i .mod 57
e x p a n d p r e c i s i o n option 481 m u l U n i p l . d a t 443
506 NDEX