You are on page 1of 528

AMPL

A Modeling Language

for Mathematical Programming

Second Edition
AMPL
A Modeling Language

for Mathematical Programming

Second Edition

Rohcrt Fourer

Northwestern Univeisity

D a vi d M . G a y

A M P L Optimizatia) L L C

Brian VV. Kernighan

Princcton University

DUXBURY

THOMSON

AU%traiu • CJLIUÜA • M a i c o • Singiparc • Sfuin • Urnfcrd KIF^gdim • UnàedSUIcx


Th rs book was lypcse* ( g r a p | p i c | L h l | o q n | L r o í £ -mtxn) m Times xixi Còurier by Oic
aulhcirx.

Copyaght C» 2003 by Robcrt Ixjurcr, David M . G a y and Hmn Kcmishin.

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:

Robert K>urer received ht% P h D . in operations research f r o m Stanford University in


1980, and is an active researcher in fiuthemarical programming and m o d e l h g language
devign. l i e j o i n e d the IXrpartmentof Industrial Enginecring and Management Sciences ai
Northwestern University in 1979, and served a s c h a i r o f lhe depanment fxom 1989 t o
1995.

Davkl M G a y reccived his P h D . in computer scienoe f r o m CornelI University in 1975.


and w a s in the Computing Science Research Center at Bell Laboratories f r o m 1981 t o
2001: he is n o w C H O o f A M P L Optimization L L C . Mis research i n f e r e s * inchide
numérica) analysis. optimi/ation. and scientilic computing.

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

( t i a p t r r 1. Produclion ModH%: Maximiiing Profit* 1


1.1 A (xixi varabk-biv.ir pmgrjLm 2
12 T h : Iwo vaiiahlc linear progrim in A M P L 5
1.3 A bivai progruranins ma dei 6
1A T h : l i n e v pragraraning model in A M P L 7
Tlie bxác madel 8
An improwd nudel 10
(\tfchmg c m rs 12
1.5 Acklmg lawcr baundx ki #ic model 13
1 J6 Acklmg resaurcccximtniiUs I» éic model 15
1.7 AMPl.mi.-xfacx.-s 18

Cliaplcr 2. Iíirl ai»d Other liiput M a d H » : MÚMini/inj: C a i U 27


2.1 A biiMJ pmgrani ferth: dic<prabk.-m 27
22 A n A M P I . model for th: dic< pr<ibk:m 30
23 IJ-ang éic A M P I . dictmodd 32
2A (icivrali/aíKins fci bkrndinc. ccciixnnx~s and sch.<Jiilxnc 57

Oiaptrr3. Trait%p<irtatkin aml A%tttf»inc*i»t M«dH% 43


3.1 A Imair pragram kw th: transp<»1a«ian problem 41
32 A n A M P I . model fcrlhc transp<»1a«ian problem 45
33 Odier mlcrprctuicim o f th: traropoitilkin model 49

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

Cl»aptrr 5. Slmple Sefeand Indaàng 73


5.1 Unordered se<s 73

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

Oia|>trr6. C o m p o u i x l Sctx and IIKICvini: 91


6.1 Se<sofordi-rcd pairs 91
62 Suhscts aixl shees of ordcied pairs 93
63 S c t x o f l a n g c r tuples %
64 Opcralxim <«i s c * o f tuple* 98
65 Indrxcdcollcctions cif xcix 1CK)

Oia|>trr7. I \ i r a m c t c r » and h x p r m k i i t * 109


7.1 Paramctcr dccl.&r.ition* 110
72 ArilhmcCic exprvxúanx 111
7.3 Lqgieal aixl conditkiiul expressions 114
74 Restriciianson jurameters 116
7.5 C b n i p i t e d p-rameters 118
7J6 Randomty genentod pAr.inurt.-jN 121
7.7 Logical p j i n u ^ e r s 122
7£ Symbolic paramctcix 123

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

9.5 Rcodxnc unfornuHcd d i l a : lhe r o a d ccnunand 163

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

U i a p t r r 11. ModHinj: C a m m a m b 203


11.1 General principies o f conuiLindsand o p t o n s 203
CcmuiLinds 201
Optums 204
112 Sc«xnc up and s o l v i i ç modeks a n d d a t i 206
Hntmqg mo deis and d i l a 206
Sol vi ng a mode 1 207
113 Modifymgdati 209
Rcscltnc 209
Resiniphi^ 209
T h e l o L conunand 210
1U M o d i f y ing models 212
Remeivmg <r rcdefmmg modelcomponento 213
Ounging lhemodel: £ i x , u n £ i x : d r q p , r c c t o r c 214
R e l i x m c BUcgrably 215

C h a p t c r 12. Dtsptay CoraraamLs 219


12.1 Browsirçg Ihrough results: I h e d i s p l a y ccmmand 219
Displiying srts 230
I>i s p l i y m g juramcl crs and variables 2 30
DispUyxng indexed exprcssions 221
122 Icmultirçg aplions for d i s s p l a y 227
X W F L A W O C e . P*3 U W 3 U A 3 E F C R WA THE WAT C/t. F R D G R A V M N 3

Arràngcmcnt a f and «atiles 227


Control a f Ixnc w i d é i 229
Supprcxsian o f zcvat 231
12J Numcríc oplionc f o r d i s p l a y 232
Apjx\irancv o f numcric valucs 233
RounJing af solutkin v-ilues 236
124 Othrr oulpul « n u i L i n d * : p r i n L AJKJ p r i n t í 238
T h e p r i n L commarxi 238
Tlie p r i n t í cxnuiLind 239
12.5 Rrhrfedsalutian vaüum 240
Objeclive funcliom 240
HounJx JLIKI slocLs 241
Dual valurs aixJ rcducxxl cxkís 243
1 2J6 Olhei drspUy fc\Uunrs kw modrlx aixl mtfojKvs 245
Di l i \ m g nuKÍelcomjx»rvnfc: tfie zher/j cxmuiLind: 246
Displiymg nuxi e 1 dcpcndencx-s: <he x r e f coimiund 247
Displiymg modcl i n s t u i c n : thu* c x p a r > d commarxi 247
Cimcric s)'rtin)'ms for varnbks.comtn&irUs oixJ objcclivcs 249
Rcsourcc htfmgs 250
12.7 Oi~ncr.il f a c i h t c s f<* nuuiipuLuing oulpul 251
Rcdinxtian o f oulpul 251
Oulpul lqgx 251
L i m à s <«i messages 252

C1» apte-r 1 1 C Iam n u ik! $ c r i p t * 2 55


13.1 Runnirçg scripts: i n c l u d c a n d c o n u i a n d s 255
13.2 Ifcrrjiling ourr a SCC <he f o r rtaànnenl 258
13J Ifera*mg subjecl Co a condi li an: é i e r c p e a L «rtafcxncnl 262
134 Tcsting acoixlrtKin: t h : i f - L h c n c l slalcnicnt 261
13J5 T c r m i i u l i n g a kiop: b r e a k and c o n t i n u e 266
13J6 Sfcppirçg Oirough a sen pl 268
13.7 Marupubilingcharaclfr tfrmc* 27*)
S«nng funclkim aixJ operai cr* 2*70
Stnng e x p n » » a n x in A M H . commandx 273

U i a p t r r 14. I n t e n d i a m \»HI» S o l v e r » 275


14.1 Preso Ivc 275
A c l í v ü r s o f lhe presolve phase 276
C a n t o D i n g é i c cffcct* o f p m d w 278
DMeclifÇ i nicas i i i l i l y in presalw 279
142 R d r i e v i q g rexukx fram s o l v m 282
S o l w ivsuks 282
S a i r e i sl atures of abjeclives And prablcms 286
Solrer xlafcirex of variables 287
Solrer sl atures of canslraint* 291
A M H . stK uses 293
A V R _ A WCC€L N 3 LAN3UAGE F C R WATHEMATCAL F T O 3 R W W N 3 XI

14.3 llxchoncinc mfcrnulkin w*i<h sal w s v i j s u f f i u - s 295


lJ<er d-Tined suífiu*s: írtcgcr pragramnurçg duvctnvs 2%
S o l w r dcfincd suflucs: scnsitovity analysis 298
S o l w r dcfincd suf fixes: mfcasitolitY dii£nc>sis 299
S o h v r d c f m c d suífixes: dircctum o f unbciunck-dnrss 300
IXTinins And u s i i ç suf fixes 302
144 Al t:rn atine tvtux-vn maòcls 301
U-5 Nantcd pmblems 309
IXTirai^s nanicd prablcms 311
lJ<ins runicd problcms 314
DispUvxng xunicd problcms 315
IXTirai^s Andusii^g nanic«Jenvm*imerts 316

C l » a p t r r 15. N r t w i r k L i M T Prugram* 319


15.1 Mininium cxK((rjLmshipnicn( nuidcls 319
A gcncraUrjLroshipment m o d e l 330
Spcoab/cd transshipuicnf niodcls 323
V i r i r ò a n s <*i transshipnicnt n u d e h 326
15.2 Othcr n e t w a A modclx 328
Maximum f k i w m a d r l s 328
Shortesl juíh mcxfels 329
TrjLnsp<HjLti<n andasu£nmcftf madrls 330
15J Dcclaring nctwcrk maòcls by rode aixi a r e 333
A gcncraUrjLroshipment m o d e l 3M
A spcculi/cd transshipnicnt model 335
Viriatians <*i transshipnicnt nuidch 336
Maximum f k i w m a d r l s 337
154 Rui cs for n o d e and a r e dcclorotuíis 340
rode (ircloratuins 340
arcdcclirotioiK 340
Irtcrjctiun w r t h o b j c c t n v d x l o r o t K í i s 341
IrtcractKfi wrthcanstraint dcchralioiK 342
liUcracticn wüh varubL- d x l a r a t u í i s 342
153 Solving network brvai programs 343

O i a p t r r 16. C d u m n v * hc- KormuLitioit* 353


16.1 An input oulput model 351
IxrmuLukin by coistrainti 351
A columnwise íormulati<in 355
Rcfmcnicnls af the colinnnwise farmulatian 357
162 A schcdulmg model 359
16.3 Rules forcohimmvrse farmulati<*is 362

Q i a p t r r 17. Pircrwfce-I Jurar Pragram* 365


17.1 CcMCcrms 366
Kixcd numhrrs a f píccrs 366
xi W F L A W O C e . P*3 U W 3 U A 3 E F C R WA THE WAT C/t. F R D G R A V M N 3

V « y mg mimtvrs a f pieccx 368


172 C o m m o n two piecc and tinte pico? fcmvt 369
IViulty C e m » for " x o f t " cunxtroint* 369
IXMIBIS witii mfeasibihtY 373
Rr\«rsl>k adi sites 377
17J OthrrpíecvwKC bivar funclians 379
17.4 Cjuidcbivs for piecewise linear oplniu/atum 382
I x n w for piecewise linear expressians 382
Siçsestians kw péecewwe-km* ar n u d c K 383

CliaptcrlX. Nanlkmr Piorara» 391


18.1 S<iurccsaf nankncarity 392
Dropping a kncarity assumptkin 393
Achieving a nonlincar effcct 396
Modckrçg an inhcrentlv nonlincar praccw 397
182 Nonlinear variahlcs 397
Initial valum a f variablcs 398
Automatic s u b s ú u t k m a f varubkrs 399
18.3 Nonlincar expressxim 400
184 Pitfallsof nankivar prosrammirçg 403
Rmctian range vkiLukim 403
Mui ti pie k c a l aptima 407
O l t e r pitfalk 410

Q i a p t r r 19. Complritirnkiril.v F t o M r n » 419


19.1 S<iurctsaf complcmcntaritv 419
A campkvncfitarity modcl a f produclkin ccunamics 430
Camplcaicflltfity for bounded vambkr* 423
ComplcinetilariCy for price dependei* demand* 425
Olher cxmplementerity modeh and appl ical k» ik 4 26
192 I x i n w o í oamplcaicflltfity con<«raints 427
19J W o r i i q g witii complcmcntarity canstrainfc 428
ReLUed sohjtian v a ü u » 428
Ptoolve 429
(jenerie xynonyms 431

Oia|>tc-r2ti. I n t r y r r IJm-ar P r o j j r a i m 437


20.1 Idegsr v m f c k » 438
202 Z e r o a n c variahlcs and lqgícal canditian* 439
Facd «kí< 440
ZefO c* mini muni xvsírjc1k»m 444
Cardiiulity rtslriclkiiK 445
203 PraclicalcoiKidcratians m integer prcgramming 448
A V R _ A WCC€L N 3 LAN3UAGE F C R WATHEMATCAL F T O 3 R W W N 3 XII

AppoidfcA. A M P L R e f e r e m * Manual 453


A . 1 L e x i c a l ruim 453
A. 2 Sc< memhrrs 451
A.3 Inck-xingexprcssian* JLJKJ subscripts 455
A.4 H&prettkim 455
A.4.1 Built in funclkiiw 458
A.4.2 Sirmg* .iixi JVCUIOJcxpressicíis 459
A . 4.3 Piccewisc lmear Icnns 460
A.5 Dcc lir.il kiro o f modcl entitic* 461
A.6 Se« decl.ir.Uian* 461
A.6.1 Cirdinality juid arity funclkim 462
A . 6 2 Ordrrcd 463
A . 6 3 Inlirrvah JLIKJ aOier infinit: SC* 463
A.7 PJLTXXIU:<CR tire 1 A X A T < m s 465
A.7.1 ChcckstUcnienls 465
A.72 Infnüy 466
A.8 V a m b k : dcclirafkim 466
A . 8.1 Defincd varâbfcs 467
A.9 C o n s t r u i * dcclaralianx 468
A . 9.1 C a mpl emcnt arit y cx» ns trai nt s 4 (fí
A . 10 Objeclive dcclaralianx 4IV)
A . 11 Suífix nolatian for auxiliary values 4 "TC)
A . 11.1 Suífix decbritk.ro 471
AllJSutuses 473
A . 12 Stindird áiAã f o m u i 473
A . 12.1 Setdjiti 473
A . 1 2 2 Ptmmcter datai 475
A . 13 DULULIULSC i c c e m And tobkrx 477
A . 14 C<BIUILLND l a n g i u g e ONCTVÍCTW 479
A . 14.1 ()pfcons .ind environmcnt vonoMes 481
A . 15 Rcdsrectian a f input aixJ auflpul 481
A . 16 Printirçg aixJ drspliy cammMlcb 482
A . 17 Readirç data 4&i
A . 18 Modckrçg «nuiurnch 485
A . 18.1 T h e r>D 1 vccx»niniarxi 485
A . 182 The . c o l u L i o n aininuuiJ 487
A . 183 The w r i t c c x i n u i u m J 487
A . 184 A u u t í w y f i k r s 487
A . 185 Chinging a m a d r l : d e l c L c t , p u r g e . r o d e e i a r e 488
A . 18.6 T h e d r o p , r c r . L o r c i n d a b j e c t i v e conuiLinds 489
A . 18.7 The f i x x i d u n i i x conuiLind* 489
A . 18.8 Muitcd pro falem* aixJ enviranmcnls 489
A . 18.9 M a d i f y i n s d a c c r c s c U updaLct, l e t 490
A . 19 Ilximining modrls 491
A . 19.1 The sheus cxíiunond 491
Xkf A W L A WCC€L N 3 LAN3UAOE FOR WATKEVATCAL F B X R W W N3

A . 192 The x r c í « n u i L i n d 492


A . 19 J The e x p a r x i a n u i u m d 492
A . 1 9 4 Generic nunca 492
A . 19.5 TTie chmckconmmná 492
A.30 Scripts juxl contrai f l o w slafcincflfc 492
A.30.1 T h e f o r . r e p e a L i £ - L h c n - c l .cc atafcmenfc 493
A.30.2 S f c p f â i ç tirou gh c o m m m d x 495
A . 21 C o m p if( atu m a I en vi k*\ menl 495
A.21.1 T h e . c h e l 1 C O f x m n d 495
A . 2 1 2 T h e o d conuiLinj 495
A . 2 1 3 T h e q u i t . e x i L a n d e r x i conunancb 4%
A.21 J4 Huik xn tiniins p n m e t e n 4%
A.21-51jcissms 4%
A . 22 Imported funetian* 497
A . 23 A M PI. nm»c.i«ian 499

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

In the developcnent and application o f mathematkral programming, one special case


stands out that in which ali the costs. requirements and other quantities o f interesi are
terms sirictly proportk>nal I o the leveis o f the activitiei. or sums o f such ter ms. In mathe-
matical terminology, the objective isa linear function. and the constraints are linear equa-
tionsand inequalities. Such a problem iscalled a linearprogram, and the processof set-
ting up such a problem and solving it is called linear programming. Linear programming
is particularly imporiam because a wide variety o f problenti can be modelcd as linear
programs, and because there are fast and reliabkr mettuxls for solving linear programs
even whh thousands o f variables and constraints. The ideai of linear programming are
also imporiam for analy/ing and solving mathematkral programming problems that are
not linear.
Ali useful mettuxls for solving linear progrant* require a computer. Thus m o s t o f the
study o f linear programming has taken place since the laie 1940's, when it became clear
that computers would be available for scientific computing. T h e first successful compu-
tational mettuxl for linear programming, the simplex algorithm. was proposed at this
time, and was the subject o f increasingly eftective implementationsover the next decide.
Coincidentally, the development o f computers gave rise to a now much more familiar
meaning for the term "programming."
In spiie o f the broad applicabilhy o f linear programming, the linearhy assumption is
somei imes kx> unrealistie. l f insiead some smooth nonlinear functk>ns o f the variables
are used in the objective or constraints, the problem is called a nontinear program. Solv-
ing such a problem is harder, though in practice not impossibly so. Although the optimal
values of nonlinear functions have been a subject o f study for over two centuries. compu-
tational metluxLs for solving nonlinear programs in many variables were developcd only
in recent decades. after the succcss o f metluxls for linear programming. The field of
mathematical programming is thus also known as large scale optimizfllion. *> distinguish
it from the classical topicsof optimi/ation in mathematical analysis.
T h e &isumptk>ns of linear programming a b o break down if some variables must take
on whole number, or integral, values. Then the problem is called inieger progmmming,
and in general becomes much harder. Nevertheless. a combination of faster computers
and more sophisticated methods have made large integer programs increasingly tractable
in recent years.

The AMPL modeüng language

Practical mathematical programming is seklom ai simpleas running some algorithmic


metluxl on a computer and printing the optimal solutk>n. T h e fuD sequence of events is
more like this:
• Formula te a model, the abstract system o f variables, objective», and constraints that
represem the general form of the problem to be solved.
• Collect data that define a specific problem instance.
• Generate a specific objective ftmction and constraint equations from the mixlel and
data.
NTRCOUCTON XVÍI

• Solve lhe problcm instance by running a program. or .VO/I«/\ toapply an algorhhm


that finds optimal values o f the variables.
• Analy/c theresults.
• Refine lhe model and daia as necessary. and repeai.
If peopkr coukl deal with mathemaiical programs in lhe same way lhai solvers do, lhe f<>r-
mulaiionand gcncraiion pha&esof modeling might be relatively straighlfocwjrd. In real-
ity, howxrver, lhere are many difícrcnces beuvven the f o i m in which human modeleis
understand a probkrm and the form in which sol ver algorithms work w i t i it. Conversion
from lhe " m o d e l e r ' s farm" to the "algorithm's form" is consequently a time-
consumi ng, costly. and o f t e n error-prone procedure.
In the special c a i e o f linear programming. the largest part o f the a|gorhhm's form is
the coAstraiitt ooefficient matrix, which is the table o f numbers thai multiply ali the vari-
ables in ali the constraints. Typically this isa very sparse (mostly zero) matrix whh any-
where from hundreds to hundreds o f thousands o f rows and columns, whose noa/ero ele-
ments appear in intricate patwrrns. A computcr program thai pnxluces a compact repre-
sentation o f the coefficienfe iscallcd a matrix gcnerator. Several programming languages
have been designcd specifically for writing matrix generak>rs. and standard computcr pro-
gramming languages are also often usod.
Ahhough matrix generators can successfully aux>makr some o f the work o f translalion
from m o d e l e i s form to algorithm's form. they remain difficuh t o d e b u g and maintain.
One way around much o f t h i s difficulty liei in the use o f a modeling hutgutige for mathe-
maiical programming. A modeling language isdesigned toexprcss the m o d e l e i s form in
a way that can serve as direct input to a computcr system. Then the translation to the
algorhhm's form can be per form ed entirely by oomputer, without the intermedbte stage
o f computcr programming. Modeling languages can help k> make mathematical pro-
gramming more eoonomical and reliable: they are panicularly advantageous for develop-
ment o f n e w m o d e k and for documentation o f m o d e k thai are subject k> change.
Since there & more than one form that mixlelers use k> express mathemaiical pro-
grams. there is more than one kind o f modeling Language. An algêbraíc modeling lan-
guage is a popular variety bccted on the use o f traditk>nal mathemaiical notation to
describe objective and constraint funetions. An algebraic language provides computcr-
readabkr equivalents o f notaiions such as x, + yr £?. t f x r x f ^ 0. and j € S thai would
be familiar to anyone who siudicd algebra t>r cak ulus. Familiarity is one o f the ma jor
advantages o f algebraic modeling languages: another is their applicability to a particu-
lar ly wide variety o f linear, nonlinear and integer programming nxxlels.
Whikr successful algorithms for mathemaiical programming firsteame into use in the
1950's. the development and distributk>n o f algebraic modeling languages only began in
the 1970's. Since then. advances in computing and computcr science have enabled such
languages to beeome stcadily more eíYicient and general.
T h i i Kx>k describes A M P L . an algebraic nnxleling language for mathemaiical pro-
gramming: it was designcd and implemented by the authors around 1985. and has been
evolving ever since. A M P L ii notable for the similar ky o f ifc arhhmetic expressions to
customary algebraic notaiion. and for the generality and powor o f hs sei and subscripting
xvill NTRCOUCT C N

expressions. A M PI. also exwrnds a l g e b n i c notation k> express commi)n mathematical


programming stmctures such ai network flow constraintsandpiecew&e linearities.

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*.

Theavailability o f an algebraic nnxleling language makes it possible k> emphasi/e the


kinds o f general mixlels that can be used to describe brge-scakr optimi/ation pcoblems.
Each AM PI. model in ihis book describes a whole class o f mathematical programming
problema, whose members corrcspond toditTerentchoices o f indexing sefc and numerical
data. Even though w e use relatively small data sefc for illustratk>n. lhe resulting prob-
lema tend to be larger than those o f the typical Krxtbook. More important. lhe sanxr
approach. using saíII larger data seis. works just as well f o r mathematical programs o f
realistic size and practical value.

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.

In addhion. AMPL software is readily available f o r experiment: the AMPL w e b site,


w w . â m p l . c o A , provides free downloadable "student" versions o f AMPL and repre-
sentative solvers that run on Windows. Unix/Linux, and Mac OS X. These can eaiily
handle problcms o f a fewhundrcxl variabkrs and consiraints. including ali o f the exam pies
in the book. Versions that support much larger problems and additional solvers are also
avaibble from a variety o f vendors: again. details may be found on the w e b site.
N1F9QDUC1CN XIX

Outline ofthe book

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:

1. Pioduction Models: Maximizing Profits


2. Diet and Olher Input Models: Minimizing Costs
3. Transportation and Assignmcnt Models
4. Building Larger Models

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

15. Network Linear Programs


16. Columnwise Formulaiions
17. Pkrcewise-Lincar ftograira
18. Nonlincar ftograms
19. Complementarhy ftrobbms
20. Intcger Linear Programs

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.

About the second edition

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

Acknowledgements to the fírst edition

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

A s w ê stated in lhe lntroductk>n. maihematical programming & a tcchnique for s o l v -


ing certain kinds o f probkrms — notably maximi/ing profits and minimizing costs —
subjcct toconstraint* on resources. capacáies, supplics. demands. and lhe like. A M P L is a
language for s p e c i f y i n g such optimi/atk>n problems. li provides an algebraic notai ion
thai k very c l o s e n> lhe w a y lhai you would describe a problem maihematical ly, s o lhai it
i s e a i y t o convert f r o m a familiar maihematical description t o A M PI..
W e w i l l concentrai? initially on linear programming. which isthe best known and eas-
icsi case: other kinds o f maihematical programming are taken up later in lhe book. This
chapter addrcsses one o f lhe most c o m m o n applications o f linear programming: maxi-
mizing the profh o f s o m e operatk>n. subject t o constrainfc thai l i m k what can be pro-
duced. Chapters 2 and 3 are devoted t o i w o other equally c o m m o n kinds o f linear pro-
grams. and Chapter \ shows h o w linear programming m o ò e k can be replicated and c o m -
bined topcoduce tmly large-scale problem». These chapters are written with lhe beginner
in mind. but experienced practiiioners o f mathemaiical programming should find them
useful a quick introduction k> A M P L .
W e begin w k h a linear program ( o r L P for s h o n ) in only twodecisk>n variabks, m o t i -
vated by a mythical steelmaking operaiion. This will provide a quick r e v i e w o f linear
programming t o refresh your m e m o r y if you already have some experiente, or t o help
you g e l â a n e d if you're jusi Icarning. W e ' 11 show h o w the same L P can be represenied
a general algebraic nxxlel o f production, together with specific data. Then w e ' l l show
h o w toexpress several linear programming problems in A M P L and h o w k> mn A M P L and
a solver t o produce a sohition.
T h e separatk>n o f m o d e l and daia & lhe k e y t o describing more c o m p l e x linear pro-
grams in a conciso and undersiandable fashion. T h e final example o f the chapter illus-
traics this by pre^enting several enhancements t o lhe modcl.

1
2 FBDCCCTCN V O C & S W A X W Z N 3 PttOF.TS CHVTÇR1

1.1 A two-variable linear program


A n ( e x t í c m e l y simplified) sieel company must d e c i d e h o w t o âDocate next W2ek's
time on a roDing miD. T h e mill takes unfinishcd slabs o f steel a* input. and can pnxluce
either o f t w o s e m i - f h i s h e d products. which \ve w f l l call bands and ooils. ( T h e terminol-
o g y is IKX entirely standard: see the bibliography ai the end o f the chapter for some
accounts o f realtvtic L P a p p l k r a i i o n s in steelmaking.) T h e milPs t w o products c o m e o f f
the rolling line at diíTerent raies:

Tons per hour: Bands 200


G>ils 1-10

and they a l s o h a v e d i f f e r e n t profitabilhies:

ftrofit per ton: Bands $23


G>ils $30

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:

M a x i m u m tons: Bands 6.000


G>ils IXXX)

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

(hours t o make a ton o f bands) x X + ( hours t o m a k e a k>n o f c o i l s ) x X c

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:

(1/200) XB + (1/140) Xc £ 40.

There a r e a l s o productk>n limits:

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

<p*ofit per ton o f bands) x Xü + (profit per ton o f c o i k ) x Xc

That is. our objeetive is *> maximize 25 Xü + 30 Xc. Puoing this ali together, have
the following linear program:

Maximize 2SXB + 30XC

Subject to < I /200) XB + < I /110) Xc £ -10


0£Xj,â6000
OíXc£AOOO

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:

Profit per hour: Bands $5,000


G>ils $4^00

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

T h e horizontal line represem* the pioduction limit on coils, the v e n i c a l on bands. T h e


diagonal line is the constraint on hours: each point on that line represents a combination
o f bands and coils that requires exactly -10 hours o f production time. and any point d o w n -
ward and t o the left requires less than -10 hours.
T h e shaded r e g i o n bounded by the axes and these three lines corresponds exactly t o
the feasibk solutions — those that satisfy ali three constraints. A m o n g ali the feaiible
solutions represented in this region, seek the one that m a x i m i z e s the ptofit.
For this problem. a line o f slope -25/30 represents combinations that produce the
same profit; for example, in the figure below, the line f r o m <0.4500) *> < 5 4 0 0 , 0 ) repre-
sents combinalions that yield $135,000 profit. D if ferem pcofíts g i v e diflerent but par aliei
lines in the figure, with higher profits g i v i n g lines that are higher and further t o the right.

Co*

Ba^
0 2000 4000 6000 SÜÜO

I f \v\r combine these t w o plots, can see the profit-maximizing. or upíumiL f e a i i b l e


solution:

N
COJÜ

CcttK 4000

2000 Optintui Soluíiun

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.

1.2 The two-variable linear program in A M P L


S o l v i n g this linear prograni with A M PI. can be ai simple ai typing A M P L ' * descrip-
tion o f the linear program.

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 :

intoa file — c a l l it p r c d O . r > c d — a n d then typing a f e w A M P l . commands:

^mpl: codol prodO .xaod;

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

a m p l : diaplay XB, XC;


XB = GO 00
XC = 14 00

ampl: quit;

T h e invocation and appearance o f an A M P L session will depend on your opera ti ng e n v i -


ronment and interface, but you will aKvays have the option o f typing A M P L statements in
response t o the a m p l : prompt. until you leave A M P L by typing quit. (Throughout the
txx>k. material you t y p e i s shown in thia ol&nted £ont.)
T h e A M P L linear program that you type into the file parallek the algebraic f o r m in
every respeet lt specifies the decision variables. defines the objeetive, and Itsts the c o n -
straints. It difYers mainly in being somewhat more formal and regular, t o facilitate Com-
puter processing. Each variable is named in a v a r statement. and each constraint by a
statement that begins with s u b j e c t t c and a name like T i m e or B _ 1 i m i t f o r the c o n -
straint. Multiplication requiresan explicit * operator, and the £ relation t% written < = .
T h e first command o f your A M P L session, r > c d e l p r c d 0 . r > c d , reads the file into
A M P L just as if you had typed it line-by-line at a m p l : prompts. Y o u then need only
6 F F O D U C T C N W O C S - S : W A X W ZNG PRCFTS CHífTÇR 1

type s o l v e t o have A M P l . translate your linear program. send it t o a linear program


sol ver. and reiurn the answer. A final eommand. d i s p l a y , is used k> show the optimal
values o f the variables.
T h e message M I NOS 5 . 5 directly f o l b w i n g the s o l v e command indicates that
A M P L used version 5-5 o f a sol ver called Ml NOS. W e have used M I N O S and several
other solvers for the examples in this b*x>k. Y o u may have a difíeient colleetion o f
solvers available on your computer, but any solver should g i v e you the same optimal
objective value for a linear program. O f t e n there is more than one soluüon that achieves
the optimal objective. howxrver. in which caie differcnt solvers may report ditTerent opti-
mal values for the variables. ( G o m m a n d s f o r choosing and cx>ntrolling solvers will be
explained in Section 11.2.)
Proceduies f o r running AM PI. can vary from one computer and opcrating sysiem t o
another. IXrtaik are provided in supplementary instructions that c o m e whh your version
o f the A M P l . software, rather than in this book. For subsequent examples, w e w i l l
assume that A M P l . has been started up, and that you have received the first a m p l :
prompt. If you are using a graphical interface f o r A M P l - like one o f those mentioned
briefly in Section 1.7, many o f the A M P l . c\>mmands may have eqüivalem menu or dialog
entries. Y o u will stiil have the option o f typing the commands as s h o w n in this lxx>k. but
you m a y have *> open a " e o m m a n d w i n d o w ' * o f s o m e kind t o see the prompts.

1.3 A linear programming model


T h e simple appruach empk>yed s o far in this chapter is helpful for understanding the
fundamentais o f linear programming. but you can see that if our problem w e i e only
sljghtly more realistic — a f e w more pnxlucts. a f e w more constraints — it would be a
nuisance t o write down and impossible *> illustrate with pictures. A n d if the problem
w\?re subject t o frequent change. either in f o r m or merely in the data values. h would be
hard t o update as w e l l .
I f WÊ are t o progress beyond the very tiniest linear programs. w e must adopt a more
general and concise w a y o f expressing them. This is where mathematical notation c o m e s
t o the rescue. W e can w r i t e a compact description o f the general f o r m o f the problem.
which WÊ call a /TOA/**/, using a|gebraic notation for the objective and the constraints.
Figure l - l shows the produetion problem inalgebraicnotation.
Figure l - l is a s y m b o i i c linear programming model. lts components are fundamental
t o ali models:

• sete, like the pcoducts


• para mete rs. like the produetion and profk rates
• \ a r i a b k s . whose values the sol ver i s t o determine
• an o b j e c t h c . t o be maximi/ed o r m i n i m i / e d
• c o i K t r a i n t s that the solution must satisfy.
S E C T C N 14 THE L N E A R F T O 3 R W W N 3 M D C € L N A V F L 7

Given: P , a sei o f products


i\f = tons per hour o f p n x l u c t f o r each ^ € P
b = hoursavailable ai lhe miD
e , = piofit per k>n o f product ) . f o r e a c h j e P
ut = maximum tons o f product j. for each jeP

Define variables: X{ = tons o f product./ k> be made. for e a c h ; € P

Maximize: Z'7*/

Subject to: £ 0/it/)x/ * h

0 £ X} £ ur for estchjeP

Figure 1-1: Bask- produetionmodel in algebraic form.

The model describes an infinite number o f rebtcd optimi/ation problems. If w e provide


specific values for daia. however, the nxxlcl becomcs a specific problem, or inshutce of
the nnxlel. that can be solved. Each different collcction o f data values defines a different
instance: the example in the prevk>us section was one such instance.
It might seem that w e have made things leis rather than more concise, since our
nnxlel fc longcr than the original statement o f the linear program in Scctk>n 1.1. Consider
what woukl happen. howxrver, if the sei P had 4 2 products rather than 2. The linear pro-
gram \vould have 120 more data values ( 4 0 each for c ^ and Uj): there \vould be -10
more variables. with ncw lower and upper limits for each: and there would be -10 nn>re
termv in the objective and the hours c\>nstraint. Y e t the abstract model. as slu>\vn above.
\vould be no different. NVithout this ability o f a short nnxlel todescribe a long linear pro-
gram. larger and more complex instances o f linear programming \vould become impossi-
ble k> deal with.
A mathemaiical nnxlel like this is thus usually the best compromise betwxren brevity
and comprehensk>n: and fonunately, h iseasy to convert into a language that a computcr
can process. From now on. w e ' l l assume nnxlels are given in the algebraic form. As
always. reality is rarely so simple, so nn>st nnxlels wfll have more sets. paramekrrs and
variables. and more complicated objectives andeonstraints. In fact. in any real situatk>n.
for mu la ti ng a correct nnxlel and providing accurate daia are by far the hardest tasks: solv-
ing a specific problcm requires only a solvcr and enough computing power.

1.4 The linear programming model in A M P L


N o w w e can talk about A M P L . The A M P L language is inkrnik>nally as close to the
mathematical form as it can get while still being easy to type on an ordinary kcyboard and
8 F F O D U C T C N W O C S - S : W A X W ZNG PRCFTS CHífTÇR 1

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:

Figure 1-2: Basic produetionmodel in A M P L (file p r o d . m o d ) .

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.

The basic model

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.

T h e k e y word p a r a m declares a parameter. which may be a single scabr value. as in

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

T h e objective ti given by the declaraiion

maximize T o t a l _ P r o £ i t : num ( j in P} cljl * Xljl;

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

subject Lo T i m e : sum ( j in P* (1/aljl) * XljJ <= b :

subject Lo L i m i t (j i n P> : 0 < = X l j l <= u[jl:

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

suai ( j in P} cljl * Xljl

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:

Figure 1-3: Production modeldaia<file p r c d . d a t ) .

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

süL PROD: 4 products


param r a t e (PttDD} > 0: 4 toa-, pr<xiuced p e r b o u r
param a v a i l > ~ 0 : 4 b o u r s a v a i l a b l c i n week
param p r o í i t (PROD}; 4 proíit p e r Lon
param m a r k e t (PROD} > = 0: 4 l i m i t on tons s o l d i n week
v a r Make ( p i n PROD} >= 0. <= market IpJ; 4 tons produc«i
maximize T o t a l _ P r o f i t : sum ( p i n PttDD} p r o í i L l p J * HakelpJ :
4 Objective: total proíits irem a l i products
subjoct t o T i m e : sum ( p i n PttDD} < l / r a t e [ p | J * M a k e [ p | < = avail:
4 C o n s t r a i n t : t o t a l o í b o u r s usod by a l i
4 p r o d u c t s may n o t c x c c o d b o u r s a v a i l a b l e

Figure l-4a: Steel produetion model ( s t e e l . m o d ) .

sei PROD : = b a n d s coils:


param: rate proíit market : =
baixis 200 * 25 6000
coils 140 30 4000 ;
param a v a i l : = 4 0:

Figure 1-4I>: Daia for steel pfüduction model ( S t e e l . d a t ) .

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 : xsodol atoai .aod;


a m p l : data ataal.dat;
ampl: a o l v o ;
MINQS 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 ns . o b j e c t i v e 192000

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 ] :

If you inadverKrntly use rwike instead of Jíake in an expression like p r o f i t [ p ] *


r i a k e [ p ] , you will receive thts message:

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:

a m p l : izodol atool .xood;


a m p l : data atool.dat;
ampl: a o l v o ;
E r r o r CXKTULii>g " s o l v e " cccnmand:
e r r o r p r o c e s s i n g param a v a i l :
f a i 1 od c h e c k : param a v a i l = -40
i s n o t >= 0 :

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:

Expressk>ns in the symbolic nnxlel such ai the coelYicients l / r a t e t p ] in this exam-


ple. are evaluaied befcxe the expansion is displayed. You can expand the objeetive and
ali of the constrainti at once by typing e x p a n d by itself.
T h e expressions above show that the symbolic model's J í a k e t j J expands ii> the
explicit variables J í a k e t ' b a n d s ' J and Jíake [ ' c o i l s ' ] . You can use expressions
like these in AMPL commands, for example to expand a particular variable to see what
coeíYicicnts it has in the objeetive and constraints:

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.

1.5 Adding lower bounds to the model


Once the model and data have been set up. it is a simple matter to change them and
then re-solve. Indeed. would not expect t o find an L P applicatk>n in which the nnxlel
and data are prepared and solved just once. or even a f e w times. Most commonly. numer-
ous refine me nts are intnxluced as the nxxlel is developed. and changes to the data con-
tinue for ai long ai the nnxlel t% used.
Let's conclude this chapter with a few examples of changes and refinements. These
examplesabo highlight some additional fea tires of AMPL.
14 F R X U C T CN W C C € L S : V A X « Z N G P R D F T S CHVTÇR 1

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 :

soL PROD : = bands c o i l s plaLo:


param: raLc proíit markoL : =
bands 2 00 25 GO 00
coils 140 30 4000
piaLc 1 GO 29 3S00 ;
param a v a i l : = 40:

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:

a m p l : isodal atoai.aod; data ataol2.datj aolvo;


M1MDS S . S : o p L i m a l s o l u t i o n í o u n d .
2 i L e r a t - i o n s . o b j o c L i v c 19G400
a m p l : diaplay Kakoj
Hake 1*1 : =
ha r>ds G000
co x i s 0
plaLc 1G00

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:

a m p l : xzodol staal 3 .jzcd; data atool3.dat; aolvo;


M1MDS S . S : o p L i m a l s o l u t i o n í o u n d .
2 i t c r a L i o n r . # o b j e t i v e 194B2B.S714

a m p l : diaplay c c n j e i t , Kako, aarkotj


: cccxniL Makc markoL :=
bands 1000 GO 00 GO 00
coils SOO SOO 4000
plaLc 7 S0 102B.S7 3S00

For compar&on. w e have displayed c o r e n í t and r ^ r k e t on either side of lhe actual


produetion, Jíake. As expected. after the commitments are met, it is nn>st profhabkr to
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 15

soL PROD: 4 products


param r a t e (PROD} > 0 : 4 p r o d u c e d t o n s p e r hour
param a v a i l > = 0 : 4 honre a v a i l a b l e i n woek
param p r o í i t ( P R O D } ; 4 p r o í i t per ton
param cccnmit (PROD} >=0: 4 lower l i m i t on toa-, s o l d i n week
param m a r k e t (PROD} >=0: 4 upper l i m i t on t o n s s o l d i n week
v a r Make ( p i n PROD} >= c o n i n i L l p l . < = m a r k e t [p 1 : 4 t o n s produc«i
maximize T o t a l _ P r o f i t : sum ( p i n PttDD} p r o £ i t [ p | * Make(pJ:
4 Objective: total profits irem ali produets
s u b j e c t t o Time: sum ( p i n PROD} <l/rate[plJ * Make [ p ] <= a v a i l :
4 C o n s t r a i n t : t o t a l o í h 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

Figure l - 5 a : Lowerboundsonproduetion(steel3.mod).

set PROD : = harxis c o i l s plate:


param: rate proíit coninit market : =
bands 200 25 1000 6000
coils 140 30 SOO 4000
plate 1G0 29 750 3 500 ;
param a v a i l : = 4 0:

Figure l « 5 b : Daia for lower boundson produetion < s t e e ! 3 - d a t ) .

produee bands up to the market limit. and then to produee plate with the remaining avail-
able time.

1.6 Adding resource constraints to the model


Processing of steel shbs ti not a single operation. buta series o f steps that may pro-
ceed at diíVerent rate». T o motivate a more general nnxlel, imagine that wvr divide pro-
duetion into a reheat stage that can process the incoming sbbs at 200 tons per hour, and a
rolling stage that makci bands. coils or plate ai the rates previously given. Funher imag-
ine that there are only 35 hours o f reheat time, even though there are -10 hours of rolling
time.
T o cover this kind of situation. w e can aJd a set STAGE o f produetion stages our
nnxlel. The parameter and constraint declarations are modificd accordingly. ai shown in
Figure 1-6*. Since there & a potentially different number o f hours available in each
stage. the parameter a v a i l is now indexed over STAGE. Since there isa potentially dif-
ferent pnxluction rate for each pnxluct in each stage. the parameter r a t e & indexed over
both PROD and STAGE. In the T í r n e constraint, the pnxluction rate for pnxluct p in
16 FRXUCT C N W C C € L S : WAX V Z M 3 P R D F T S CHífTÇR 1

sol PROD: 4 products


r.cl OTAOE: 4 stages

param r a L c (PROD.STAÚB} > 0: 4 t o n s p e r hour i n e a c h s t a g e


param a v a i l (STAGH} > = 0 : 4 bours a v a i lable/week in each stage
param p r o í i t ( P R O D } ; 4 p r o í i t p e r Lon

param cccnmit (PROD} >=0: 4 l o w e r l i m i L o n Lon 5 s o l d i n «Mtk


param m a r k e t (PROD} >=0: 4 upper l i m i L o n Lon 5 s o l d i n «Mtk
v a r Make ( p i n PROD} >= c o n r n i L [ p l . <= market [ p j ; 4 tons producod

maximize T o L a l _ P r o í i t : sim ( p i n PttDD} p r o £ i L [ p | * Make(pl:

4 Objective: total proíits irem ali produets

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

Figure 1-éa: Additional resource constrainfc ( s t e e i 4 .r>cd).

stage s is referred to as r a t e [ p . a ] : this is AMPl.'s versk>n o f a doubly subscriptcd


entity like u ^ in algebraic notatk>n.
T h e only other ehange is to the constraint decbration. where we no longer have a sin-
gle constraint. but a constraint for each stage. imposed by limited time available at that
stage. In algebraie notation. this might have been written

Subject to £< Wit r')xr * b ' •forc«rh.í€S.


rwP

Compare the AMPl. version:

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 :

As in the other examples. this is a straightforward analogue. adapted the requirements


of a computer bnguage. In almost ali nnxlek. most of the constraints are indexed collec-
tions like this one.
Since r a t e is now indexed ovar combinationsof two indices. it requires a data table
ali k> itself. ai in Figure l-6b. The data file must also include the membership for the
new set STAGE. and values o f a v a i l for both r e h e a t and r o l l .
After these changesare made. use AMPl. t o g e t another revised solution:

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

.cot PROD : = bands c o i l s p l a L c ;


s e t STAOH : = r e h e a L r o l l ;
param r a L e : reheaL roll : =
bands 200 200
coils 200 140
piaLo 200 160 ;
param: proíiL coniniL markeL : =
bands 2S 1000 600 0
coils 30 SOO 4000
piaLo 29 7S0 3S00 ;
param a v a i l := roheaL 3S roll 40 ;

Ffeure l-6bs Daia for additional resource constraints < s t e e 14 . d a t ) .

ampl: diaplay Mako.lb, Kaka, Makm.ub, Kaka.rcj


: Make.lb Make Make.ub Make. r c
bands 1000 3357.14 6000 S.32907e-lS
coils SOO SOO 4 000 -1.8S714
plaLo 7 S0 3142.86 3S00 3.SS271c-lS

a m p l : diaplay Tiizo;
Time l * | : =
rohcaL 1800
roll 32 00

The r e a e t commandcrases the prevk>us model so a n e w onecan be read in.


A t the end of the example above \v>í have displayed the "marginal values" (also
calkrd "dual values" or "shadow priccs**) associatcd with the Tirr>e constraints. T h e
marginal value o f a constraint measures how much the vahie o f the objective would
improve if the constraint were relaxed by a small amount. For example. here we would
expect thai up k> some poini additional reheat time would produce another $1800 o f
extra pcofit per hour, and additional rolling time would produce $3200 per hour: dccreas-
ing these times would decrease the profit correspondingly. In output cx>mmands like
d i a p l a y , AMPI. interprets a constraint'* name alone asreferring to the associaicd mar-
ginal values.
W e also dtvplay several quantities assocbkrd with the variables M a k e . First there are
lowor bounds M a k e . l b and upper bounds M a k e . ub, which in this caie are the same ai
correnit and r r i a r k e t . We also show the "reduced c o s t " M a k e . r c , which has the
same meaning with respect to the bounds that the marginal values have with respect to
the constraints. Thus \v>í see thai, again up to some point, each increaic o f a ton in the
lowor bound ( o r commhmcnt) for ooil produetion shoukl reduce profits by about $1.86;
each one-ton decxeaie in the tower bound should improve profits by about $1.86. The
productk>n leveis for bands and plaies are betwxren the ir bounds. so the ir reduced costi are
eisentially zero (recall that e - 1 5 means x l O ,5X and changing their leveis will have no
18 F R C O U C T O N W C C € L S : WAX W Z P*3 P F O F T S CHÍPTER 1

*XTI.'J*U«;VMtM • l 1
llle te* tftvw l>\plíY V.W lu« • HIM

Tf7r?írtir L> w C .'i v.rf./fr^. ^rm^ .^r^l vr«1


;/iíp' ofecl» M>ks; 4»*. ffcCC;•
'1
'AH» ->H:U) > Aj
— i •• r ; o l x-.Ml.sol, diu r.M'..4i'.; aol |.iV'AnMlll ^ (»
• Km pr
í 'rtie M*l'>lilr l'
rmi
J
|«»»<4i# • '.•!«» i- »«•• hn
/ i**!«M'f, JII U»Mr f«".r> >• t i* » <•• •»»"» ml* li >*"•
i AI lirAWi ;
1 i f i - w -••«•! f t-í-í^rrt vir {p -n K O ) »• •• M W ( r ; ? # ttn»
KTJW !.>: *».'.«« rMl-^M i « i U tvcÉJ.. In MM) • NiU|;|i
KZSW « í t f i . «vlit.vt ±t*l
2 .uriu-.u, aãjtctáv* MZBM ' lívlMlIVkl tva'. p t ^ l u Í4M* a i
— 5 •• pl»y
K»tí» |*1 »•« — ••• Ata • r» l« |l/M»r(i]i • •:-
Itia iV. "11C
fti V.

:
• tvrfi rr H-«-» «»»-- -»
• ptt^it-J to? rot «roer 1
/ «

/
'1

F i g u r e l - 7 a : A Java-baied A M P L graphical user interface (Macintosh).

e f f e c t . Bounds. marginal ( o r d u a l ) values, rcduccd c*>sts and other quantities associafcrd


with variables and constraintsare expk>red lunher i n S o c t i o n 12.5.
Comparing this session with our previous one, w e see that the additional reheat linxr
restriction reduccs profits by about $4750, and forces a substantbil change in t h e o p t i m a l
solution: much higher pr ixluction o f plakr and lowvrr produetion o f bands. Moreover, the
l o g i c underlying the optimum ti n o longer s o obvious. lt & the d i f f i c u l t y o f solving L P s
by logical reau>ning alone that necessitatcs computer-baved sysiems such a* A M P L .

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 -

F i g u r e i - 7 b : A Tcl/Tk-hased A M P L graphkal user interface ( U n i x ) .

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

Figure i - 7 c : A Visual Basic A M P L graphical user interface ( W i n d o w s ) .

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

Robcrt J. VjLndtttici. linear P)o^mnv)\in^ FounSuinns a mi Exlrnsi/yns (2nJ edition). Kluwer


Academic Pubhshers (Dcrdrccht. T h : NcHherLind*. 2CK11). An updUcd survey o f fincar piqgíMii
mirçg theury andmrtfcid*.
SECT-GN 1 7 W F L NTEPFACES 21

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

X, ^ S fer each jc />


ur

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.

( c ) U s e A M P L t o w r i f y lhe foüowing stateinenfe: If the availibke reh-at time is increased fram 35


to 36 in lhe dita of Fjgun? 1 6h. then lhe prafit goes up by $ 18CK1 as predicled in .Seclkin 1 .6 If lhe
reh-at i m e is further increased Io 37, lhe profit gcies up by aixither 5 18CK). I f o w e w r . if I h : reheat
time k «ncreased t o 38, there is a smaller increme in t h : profit. aixl further «nenroses just 38 h i v e
no e f f e c l o n th- optimal profit at ali. T o c h a r ç e lhe reheat time t a say. 36 withiut chinging axxl
jvotiinc th- d&ta file o \ r f acam. type th- o a m m n d

l*t AVAll[*!»2lAAt:»] :- 36;

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.

1 - 4 . H e i e is a sniuUr profit maximi/ms m o d e l but m a different context. An M k m o t a l e nunu


facturer praduers se\rral iinch o f a n I:ach kinJ requinw a ceitiin amount o f faclory time per car
to producv. anJ yielcfc a certain profit per car. A cortiin amount of fortory time has becn scheduled
f<* lhe next weck. and ü is desired to ute ali thw time: but at least acertam number o f each kirxJ o f
car mu st be manuíactured Io meet dealer requi remei* s.

(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.

Vjke Wcçtá Vofanc Axuiiible

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

aixl by KmilXOf 500 pau reis and 300cubic feet.


( c ) Suppose thit it is desirabk* to acquin: same af each item, sa as k) ahvays have skick availoble
hw nMaüe. Suppose in additicvi thit there are upper bciund* <«i haw man>' o f each item vau can
reasaiubh- expecl taseD. I l a w would yau addthese conditkim k» the madel?
( d ) H a w coukl the gxxiiip use the diul v a r á b b s o n the mxximum ux-ight aixl nuLXimum \xilume
cxnstraints t o evaliutc pcitential new putners for their actisities?
( e ) Thríii^gh adverse circumstances the gwiup hxs been reduced ki anly ane member, wha can Cãiry
a mere 75 pciunds and fivecubic feet. W h a t i s the optimum stntegy n o w ? G i v e n that this requires
a n<«i integral number af acquisitians, what is the best ali integer salutkin? ( T h e inlegralit>' cx«i
straint c o m e r t t thw fram a sOndud linear pxxigranuning pffablem into a much harder problcm
called a Krup-ack Problcm. See (Tupter 2 0 . )
24 F R X U C T CN WCC€LS: WAX W Z N S P R O F T S CHVTÇR 1

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)'

a- barreis o f inlcfmednle i a vaiLxbk:. for each i c /


RL4 units o f .atribute A coiUributed per KJJTCI of inlemiedute I, for each icl and kc K
u-i nuixinium alkiued units of attribuli' A per túnel o f final producl j*
for e a c h 7 and kc K
1 if inlcvmediatci i s a l k i u e d i n t h : blcnd f<r p r o d u c l « Ootherwise.
for each icl and jc J

anJ t h : eoanamic dita can h? gi\x-n by

ci ivvenue per túnel o f producl f<* each jc J

Theve are «wocollections of deciskin variables:

X-f b v r e k o f i n l c f m e d n l e i used Io make producl j, f<r each i c / ai»J jc /


K. barrek o f producl j nude. f<* each jc J

H i e o b j e c i w is Io

ma»núe

which is é i e sum o f th? fevenuex firam t h : various producis.


It reniains lei spccifv the constraints. U i e arnount of each inlemiedute used to m o l e produets must
equal the anwiunt available:

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 ü:

1ÍC,X.Í = YF« for e a c h / c J.

lx»r each producl. the «citai at tributes contributed by ali âifcrmcdiates must reit exceed t h : fcilil
allowed:

£ rA Xt. £ uti r H for each jc J and k € A'.

I i i u l l y . w e txiund the variables as f o l b w s :

0 £ Xa Z ò„a,, for each ic /. jc J%


0 ^ Yh fer ejeh jc J.
SECT-GN 1 7 W F L NTEPFACES 25

H i e upper bound o n Xt/ assuies thit only f i e appropriale mlermediites w i l l he w c d in bk*nding. If


i n t o m e d u t e i k not alkrwed in the blcnd for prodirt as inJicaled by ò, t being z o o , then the
uppti txiund <*i is zero: this crourw thit X , v camnof be pcnâtiw m any solutem. Otherwise. lhe
upjur bciurxl <*i Xt/ is just a | S which his nci effect since éiere an: CKI1>* a , barre k o f mlermedLUe i
avaihbk- f<r bleixlmgin on)' c i s e .
U ) Trarocrihe this model Io A M H - , usirçg lhe « m e rumes as in the algcbraic ferm f<r the s e * ,
p n m e t e n aixl varubk-s as much as p o w i i k - .
<b) Re wrile the A M H . model usirçg meaningful names anJ u i m i R O b , «n the x t y k o f Figure 1 -«ia.
( c ) In a represei* ali \e small scale inxtance of this model, the i n t e r m e d i a s an: S*Xi (xtraighl run
gatolineK N (ruphthi), R F (reformate). CG (cracked casolme), B (butine). D l (dixtilLUe írternuxh
ale>, OO ( g a s o i l ) , aixJ R S (residuum). The fmjil produeto are R3 (premium casolxne). FG (regular
gatolineK D (distillxte). and 1IF (lieavy fuel « 1 ) . 1'xnally. the atribules are v a p ( v a p o r pressure),
o c L (rescarch oclarv), d o n ( d e f K Í t y ) , aixJ s u l (sulfur).
H i e f o D a w i n g junounlsof the i n t e r m e d i a ! » are scheduled Io be avaiUbk-:

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):

iVcruujn A tc^lir^ascihâe Uvollxc \kú\y telcol


vap oet dan flUl fiul
SIC li.4 -7X.S
K 6M -65.0 272
RF 237 -IOIjO
CG 6.90
B -91*
D: 2*2 52b
GO 2*5 J5* 295 J5*
RS Í4J 4.70

T h e attnbule bmstsand rewnues.tiarrel for the produets aie:

VAp oet dan flui rawnua


PC 12-2 -SO 1040
RC 12.7 —246 9.10
D 306 05 7.70
HF Í52 ÍJS 665

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

T o complement the proftt-maximi/ing m o d e l s o f Chapter I . n o w oonsidor linear


programming models in which lhe objeetive t% t o minimi/e costs. Where the constraints
o f maximi/atk>n nnxlek tend t o be upper limits on the availability o f resources, the c o n -
straints in minimi/ation mixlelsare more likely *> be k>\ver limits on the amounts o f cer-
tain ' 'qualities" in the solutk>n.
A s a n intuhive exampke o f a cosi-mini mi/i ng n n x l e l this chapter uses the w e l l - k n o w n
" d i e t p r o b l e m " , w h i c h finds a m i x o f fcxxLs that satisfies rcquirements on the amounts o f
various vitamins. W e w i l l again construct a small, e x p l i c h linear program. and then show
h o w a general nuxlel can be formulated f o r ali linear programs o f that kind. *Since you
are n o w more familiar with A M P L . howxrver, will spend more time on A M P L and less
witha|gebraic notation.
A l t e r formulating the diet nnxlel. will discuss a f e w changes that might make it
more realistic. T h e fuD powa o f this nnxlel, ho\v>íver, derives from hs applicability t o
many situatk>ns that have nothing t o d o with diets. Thus wvr conclude this chapter by
rewriting the mixlel in a more general way, and discussing its application t o blending,
economics, and scheduling.

2.1 A linear program for the diet problem


Consider the problem o f choosing prepared fcxxls *> meet cenain nutrhional require-
ments. Suppose that precookcd dinners o f the f o l l o w i n g kinds are available for the f o l -
l o w i n g prices per package:

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

Rfc» beef $3.19


anc chicken 2.59
HSII fish 2.29
II AM ham 2.89
MOII macaroni & cheese 1.89
Mil. meai kxaf 1.99
sp<; spaghetti 1.99
TUR turkey 2.49

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

Rfc» 60% 20% 10% 15%


anc 8 0 20 20
HSII 8 10 15 10
IIAM 10 10 35 10
MOII 15 35 15 15
Mil. 70 30 15 15
SP<Í 25 50 25 15
TUR 60 20 15 10

T h e pcoblem is t o find the cheapest combination o f packages that w i l l me et a \vvek's


requirementv — that tv. at least 7 0 0 % o f the daily requirement for each nutrient.
L e t us write XAAR ^ the numbcr o f packages o f beef dinner t o be purchased. X<J/K
for the number o f packages o f chicken dinner. and s o forth. Then the *>tal cost o f the diet
will be:

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

T h e total percentage o f the vitamin A requirement is given by a similar formula, except


that X ^ j f . X c h k * ft*1*1 aíe multipliod by the percentage per package insicad o f
the cost per package:

total percentage o f vhamin A daily requirement m e t =


6 0 X MM + 8 XOÍK + 8 XFISM + 40 X J/AM +
\ 5 X m c h + 70 X iW/J . + 23 X&C + 60 X,VR

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

20 XMJS + 0 XOÍK + 1 0 * ™ , , + A0XHAÍÁ +


+ 30 + 50 Xjspo + 20 X7VK 2 700

1 0 X ^ + 20 XATX + 15 X / J S W + 3SXHAM +
15 X * ™ + 15 XMFL + 23 X w ; + 15 X7VK 2 700

1 5 x ^ + 20x0,,+ iox f a f + ioa:waw +


15 X j y r w + 15 X iV/J> + 15 X ^ + 10 X / L * 5 700

^ 0, XANC 2 0.X fiS „ 2 0. XHAST 2 0.


X ^ 2 0. XM/L 2 0. XSPO 2 0. XWK 5 0

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:

v a r X b c c í >= 0: v a r X c h k >= 0: v a r Xfisih >= 0:


v a r Xham > = 0: v a r Xmch >= 0: v a r XmLl >= 0:
v a r X s p g > = 0: v a r X L u r >= 0:

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

a m p l : zsodol dlatO .aod;


ampl: aolvo;
M1NQS S . S : o p L i m a l s o l u t i o n í o u n d .
G i t o r a t i o n s , o b j o c L i v c BB. 2
a m p l : diaplay Xboof, Xchk, Xf isih,Xhass,XjDch,Xictl ,Xap<j,Xtiir/
Xboef = 0
Xchk = 0
Xíish = 0
Xham = 0
Xmch = 4G.GGG7
XmLl = - 3 . G 9 1 5 9 c - l B
Xspg = - 4 . 0 S 3 4 7 c - l G
XLur = 0

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.

2.2 An A M P L model for the diet problem


Clearly w e wiD have t o oonsider more extensive mixliíicaiions to our linear program
in order t o produce a diet thai ti even remotely acceptable. W e will probably want t o
change the sets o f f o o d and nutrientv. as well ai the naiure o f the constrainto and bounds.
A s in the producú>n e x a m p l e o f the previous chapter. this w i l l be much easier k> d o if w »
rely on a general nnxlel that can be couplcd whh a variety o f specific data files.
T h i i mixlel deals with t w o things: nutriente and foods. Thus wvr begin an A M P L
nnxlel by dcclaring sets o f each:

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:

param c o s L (FOOD} > 0:

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

param £_min (FOOD} > = 0:


param £ nvax ( j i n FOOD} > = £_minljl :

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:

p a r a m amt (NtrrR.FOOD} >= 0:

R e f e r e n t e s t o this parameter require t w o indices. For example. a m t [ i . j ] is the amount


o f nutrient i in a package o f food j .
T h e d e c i s i o n variables for th& nxxlel are the numbers o f packagcs t o buy o f the d i f l e r -
ent foods:

var Buy (j in FOOD} >= £_min[jl. <= £ nvaxljl:

T h e number o f packagcs o f s o m e food j t o be bought will be called B u y t j ] : in any


acceptables4)hitionitwillhavetoliebet\vvxrn£-min[j] and £ _ m a x [ j ] .
T h e total cost o f buying a ftxxl j is the cost per package. c o s t t j h times the num-
ber o f packagcs. B u y [ j ] . T h e objeetive t o be minimi/ed is the sum o f this product o v e r
ali fcxxls j :

minimize Total_Cost: sum ( j in FOOD} costljl * Buyljl;

This m i n i m i z e dccbration wories the same as m a x i m i z e did in Chapter 1.


SimQarly. the amount o f a nutrient i supplied by a ftxxl j is the nutrient per package.
a m t [ i . j ) , times the number o f packagcs B u y [ j J. T h e total amount o f nutrient i sup-
plied is the sum o f this product o v e r ali foods j :

sum ( j in FOOD} amLli.jl * Buyljl

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} :

t o say that a constraint named D i e t I i ] must be imposed for cach member i o f N U T R .


T h e resi o f the declaration gives the algebraic statement o f the constraint for nutrient i :
the variables must satisfy

n min l i 1 < = sum ( j in FOOD} amt[i.j| * Buyljl <= n maxlil


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

M L NITTR:
FOOD:

param c o s L (FOOD} > 0:


param £_min (FOOD} > = 0:
param £ nvax ( j i n FOOD} > = £ _ m i n l j | :
param n_min (NUTR} > = 0:
param n nvax ( i i n í f J T R } > = n_minli|:
param amL (NtrrR.FOOD} >= 0:
v a r Buy (j i n FOOD} >= £ _ m i n l j j , <= £ n v a x l j l :
minimize ToLal_CosL: zun ( j in FODD} c o s L l j l * Buyíjl;
s u b j e c L Lo DioL ( i i n ? r j r R } :
n _ m i n [ i l <= suai ( j i n FOOD} a m L [ i . j J * BuyljJ <= nmaxlil:

Figure2-1: Diet nnxlel in AMPL ( d i e t : . m o d ) .

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.

2.3 Using the A M P L diet model


By spccifying appropriaic daia. uw» can solve any o f the linear programs lhat corre-
spond to the above nnxlel. Let's begin by using lhe data from the beginning o f this chap-
ter, which is shown in AMPL format in Figure 2-2.
T h e value* of £_snin and n j n i n are as given originally, while £_rnax and n_snax
are set, for the time being, to large values that won't aflect the optimal solution. In the
table fc>f arnt, the notation i t r ) indicates thai w e have "tran&po&ed" the table so the
columns correspond *> the first index (nutriente), and the rows to the second (foods).
Alternaiively, we oould have changed the nnxlel lo say

param amL {FOOD.NWR}

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: isodol dlot.xaod;


ampl: data diot.dat;

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 ;

Figure 2-2: Data foi diet nnxlel « l i e t . d a t ) .

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

Natural ly. the result is the same ai before.


Now&uppo&e that \V>Í \vant to makc the foDowing cnhancements. T o ptfomote variety,
the waekly diet must contain between 2 and 10 packagcs o f each food. The anx>unt o f
sodium and calories in each package is alio given: total sodium must not exceed -10.000
mg. and total calories must be between 16.000 and 2-1.000. AH o f these changes can be
made through a f e w modi fie ations to the data. ai shown in Figure 2-3. Putting this new
data in file d i e t 2 . d a t , we can mn A M P L again:
34 D E T A N D Q T H m NPUTWOCe-S: W NMZ W3COSTS CHífTÇR2

M t NlfTR ! = A B l B2 C NA CAL :
£ « t FOOD : = BKKF ÜLK F1S11 HAM MC1I MTL SPG TUR :

param: cosi £_min f oiAx :


13I£1£F 3.19 2 10
Cl IX 2.59 2 10
F1S11 2.29 2 10
HAM 2 .89 2 10
1.89 2 10
MTL 1.99 2 10
SPG 1.99 2 10
TUR 2.49 2 10 ;

param: n_min n nvax j r


A 700 2 0000
C 700 2 0000
131 700 2 0000
B2 700 2 0000
NA 0 4 0000
CAL 16000 24000 •

param amt <trj :


A C 131 132 NA CAL
BliüF GO 20 10 15 93 8 2 95
a ix 8 0 20 20 2180 770
F1S11 8 10 IS 10 94 5 440
HAM 40 40 35 10 27 8 430
IS 35 IS 15 1182 315
M1'L 70 30 15 15 89 G 4 00
SPG 2S SO 25 15 1329 370
TUR GO 20 15 10 1397 4 50

Figure 2-3: Daia for cnhancvrd diet model < d i e t 2 . d a t ) .

ampl: xsodal diot.xsod;


ampl: data diot2.datj

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

a m p l : diaplay Diot.lb, Diot.body, Diat.ub;


• DioL.lb DioL.body DicL.ub
A 700 1993.09 2 0000
131 700 841.091 2 0000
B2 700 601.091 2 0000
C 700 1272. SS 2 0000
CAL 1G000 17222.9 24000
NA 0 4 0000 4 0000

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:

ampl: lat n aax [ "KA") i- 30000;

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

ampl: lot BayfBEEF" J t» 6/


ampl: lot Buy["SPG"] t* 10 j

a m p l : diaplay Diot.lb, Diot .body, Diot.ubj


: D i o t . l b Diet.ixxiy Diet.ub :=
A 700 2 012 2 0000
131 700 10G0 2 0000
B2 700 720 2 0000
C 700 1730 2 0000
CAL 1G000 20240 24000
NA 0 51522 50000

(The l e t statrnvrnt. which permiti modifications o f data, is described in Sectk>n 1 I J . )


You can simibrly check thai rounding the solution down to 5 o f beef and 9 o f spagheni
w i l l provide insuflicient vitaniin B2. Rounding one up and the other down d o e u T t woric
either. With enough experimcnting you can find a nearby all-integer solution thai does
salisfy the constraints. but still you will have no guarantce that it is the least-cost all-
integer solution.
A M P l . does provide for puning the integrality lestriction dircctly into the declaraiion
o f the variables:

v a r Buy (j i n FOOD} intoger >= f _ j n i n ( j l , <= £ m a x l j l :

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 : data diot2a .datj


a m p l : option oolvor cploxj
ampl: aolvo;
CPLlüí 8 . 0 . 0 : o p t i m a l i n t c g o r s o l u t i o n : objoctivc 119.3
11 MLP s i m p l o x i t c r a t i o n s
1 hrarxrh-arxd-ixDiind nodcr.

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.

2.4 Generalizations to blending. economics and scheduling


Y o u r pcrsonal experience prohably suggests that diet nnxlels are not widely used by
people to dux>se their dinners. These nnxlels would be much betier suhed tosituations in
which packaging and personal preferences don't play sucha prominent role — for exam-
ple, the blending o f animal fecd or perhaps food for college dining halls.
T h e diet mixlel is a convenient, intuitive example o f a linear programming formula-
tion that appears in many contexts. Suppose that rewrite the mixlel in a more general
w a y , av shown in Figure 2-4. T h e objeets thai wxrre called foods and nutrienti in the diet
nnxlel are now referred to more generically as " i n p u t s " and " o u t p u t s " . For each input
j, w e must decide to use a quantity X [ j ] that lies between in_min[jl and
i n _ m a x ( j 1: ai a resuh w e incur a cost cqual to c o s t t j 1 * X [ j ] . and w e create
i o [ i . j ) * X [ j 1 units o f each output i . Our goal is to find the leait-oost combinaiion
of inputs that yiclds. for each output i , an amount beiween o u t _ s n i n [ i ] and
out_max(i).
In one common c b s s o f applicaiions for this mixlel. the inputs are raw materiais to be
mixed together. The outputsarc qualitiei o f the resulting blend. The raw materiais oould
be the componente o f an animal feed, but they oould equally well be the crude oil deriva-
tives that are blended to make gaioline. or the diffeient kinds o f coal thai are mixed as
input to a c o k e o v e n . The qualities can be amounts o f somcthing (sodhim or calories for
animal feed). or more complex measures <vapor pressure or octanc rating for gaioline), or
even physical properties such as m i g h t and volume.
Inanother wxrll-known application. the inputs are pnxluction activities o f some sector
o f an economy, and the outputs are various pnxlucts. The i n _ m i r i and i n _ r n a x param-
eters are limits on the levek o f the activitiei, while o u t _ s n i r i and o u t _ r n a x are regu-
laicd by demands. Thus the goal is to find leveis o f the activities thai meei demand at the
lowest c o s t Thiü interpretatk>n t% relaied to the concept o f an economic equilibrium, ai
will e x p b i n in Chapter 19.
In still another, quite difteient applicatk>n. the inputs are work schedules. and the out-
puts corrcspond to hours worked on cenain days o f a month. For a particular work
schedule j , i o [ i f j) is the number o f hours that a person following schedule j will
work on day i (zero if none), c o s t I j ) is the monthly sabry for a person following
schedule j , and x [ j ) & the number o f workers aisigned thai schedule. Under this inter-
prctaiion, the objective becomes the total cost o f the monthly payroll. while the con-
straints say thai for each day i , the total number o f workers assigned to work thai day
must lie befween the limits o u t _ _ s n i n ( i ) and o u t _ s i a x ( i ] . The same approach can
38 D E T A N D O T H & 3 NFUT V O C & S U NMZ W3 C O S T S CHífTÇR2

s e t INPUT: 4 inputs
s e t OUTPUT; 4 OuLput-S

param c o s t ( I NP ITT} > 0:


param i n _ m i n { Í N R J T } >= 0 :
param i n max ( j i n I N P U T } >= i n j n i n l j ) :

param o u L _ m i n {OUTFJT} >= 0:


param o u t max (i in 0*JTFJT} >= out_minlil:

param i o (OUTPUT, I NP ITT} >= 0:

var X (j i n INPUT} >= i n m i n l j l , <= i n maxljl:

minimize T o t a l . Cost: sum ( j i n INPUT} costljl * Xljl;

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 ] ;

F i g u r e 2-4: Least-cost input nnxlel ( b l e n d . r n c d ) .

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.

A s anotherexample. in writing the objective ai

sum ( j in IWPUT} costljl * Xljl

\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*

out_jninlil < = sum ( j i n INPUT} ioli.jl * Xljl <=out nvaxlil

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

GcargB B. D M I Z Q , "lhe Dia Problem." Interfaces 241 4 (1990) pp. 43-47. An c i t f c f t M i ç


account o f lhe origmx of lhe d i d problem.
Sutrn Garaev Garilk- and Saul I. G T O , "Sigla*'* D i d Problem Revwited." Operalkim R e m d i
49. 1 <2001 )pp. 1-13. A review of th: dii-l problem'* angins AIK! HS influence overlhe years <*i
Imoir programmifÇ andon nutri li onisfc.

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.)

ttroJ aiGH pcace. âiik ^clitu rc^-xird

cu k m * 1254 1457 318 46 3W 1725 3000


fU< cr", n 4 16 43
cikjLjn 41S 41 42 141 536 0 «Í...U/
»ajjru--. A 0 0 70 860 720 0 500 I f .
ú>*,)pooad Í03O $1.00 $DQ5 $008 $023 $0.43

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:

Gilonet 100 200 300 130 300 500


Tolarac 5 2 $ $ OS

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

1 IIiE ,r & .5 0 '5


JtjjjJ l l 1 j l l
* o * E C
<3 5 I rf 2 í 1 8 É 8 | |
2 ? J * 2 A £ I ™ ® 5 ^
T t £ U M i l i >r
V I HH
M fC «* H J1 J1
r- r m í ri

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.)

2-7. In th- refinery model o f E x e i r â c 1-6, th- amount o f p r e m i u n gasobne t o be produred is a


dccision varubk*. Suppose imtead that orders dictate a produetion o f 42,000 turreis. T h : octine
ratirçg o f th- p r o d u z ispemiitted to be in the r a q g c o f 8 9 t o 91, and the vap<r pressure in a r a r ç e o f
11.7 lei 12.7. The five feed*tocks that are blended tc» make premium casolme h i v e the folkiwirç;
pxiduction and'<r purchise cxKfc:
32 D E T ANDOTHS^ NPUT W O C & S W NMI W5 C O S T S CHífTÇR2

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

3.1 A linear program for the transportation problem


Suppose that w e have dccided (perhaps by the methods dcscribcd in Chapter I ) t o
producc sieel c o i k ai three miD kxrations. in the f o l l o w i n g aniounts:

CARY Gary, Indiana 1-100


CLEV Ckrveland.Ohk) 2600
wrr Pittsburgh. Pcnnsylvania 2900

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:

FRA Framingham. Mavsachusetts 900


MT Detroit, M i c h i g a n 1200
LAN Lansing, Michigan 600
WIN NVindsor. Ontario 100
STL S t Loufc, Missouri 1700
FRE Fremont, Califórnia 1100
LAF Lafayetie. Indiana 1000

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:

GARY CLEV PIRR

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

L e t G A R Y : F R A be the number o f tons t o be shipped f r o m GARY *> FRA, and similarly f o r


the other city pairs. T h e n the objeetive can be wrfeten ai f o l l o w s :

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 +

I6GARY:STL + 26CLEV:STL + 28 PHT:$TL +

82 < ; a r y : f r e + 9 5 CLEV:PRE + 9 9 PITT:FRE +

8GARY:LAF + I7CLEV:LAF + 20prrr:LAF

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 +

GARYÍSTL + GARYÍRFC + G A R Y U L F = 1400

There areanalogous constraints f o r the other t w o mills:

CL£V:FRA + C1-EV:I*.T + C L K V : L A N + C1J-.V: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 +

P I M S T L + N R R : N & + HTT:LAF = 2900

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

And similarly for the other six factories:

G A R Y D E T + CLEVDTT + M T T D £ T = 1200

G A R Y L A N + CL£V1J\N + P1TT:LAN = 600

GARY W I N + OJBV:WIN + RAR:wiN = 400

G A R Y S T L + CLEV:S1L + HTTÍSTL = 1700

G A R Y » R E + CL-FCV:FR£ + WTTÍBRFC = 1100

GARY1Ü\F + CI£V:LAF + HTT:LAF = 1000

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.

3.2 An A M P L model for the transportation problem


T\vx> fundamental sets o f objects underlie the transportation problem: the sources or
origins (mills. in our e x a m p l e ) and the destinations (factories). Thus w e begin the A M P I .
nnxlel whh a declaration o f these t w o sets:
46 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

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:

param s u p p l y (0K1G} >= 0:


param d«nar>d {DKST} >= 0:

check: sum ( i in ORlG} supplylil = sum ( j in DKSr} dcmandljj ;

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:

F o r a particular o r j g i n i and destination j , s h i p T r a n s [ i . j ] units from i t o j , at a


cost o f c o s t 1 i , j ) per unit: the k>tal cost for this pair is

costli.jl * Trancli, jl

Adding o v e r ali pairs, have the objective funetion:

minimize Total_Cost:
sum ( i i n O R l G . j in DKST} c o s t l i . jl * Transli. jl :

which could also be wrilten ai

sum (j in DKSr. i i n ORlG} c o s t l i . jl * Transli.jl;

orai

sum (i in ORlG} sun (j i n DKST} c o s t l i . jl * Transli.jl:

A s k>ng ai you express the o b j e c t i v e in s o m e mathematically oorrect w a y , A M P l . will soit


out the ternti.
It remains t o speeify the t w o collcctk>ns o f constraints. those ai the or^gins and those
ai the destinations. I f \v\r na me these collcctk>ns S u p p l y and D e s t a n d , their d e c b r a -
tions will stan ai f o l b w s :

subject to Supply (i in ORlG}: ...


subject to Dcmarxi (j i n DKST}:

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

sol ORlG: 4 origins


sol C15-ST ; 4 denL i n a t i o n s
param s u p p l y ( O R l G } > = 0: 4 amounLs a v a i l a b l e aL o r i g i n s
param demand (Dl£Sr} > = 0: 4 amounLs r o g u i r o d a L d e s t i n a L i o n s
check: r.an ( i i n ORlG} supplylil = num ( j in OSST} domandl j ) :
param c o s t ( O R I G . DEST} >= 0: 4 shijxncnL c o s t s p e r u n i t
v a r T r a n r . ( O R l G . DESr} > = 0 ; 4 uniLs t o b e shipped
minimize ToLal_CosL:
num ( i i n ORlG. j i n DESr} c o s t l i . j l * Transi i . j l :
s u b j o c L t o Supply ( i in ORlG}:
sum ( j i n DEST} T r a n s l i . j l = supply[i];
s u b j o c L t o Demand ( j i n DB5JT}:
sum ( i i n ORlG} T r a n s l i . j l = d e m a n d [ j l ;

Figure 3 - t a : Transpor Uflion nnxlel ( t r a n s p . m o d ) .

sum ( j in DESr} Transli.jl

Since w e have alreaJy defined a parameter s u p p l y indexed o v e r origins, lhe amount


a v a i b b l e a t i is s u p p l y l i ) . Thus the oonstraint is

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: OR1G: supply := 4 doíincí: scl *0R1G" and p a r a m "cupply*


GARY 1400
CLKV 2 G00
PITT 2 900 ;

param: DKOT: dcmand := * d o fine.*: " DKST" a n d 'demand-


FRA 900
D AR 1200
LAN 600
WIN 400
STL 1700
FRK 1100
LAF 1000 ;

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

F i g u r c 3 - l b : Data f o r transponaiion nnxlel ( t r a n s p . d a t ) .

l f lhe nnxlel is tíoted in a file t r â n s p . m o d and the data in t r a n s p . d a t , w e can


solve lhe linear program and examine the output:

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 : option aolvor snoptj


ampl: aolvo;
SNOPT 6 . 1 - 1 : O p L i m a i s o l u t i o n í o u n d .
I S i t c r a t i o n s . o b j o c L i v o 19G200
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 THE T R Í W S F C R T A T O N WCC€L 49

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 .

3.3 Other interpretations of the tra ns porta tio n model


A s the nanie suggests. a transponation nxxlel is applicable whenever some material is
being shippcd from a set o f origins *> a set o f destinaiions. Given ccrtain amounts avail-
able at the origins, and required ai the dcstinations. the problem is to meet the require-
ments at a minimum shipping cost.
Viewxxl more broadly. transponation nuxlels do not have to be concerned with the
shipping o f "materiais' \ They can be applied *> the transpoftalionof anything, provkled
that the quantities avaibble and rcquircd can be me&vurcd in some units. and that the
transpor tal ion cost per unit can be determined. They might be used to model the ship-
ments o f automobiles to dealers. for cxampkc. or the movement o f military personnel to
new assignments.
In an even broadcr v i e w , transponation models need not deal with • 'shipping" atalL
The quantities at the origins may be merely associaicd whh various destinations. white
the objective measures some value o f the association that has nothing to do with actually
moving anything. Often theresult i s r e f e r r e d t o a i a n "assignmcnt" model.
A s one panicularly well-known example. consider a depanment that needs to assign
some number o f people to an cqual number o f ofllces. The origins now represent individ-
ual people. and the destinations represent individual ofllces. Since each pcrson is
assigncd one office. and each o f l l c e is occupkrd by one person. ali o f the parameter values
s u p p l y [ i 1 and d e r w i n d [ j ] are I. W e interpret T r a n s [ i . j ] as the " a m o u n t " o f
pcrson i that is assigncd *> o f f i c e j : that is. if T r a n s [ i . j J is I then person i will
occupy o f f i c e j , while if T r a n a [ i . j ] is 0 then pcrson i will not occupy o f f i c e j .
What o f the objective? One possibility is to avk people to ranl the ofllces. giving
their first choice. second choice, and so forth. Then w e can lei c o s t I i . j ] be the rank
50 TRAttSFORTATON W D A S S G W 0 Í T WCC€LS CHífTÇR3

smt OK1C : = Co u l l a r d D a c k i n l l a z o n Itopp I r a v a n i L i n e L s k y


M e h r o L r a N e l s o n S m i l o w i t z Tamhane WhiLo •

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

Figure 3-2: Data for assignmcnt p r o b l e m ( a s s i g n . d ã t ) .

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:

Ne» Yod Ctü&fo TcpeLi


Scjltlc 2500 1700 1800
SiaI>x£o 2500 1S00 1400

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

TTiecost per ton of shipping a s l i b from aplaiK t o a niill is as f d b w t :

GARY CL EV PXTP
KUfMK 12 B 17
Wèd/SK 10 S 13

A l i other dita vahies an? the same as b e f c i e . but with s i i p p l y _ p c L a i n l t p f u l x l as the m u i m i m


fraction o f a p l i n f s supplv thit may be sent to any o n e mill.

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.

3 - 4 . TTiis exeiciseconsiders varutxms o n t h e assignmcnt probk*m introducvd «n Sertion 3JL


(a> Trv rrordering t h : hst o f members o f OEST «n t h : dita ( F i g u r e 3-2K and solving acam. Tind a
reordering that causes your solser t o report a different optimal assignmcnt

<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

( d ) Some p c a p k may h i w scnicrily ihi< cntillr* Ihrm I o gicatcr cun*idLT.i«k»n in i i c i r d n k e o f


o f f i c r . IlvpljLin haw you coukJ cnhancv lhe modcl u « scniarily lc\«l ÓJÀX for each person.
CopyrÍ£ht O O T by Robcrt Fourcr, David M . G « y a n d Brim W. Konçhan

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

4.1 A multicommodity transportation model


T h e transponaiion nxxlcl o f the previous chapar was concerncd with shipping a sin-
gle commodky from origins to destinations. Suppose now that \V>Í are shipping several
dilTerent pnxlucts. W e can define a new set, PROD, whose members represent the differ-
ent productv, and we can add PROD to the indexing o f evety component in the nnxlel: the
resuh can be seen in Figure 4-1. Bccause s u p p l y . d e r u i n d , c o s t , and T r a n s are
indexed over one more set in this version, they take one more subscript: s u p p l y ( i . p ]
for the amount of pnxluct p shipped from orjgin i , T r a n s [ i . j , p ] for the amount o f p
shipped from i D j , and so for th. Even the c h e c k statcment is now indexed over
PROD, so that it verifies that supply cquak demand for each separate pnxluct.
l f we look at S u p p l y . Der^and and T r a n s , there are (origins + destinations) x
(products) constrainfc in (origins) x (destinaiions) x (products) variables. T h e result
could be quite a large linear program, even if the individual sets do not have many mem-
bers. H>r example. 5 origins, 20 destinations and 10 products give 250 constraints in
1000 variables. The size o f this L P is mtileading, however, because the shipments of the
pnxlucts are independem. Thai is. lhe amounts we ship of one product do noi affect the
amounts wecan ship of any other product, t>r the costsof shipping any other pnxluct. W e
would do beiter in this case to solve a smaller transponaiion problem for each individual
pnxluct. In AMPI. terms, w e would use the simple transponaiion nxxlel from the previ-
ous chapter, logether with a dilTerent daia file for each pnxluct.
T h e shuation would be dilTerent if some additk>nal circumstances had the effect of
tying together the different products. As an example. imagine that there are restrictions
on the total shipments o f products from an origin k> a destinaiion, perhaps because of lim-
ited shipping capacity. Toaccommodaie such restrictions in our nnxlel, wxr declare a new
parameter 1 i m i t indexed over the combinaiions o f origins and destinations:

param l i m i t (ORlG.DKSr} >= 0;

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):

s u b j e c t Lo Mui t i ( i i n ORIG. j i n D&ST}:


sum ( p i n PROD} T r a n s l i . j . p l <= l i m i t l i . j l ;

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:

a m p l : izodol xailti .xoodj data zxilti.dat / aolvo;


CPLKX 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 e 199500
41 d u a l s i m p l c x i t c r a L i o n s ( 0 i n p h a s c I J
S E C T tON 4.1 AWULTCCWWC07Y7RÍWSFCRTATONWCCCL 57

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

param s u p p l y ( O R l G . PROD} >= 0 ; 4 amounLc a v a i l a b l c aL o r i g i n s


p a r a m demand (DEST. PROD} >= 0 ; 4 amaunLs r e q u i r e d a L d c s L i n a L i o n s

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:

param l i m i t (ORlG.DESl'} >= 0:

p a r a m c o s L ( O R l G . DE S r . FROD} > = 0 ; 4 shiçment cosLs per u n i t


v a r T r a n s ( O R l G . DEST. FROD} >= 0: 4 units Lo be shippod

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 L o Demand ( j i n DEST. p i n FROD}:


sum ( i i n O R I G } T r a n s l i . j . p l = d c m a n d l j . p ) :

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 ) :

Figure 4-1: MuMioommodity transpor uaion nnxlel ( m u l t i .r>cd).

ampl: diaplay {p in PROD) i {i in ORIQ, j in DEST) Trona [ i , j , p) 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

s e t OKI Cl í = G>\KY CLKV P I T T :


s e t DKST : = FRA DBT LAN WIN S1'L FRB LAF
s e t PROD : = b a n d s c o i l s p l a L e ;

param s u p p l y (LrJ : GARY CLHV PITT :


bands 4 00 700 eoo
coils 800 1G00 1800
p i a Lc 2 00 300 300 ;

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 : =

l *, * . baixisl : FRA DKT LAN WIN SV L FRK LAF : =


OARY 30 10 8 10 11 71 6
CLKV 22 7 10 7 21 82 13
PITT 19 11 12 10 2S 83 15

l*.*.coilsl : FRA DKT LAN WIN SV L FRK LAF : =


OARY 39 14 11 14 16 82 8
CLKV 27 9 12 9 26 95 17
PITT 24 14 17 13 28 99 20

l *. * . p l a L c j : FRA DKT LAN WIN SV L FRK LAF : =


GA.KY 41 IS 12 16 17 86 8
CLKV 29 9 13 9 28 99 18
PITT 26 14 17 13 31 104 20 ;

Figure 4-2: Multicommodity transponationproblem data ( « m l t i . d a t ) .

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

smt PttDD: 4 prodixrLs


param T > 0: i number o £ wcokr.
param r a t e {PttDD} > 0: * tons p e r bour produced
param a v a i l ( 1 . . T } > = 0: * b o u r s a v a i l a b l e i n wook
param p r o f i t (PROD, 1 . . T } ; * p r o í i t p e r Lon
param markeL {PROD. 1 . . T } >= 0 ; i l i m i L o n t o n s s o l d i n week

v a r Make ( p in PROD. t in 1..T} >= 0. <= markeL [ p . t j :


* tons produced
maximize T o t a l _ P r o £ i t :
sum ( p i n PROD. t i n 1 . . T } profitlp.tj * Makelp.tJ;
i total proíits £rom a l i products in a l i weeks

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

Figure 4-3: ftroduction model rcplicaicdover pericxls< s t e e l T O .r>cd).

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.

4.2 A multiperiod produetion model


Another common way in which nnxlels are expanded is by replicating them o v e r time.
T o illustraic, w e conskler how the mixlcl o f Figure I - l a might be used to plan pnxluction
for the next T weeks, rather than for a singkr week.
W e begin by adding another index set to most o f the quantities o f inteiest. The added
set represents weeks numbered I through 7', ai shown in Figure 4-3. T h e expression
1 . . T is AMPI/s shonhand for the set o f integers from I through T . W e have replicated
ali the parameters and variables over this set, except for r a t e , which is regardedas fixed
over time. As a result there is a constraint for each week, and the p r o f i t terms are
summcd over weeks ai wvll as products.
S o far this is merely a se para te L P for each week, unkrss somcthing is added k> tie the
wxreks together. Just ai \v\rre able to find constraints that involved ali the products, w »
60 BULDP*3LA«3ERWCC€LS CHÉFTCR4

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:

v a r Make (PROD. 1. . T } > = 0 :


v a r I n v ( P R O D . 0 . . T } >= 0:

var Sol 1 (p in PROD. t in 1..T} >= 0. <= marketlp.tj;

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:

param i n v O (PROD} >= 0;

A simple cx>nstraint guarantees thai the variables I n v [ p . 0 ] take these values:

subject Lo l n i t _ l n v (p i n PROD}: lnvlp.01 = invOlpl :

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:

param r e v e n u e (PROD. 1. . T } > = 0 :


param p r o d e o s t (PttDD} >= 0:
param i n v e o s t (PROD} > = 0 ;

These are incorporaicd intothe objective ai f o i b w s :

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

ampl: option diaplay lcol 0;

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

soL PROD: < produets


param T > 0 ; * number o £ w e e k s
param r a L c (PROD} > 0 : * tons per hour produced
param invO (PROD} > = 0: 4 i n i t i a l inventory
param a v a i l ( 1 . . T } >= 0: * h o u r s a v a i l a b l e i n wook
param m a r k e t (PROD. 1. . T } 0: i l i m i t o n t o n s s o l d i n wook
param p r o d c o s t (PttDD} > = 0 : * c o s t per ton produced
param i n v c o s t (PttDD} >= 0: * c a r r y i n g c o s t / t o n o£ i n v e n t o r y
param r e v e n u e (PROD, 1 . .T } >= 0; i r e v e n u e p e r Lon s o l d
v a r Make ( P K 0 D . 1 . . T } >= 0: * tons produee d
v a r I n v (PROD. 0. . T } > = 0 : * tons invenLoried
v a r Se 11 ( p i n PttDD. t i n 1 . . T } >= 0 . < = m a r k e t l p . t j : i Lons sold
maximize T o t a l _ P r o f i t :
sum ( p i n PROD. t i n 1. . T } ( r e v e n u e l p . t ] * S e l l l p . t | -
p r o d c o s t lp 1 * Make lp . 11 - i n v c o s t l p ] * I n v l p . t ] J:
i T o t a l revenue less costs in a l i weeks
s u b j e c t t o Time ( t in 1 . . T } :
sum ( p i n PROD} ( l / r a t e IplJ * Makelp.tJ <= a v a i l [ t j ;
i Total oí h o u r s used by a l i produets
rt 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 e a c h week
subject to lnit_lnv (p in PttDD} : lnv[p,0J = invOlp]:
* Initial i n v e n t o r y musL e q u a l g i v e n value
s u b j e c t t o B a l a n c e ( p i n PttDD. t i n 1 . . T } :
Makelp.t] + Invlp.t-1) = Sell[p.tJ + Invlp.tJ;
* T o n s p r o d u e e d and t a k e n í r o m i i r / c n L o r y
* must © q u a l t o n s s o l d and p u t i n L o i n v e n L o r y

Ffeure 4-4: Muhiperiod produetion nnxlel < s t e e l T . r » c d ) .

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 •

Figure 4-5: Daia for multiperiod píoduclion nnxlel < a t e e l T . d a t ) .


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 63

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.)

4.3 A model of produetion and tra ns porta tio n


Large linear programs can be creatcd not only by tying together small nuxlels of one
kind. ai in the two exampkrs above, but by linking dilTerent kinds o f nxxlels. We con-
clude this chapter with an example that combines features of both pnxluction and trans-
ponation mixlcls.
Suppose thai the steel pnxlucts are made ai several mills. from which they are shipped
to customers ai lhe various factories. For each mill we can define a separaie pnxluction
nnxlel k> optimi/e the amounts of each pnxluct to make. K>r each pnxluct we can define
a separaie transponation model. whh mills ai origins and factories as destinaiions. to
optimi/e the amounts o f the pnxluct to be shipped. We would like to link ali these sepa-
rate nnxlek into a single integrated model of pnxluction and transponaiion.
T o b e g i n . we replicate the pnxluction model o f Figure M a over mills — that is. ori-
gins — raiher than over weeks ai in the previous example:

s e t PttDD: * products
s e t 0K1Q: i origins (steel millsj

param r a t e (ORIG, PROD} > 0: i t o n s p e r haur a t o r i g i n s


param a v a i l (QR1G} > = 0: * hours a v a i l a b l e at o r i g i n s

v a r Make (ORIG. PROD} > = 0 ; i tons produced a t origins

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 e t ORIG; i origins (steel millsj


s e t DBST: i destinations <íactoriesJ
s e t PttDD: * products

param s u p p l y (OR1G.PWDD} >= 0: * tons a v a i l a b l e at o r i g i n s


param demand (DEST.PWDD} >= 0: * tons required at d e s t i n a t i o n s

var Trans (ORIG. DESV. PttDD} >= 0; * tons shippod


64 BULDP*3LA«3ERWCC€LS CHÉFTCR4

s e t ORlQ: 4 origins (sLeel millsJ


s e t DEST: * desLinaLions (facLoriesJ
s e t PttDD: * producLs
p a r a m r a t e ( O R I G . PROD} > 0 : * Lons per hour aL o r i g i n s
p a r a m a v a i l ( O R I G } >= 0 ; * h o u r s a v a i l a b l e aL o r i g i n s
p a r a m demand (DEST, PROD} >= 0 ; i Lons r o ^ u i r o d aL d e s L i n a L i o n s
p a r a m make c o s t ( O R I G . PROD} > = 0 ; * manu f a c L u r i n g c o s t / L o n
p a r a m L r a n s _ c o s L ( O R I G . DEST. PttDD} >= 0 ; * shipping cosL/Lon

var Make (ORIG.PROD} > = 0: A L o n s p r o d u c e d aL origins


var T r a n s ( O R I G . DEST. PROD} >= 0: * Lons s h i p p e d
minimize ToLal_CosL:
sum ( i i n ORIG, p i n PttDD} m a k e _ c o s L l i . p l * Makeli.pl «-
Sum ( i i n O R I G . j i n DEST. p i n PROD}
L r a n s _ c o s L l i . j . pl * Trans l i . j . p l :
subjecL t o Time ( i in ORIG}:
sum ( p i n PROD} ( 1 / r a L e ( i . pl J * M a k e l i . p l <= availlij;
s u b j e c L L o S u p p l y ( i i n ORIG. p i n PROD}:
sum ( j i n DEST} T r a n s ( i , j , p l = M a k e ( i . p l :
s u b j e c L L o Demand ( j i n DEST. p i n PROD}:
sum ( i i n O R I G } T r a n s l i . j . p l = d e m a n d l j . p | :

Figure 4-6: Pioduction/tiansportation model, 3rd version ( s t e e l ? . r » c d ) .

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 :

s u b j e c L Lo Demand ( j i n DEST. p i n PROD} :


sum ( i i n O R I G } T r a n s l i . j . p l = d c m a n d l j . 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

s e t OR1G í = G>\KY CLKV P I T T :


s e t DKST : = FRA DBT LAN WIN S1'L FRB LAF •
s e t PttDD : = b a n d s c o i l s p i a Lo ;

param a v a i l := OARY 2 0 CLKV I S PITT 20 ;

param dcmand (LrJ :


FRA DBT WIN STL FRK LAF :
bands 300 300 100 7S 6S0 22 S 2 S0
coils SOO 7 S0 400 2 S0 9S0 eso SOO
p i a Lo 100 100 0 SO 200 100 2 S0 :
param r a L e <Lr): GARY CLKV PITT j r
bands 200 190 230
co x i s 140 130 160
plaLe 160 160 17 0
param make c o s L < LrJ :
OARY CLKV PITT :=
bands 180 190 190
coils 170 170 180
plaLe 180 18S 18S :

param t r a n s _ c o s L :=

l » . * ,bandsl : FRA DBT LAN WIN SVL FRK LAF


OARY 30 10 8 10 11 71 6
CLKV 22 7 10 7 21 82 13
PITT 19 11 12 10 2S 83 IS

.coilsl : FRA DBT LAN WIN SVL FRK LAF


OARY 39 14 11 14 16 82 8
CLKV 27 9 12 9 26 95 17
PITT 24 14 17 13 28 99 20

1».* .plaLe! : FRA DBT LAN WIN SVL FRK LAF


OARY 41 IS 12 16 17 86 8
CLKV 29 9 13 9 28 99 18
PITT 26 14 17 13 31 104 20

FÍRurc4-7: D a t a f o r produciion/transponation nxxlcl ( s t e e i P . d a t ) .

R e v i e w i n g thfc formulaiion. itiight observe ihai, according to lhe S u p p l y d e c h -


ratk>n. the nonncgative expression

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 : j s o d o l atoolP.aod; data atoolP.dat/ aolvoj


CPLEX B . 0 . 0 : op L i m a i s o l u L i o n : o b j e c L i v e 1392175
27 d u a l s i m p l e x i L e r a L i o n s ( 0 i n p h a s « 1J

ampl: option diaplay lcol 5/


ampl: option arzit zoro roxts 1, oxait zoro cola lj

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:

ampl: diaplay s u e ( i in ORIG, p i n PROD^


oako coat[i,p] • Jía*o/i,p;/
sum(i i n O R I G . p i n PROD} makc c o s L l i . p i *Make l i . p l = 1215250

ampl: d i a p l a y sun ( i in ORIG, j in DE ST, p in PROD)


trans coot [ i , j,p) • Trano [ i , j , p);
s u m ( i i n O R I G . j i n DBCT, p i n PWDD}
L r a n c _ c o s L l i . j . p l ' T r a n s i i . j . p l = 176925

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:

/ number o f produclion lines: nuLÜmuni number a f c x c w s that can w a k in any shift


rp produ^kin vale for producl p . i n e r c w hours per 1000 boxes
HR number o f hours thit a CTCW wcrks in plonmng periad i

The folloiving dita u e d i t r u i i m l by market <r managerial considerotkiro:

WT total wages for a CTCVT o n diift x in o n e period


d^ dcnianJ for producl p th A must b e m d in period 1
.1/ maximum ctiaqge «n number of e r r v * empk»\x-d í n n i o n e period t o t h : nexl

l h e decnkin variables o f t h : mo dei ãxc:

A' (r £ d^ total boxes (in l ( K K K ) o f producl p tukcd in periad 1


0 nuniber o f c r e w s empk»\vd o n s h i f t x in period 1

l h e o b j e d i w n IO mi ri mi/r the fctlil cosi of ali cvews empki\vd.

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*.

X K £ f#J| Y a , for each i = 1 T.

The charçge in nuniber OFCTCWS is resineied by

-.1/£ £ £ .W, f o r each i = l , . - , r - l .

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?

<b) T o bc c o m i d e n l . you should i k o require at moct a charçge o f .1/ b e t « c v n t h : known m ü u l


numba o f crews (abeady empki\ed in the period befoie the first) and the nunibcr of c i e w x to bc
employed m the first piinnirçg period. A d d a provi si an for this restrictian to the model.

Rc solve with 11 milül crews. Y o u shoukJ gctthe « m e sohitian.

( 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:

parair. prob f l . . S ) > - 0, < - 1;


0.99999 < flUr, ffl í n 1 . . S ) p r o b [ f l ] < 1.0Q001;

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).

( c ) The f b n n u M ú n in ( b ) i s no improvemenl because it makes no coancctian bctwecn th- somar


ias. One w a y lei make the model u*ible is to adJ "ncmanticipitÍN-ity" cxnstraxnt^ thit rcquire each
wvek 1 varubk- lei be SÍNX.TI th- some value OCKKS ali scmaricis. Thetl the n.-suk w i l l g i v e yau the
bett sii^gk: stralcgy f<r the first wvek. in the s e m e o f maximi/ins expccled pr<»fit f<r ali weeks.
H i e stra%:cx's u-ill still diverge a t e r th- first v.vck — but a weck f r o m nciw you can updat: your
d J a and run the sfcichistic program a^iin ki fienerjte a second weck's s m t e g y .
A reinmticipativit)' constraint kw the M a k e variables canbe written

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 ] ) ;

Which x c e n r i o will be nurst pj\ifítibk.\ JLIKJ which will be kMstprofitibk:?


Rcpe.it éic analyâx with prohtfnlitíes af 0 . C K 1 0 1 . O J C K K I 1 JLJKJ 0 . 9 9 9 8 for scvfiaríos 1, 2 and 1 You
shciuld fiixJ that profit from xlrategy 3 goes up, but profits from éie othcx two g o down. HxpUxn
what thcsc profits rcpresent, xixi why th: rcsulfc an: what you woukl cxpcct.
CopvrishtO 3 K B by Robcrt Fourcx. David M . Oay and Brian W . K a n ç h v i

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

5.1 Unordered sets


T h e most elementary kind o f A M P L set is an unordered collection o f character strings.
Usually ali o f the strings in a set are intended t o represem instances o f the same kind o f

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:

A list o f reserved words is given in Section A . I .


A declared set's membership is norma D y specified as part o f the data for the nnxlel, in
the manner t o be described in Chapter 9: this separation o f nnxlel and data is recom-
mended for most mathematieal programming applieations. Occask>nally, however, it is
desirable t o refer t o a particular set o f strings within a nnxlel. A literal set o f this kind is
specified by listing hs members within braees:

(-bands". -coils". -plaLe-}

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:

set PROD = ( "bands-. -coils". "plaLo" }:

This sort o f declaration is best limited t o cases where a s e f s membership is small, is a


fundamental aspect o f the n n x l e l or is not expected t o change often. Nevertheless wvr
will see that the = phrase is o f t e n useful in set decbrations, f o r the pur pose o f defining a
set in terms o f other sets and parameters. T h e operator = may be replaeed by d e ü a u l t
t o initiali/e the set while allowing its value t o be overridden by a data statement or
changed by subsequent assignments. These options are more importam for parameters,
however, s o w e discuss them m o i e fully in Sectk>n 7,5.
N o t i c e that A M P L makes a distinction betwaen a string such as ' b a n d s " and a set
like { • b a n d s ' > that has a membership o f one string. T h e set that has n o members < the
empty s e t ) is denoted {}.
SECT C N 5 2 SETSOFNUWeSíS 75

5.2 Sets of numbers


Sei members may also be numbers. In fact a sef s members may bea mixture o f num-
bers and strings. though this is seldom the c a i e . In an A M P L model. a literal number is
wrfcten in the customary way ai a sequence o f digito, optionally preceded by a sign. con-
taining an optional decimal point and optionaDy foQowed by an exponent: the exponent
oonsists o f a d . D, e , or E. optionally a sjgn. and a seque nce o f digits. A number ( 1 ) and
the cor respondi ng string ( ' 1 ' ) are distinct: by contrast. different represe nu tk>ns o f the
same number.suchas 1 0 0 and l E * 2 , s t a n d for the same set member.
A set o f numbers is often a sequcncc that corresponds to some progrcssion in the situ-
ation being modckrd. such ai a series o f weeks or ycars. Just as for strings. the numbers
in a set can be specified as part o f the data. or can be specified within a model as a list
betwxren braces. such ai { 1 . 2 . 3 . 4 . 5 . 6 } . This sort o f set can be described mote con-
cisely by the notation 1 . . 6. An additional b y clause can be used to specify an interval
other than I betwcen the numbers: for instance.

1990 .. 2020 by S

tepresents the set

(1990. 199S. 2000. 200S. 2010. 201S. 2020}

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:

s e t YKARS = 1990 .. 2020 by 5:

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:

If subsequently ws te t o g i v e the data as

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

then Y E A R S would be the same set ai in the pceviotis e x a m p l e <as it would a l s o be if e n d


w e i e 2023.) Y o u may use any arithmetic expression t o represem any o f the values in a
.. expression.
T h e members o f a set o f numbers have the same properties as any other numbers. and
hence can be used in arithmetic expressions. A simple example is seen in Figure 4-4,
where the material balance constraint is declared ai

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:

Because L runsover the set 1 . . T , w e c a n write I n v [ p . t - 1 ] t o represem the inventory


ai the end o f the previous wvek. l f t instead ran over a set o f strings. the expressk>n t - 1
would be rejected as an error.
Set members need not be iniegers. A M P I . aitempts t o store each numerical set mem-
ber ai the nearest repr esentable lloaiing-point number. Y o u can see h o w this works out
on your comptiter by trying an experiment like the f o l l o w i n g :

a m p l : option díaplay ifidth 30j


a m p l : diaplay -3/3 . . 5/3 by 1/3j
m l - S / 3 . . 5/3 b y 1/3 : =
-1.6666666666666667 0. 33333333333333326
-1.3333333333333335 0. 6666666666666663
-1 0.999999999999999*
-0.6666666666666667 1.3333333333333333
-0.3333333333333335 1.6666666666666663
- 2 . 2 2 04 4 6 0 4 9 2 5 0 3 1 3 o - 1 6 :

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.

5.3 Set operations


A M P I . h^i four operators that constmct new sets from existing ones:

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

T h e f o l l o w i n g excerpt f r o m an A M P I . sessk>n shows h o w these work:


S E C T G N S.3 SETOFERATCttS 77

a m p l : aat Yl - 1990 .. 2020 by 3;


a m p l : aot Y2 - 2000 .. 2023 by 3;
a m p l : d i a p l a y Yl union Y2, y l i x a t o r M /
KCL Y l u n i o n Y2 : = 1990 199S 2 0 0 0 200S 2 0 1 0 201S 2 0 2 0 2 0 2 5 :
s e t Y l i n L e r Y2 : = 2 0 0 0 200S 2 0 1 0 201S 2 0 2 0 :
a m p l : diaplay Yl d i f f Y2, Yl ayadiff Y2;
m l Y l d i í í Y2 : = 1990 1995:
M L Y l s y m d i f f Y2 : = 1990 1995 2 025:

The operands o f set operators may be other set expressions, allowing more compkrx
expressions to be built up:

a m p l : diaplay Yl ayxzdiff (Yl aymdiff Y2) j


m l Y 1 s y m d i f f < Y l s y m d i f f Y2J : =
2000 200S 2010 2015 2020 2025:

a m p l : diaplay (Yl union {2025,2035,2045)) diff Y2;


m l Y l union ( 2 0 2 5 . 2 035. 204 5 } d i í f Y2 : =
1990 1995 2 03 5 2 045:

a m p l : diaplay 2000.. 2040 by 5 ayadiff (Yl union Y2)j


m l 2 000 . . 204 0 by 5 s y m d i f í ( Y l u n i o n Y2J : =
2030 203 5 2 04 0 1990 1995:

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

A precedence hierarchy o f ali A M P L operators is given in Table A - l o f Section A . 4 .


Set operations are often used in the assignment phrase o f a set declaration. to define a
new set in ter ms o f already dccbrcd sets. A simple example is provided by a variaik>n on
the diet nnxlel o f Figure 2-1. Rather than specifying a k>wer limit and an upper limit on
the amount o f every nutri? nt, suppose that you want to specify a set o f nutrients that have
a lower limit and a set o f nutrients that have an upper limit. (Every nutrient is in one set
or the other: some nutrients might be in both.) You oould declare:

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:

M L NITTR = MINRHD u n i o n MAXRKQ:


78 S HFLE S E T SAf*}N D E X N G CHífTÇRS

M L M1NREQ; A nuLrionLs w i L h minimum r o q u i r c m e n L s


SOL MAXRKQ : i nuLrionLs w i L h tnaximutn r o q u i r c m c n L s
SOL NUTR = MIWRBO u n i o n MAXRKQ: * nuLrionLs
s o L FOOD; A íoods
param c o s L (FOOD} > 0:
param £ _ m i n (FOOD} > = 0 ;
param £ max ( j i n FOOD} > = £_min(jj :
param n j n i n (MINRKQ} >= 0:
param n max (MAXRBQ} >= 0:
param amL (NUTR. FOOD} >= 0;
var Buy (j i n F00O} >= £_min(jl. <= £ maxljl:

minimize ToLal_CosL: sum ( j in PCX) D} cosL(j) * Buyljl:


s u b j o c L Lo D i o L _ M i n ( i i n M I M R B 0 } :
sum ( j i n FOOD} a m L l i . j l * Buyljl >= n_min(i|:
s u b j o c L Lo D i o L Max ( i i n MAXRHQ}:
sum ( j i n FOOD} a m L l i . j l * Buyljl <= n maxlil:

F i g u r e 5-1: Diet model using u n i o n operator < d i e t u . r > c d ) .

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,

param n jnin (M1MRDJ} >= 0;


p a r a m n max (M*\XRl^)} >= 0;

while the amountv o f nutriente in the ftxxls are indexed o v e r N U T R :

p a r a m amL (NtrrR.FOOD} >= 0:

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.

5.4 Set membership operations and funetions


T w o other A M P L operators. i n and w i t h i n . test the membership o f sets. A s an
example, theexpression

"*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.

5.5 Indexing expressions


In algebraic notation. the use o f sets is indicated informally by phrases such ai " f o r
ali j € P " or " f o r / = 1 7 " or " f o r a l i ; eR such that c} > 0 . " T h e A M P l . oounter-
part is the indexing expiexxiún that appears within braccs { . . . | in nearly ali o f our e x a m -
ples. A n indexing exprcssion is used whenever s p e c i f y the set over which a model
component is indexed. or the set over which a sum mal ion runs. Since an indexing
exprcssion defines a set, it can be used in any p b c e where a set is approprbte.
T h e simplest form o f indexing exprcssion is just a set name or exprcssion within
braccs. W e have seen this in parameter deciarations such ai these from the multiperiod
pnxluctk>n model o f Figure 4-4:

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

param í _ m i n (FOOD} > = 0:


param £ max ( j i n FOOD} > = £_minljj :

and on variables:

v a r Buy (j i n FOOD} >= £ _ m i n [ j l . <= £ o v a x l j l :

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

(j in FOOD: f maxlji - f_minljl < 1}

describes lhe sei o f ali fcxxls whose minimum and ma xi muni amounts are nearly the
same. and

(i i n NITFR: i i n MAXRKQ o r njninlil > 0}

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

s e t NITTRBQ = ( i i n NITTR: i i n MAXRHQ o r n _ m i n [ i ) > 0}:


s e t NITTRBQ = MAXRKQ u n i o n ( i i n MINRKO: n _ m i n [ i l > 0}:

to define NUTRBQ to represent our precxrding example o f a set expression. and you could
use either o f

s e t B0T11RKQ = ( i i n MINRKQ: i i n MAXRKQ} :


s e t B0T11RKQ = M1NRDJ i n L e r MAXRKQ:

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: xzodol dia tu .aodj


ampl: data diotu. dat j

a m p l : diaplay MJíXREQ union {i in KIKREQ: n xsdn[i) > 0);


s e t MAXRKQ u n i o n ( i i n M I N R l * ) : n _ m i n l i l > 0 } : = A NA CAL C:

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 : diaplay { j in FOOD: Buy[j) > f sdn[j))/


s e L ( j i n FOOD: B u y l j l > £ _ m i n l j l > : = CllK >tt'L SP3:

a m p l : diaplay ( i in KIKREQ: Diot Nin[i). olack * 0);


s e L ( i i n MINRKQ: < D i e t _ M i n [i\ . s l a c k j == 0 } : = C CAL:

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 :

param: cosi £_min f max :=


BKHF 3.19 2 10
Cl IX 2.S9 2 10
FISH 2.29 2 10
HAM 2.B9 2 10
1.89 2 10
Jfl'L 1.99 2 10
SP3 1.99 2 10
TUR 2.49 2 10 •

param: n_min n max : r


A 700 2 0000
C 700
131 0
B2 0
NA . 50000
CAL 16000 24000 •

param amL <trj : A C Bl B2 NA CAL :


BKKF 60 20 10 15 938 295
ciix e 0 20 20 2180 77 0
FISll 8 10 IS 10 945 44 0
MAM 40 40 35 10 278 430
MCT1I IS 35 IS 15 1182 315
MI'L 70 30 15 15 896 400
SPG 25 SO 25 15 1329 37 0
TUR 60 20 15 10 1397 450 :

Figure 5-2: Data for diet nnxlel < d i e t u . d ã t ) .

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).

5.6 Ordered sets


A n y set o f numbers ha* a natural ordering. so numbers are often used k> represem
entities, like time periods, whose ordering is essential tothe specificatk>n o f a nnxlel. T o
SEC7CN56 CFC€FED3ETS 83

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:

and ali subsequent oceurrences o f 1 . . T are replaced by WEEKS. In the B a l a n c e con-


straint, the expression t - 1 is replaced by p r e v { t >, which seleets the member before t
i n t h e s e f s order ing:

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:

error p r o c e s s i n g c o n s t r a i n t B a l a n c e [ ' bands • 2 7 sep ' 1 :


c a n ' t c c m p u t e p r e v < ' 2 7 s e p ' . WEEKS) —
' 2 7 n e p ' i s t h e f i r s t member

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 regular balance constraint ti limited to the remaining weeks:

s u b j e c t t o B a l a n c e ( p i n PROD. t i n WEEKS: o r d ( t ) > 1>:


Make l p . t l + 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 ;

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

p a r a m p r o d e o s t (PttDD} >= 0: i c o s t p e r Lon p r o d u c e d


p a r a m i n v e o s t (PROD} > = 0: * carrying cost/ton o £ inventory
p a r a m r e v e n u e (PROD.WKIiXS} > = 0 : 4 revenue/ton sold
var Make (PROD.WBKKS} >= 0: * tone produced
var I n v (PttDD. WKlíXS} > = 0: * tons inventoried
var S e i 1 ( p i n PROD. t i n WKKKS} > = 0 . <= m a r k e L l p . t j : * tons sold

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

Figure 5-3: Produetion model with ordered sets < s t e e l T 2 . r > c d ) .

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

sol PROD : = bands: c o i l s :


set WEEXS : = 2 7 s e p 0 4 o c t 1 l o c L lBoct •

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 :

param p r o d e o s t : = bands 10 coils 11 :


param i n v e o s t : = bands 2.S coils 3 :
param r e v e n u e : 27scp 04oct lloct lBoct
barxis 25 26 27 27
coils 30 35 37 39
param ma r k e t : 27scp 04oct lloct lBoct
bands GO 00 GO 00 4 000 6500
coils 4000 2500 3 500 4200

Figure 5-4: Data for production mixlel < s t e e l T 2 . d a t ) .

ratk>ns wxrre c i r c u l a r . In ali o f these funetions. the first argument mustevaluate to a


number or string. the second argument k> an ordered s e t and the third to an integer. Nor-
mally the integer ti positive, but zero and negative values are interpretei in a consistem
w a y : for instance, n e x t { t . WEEKS. 0 > is the same as t , and n e x t { t . WEEKS. - 5 > is
the same ai p r e v { t . WEEKS. 5 ) .
Final ly, there are functk>ns that return the poshion o f a member whhin a s e t The
expression o r d { t , WEEKS} returns the numerical poshion o f t whhin the set WEEKS.
or gives you an error message if t is not a member o f WEEKS. The alternative
o r d O { t . WEEKS} is the same except that it returns 0 if t is not a member o f WEEKS.
For these funetions the first argument must evaluate to a positive integer. and the second
to an ordered set.
I f the first argument o f n e x t , n e x t v . p r e v , p r e v v , or o r d isa dummy index that
mns over an ordered set, its associatcd indexing set is aisumed if a set is not given as the
second argument. Thus in the constraint

s u b j e c t t o B a l a n c e ( p i n PROD. t i n WEEKS: o r d < t J > 1 } :


Makelp.tl + Invlp .prev <tj 1 = S e l l l p . t l + I n v l p . t J ;

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 ;

s o L WBH2CS = (L in ALL_WKKKS: ord(Lj <= T } ordered by ALL.WEHXS;

W e s p e e i f y o r d e r e d b y A L L _ W E E K S s o that WEEKS beeomes an ordered set. with its


members having the same ordering as they d o in À L L _ W E E K S . T h e o r d e r e d b y and
circulâr by phrases have the same efTect ai the w i t h i n phrase o f Section 5.4
together whh o r d e r e d or c i r c u l a r , except that they also cause the declared set t o
inherh the ordering from the containing set. There are a l s o o r d e r e d b y reversed
and c i r c u l a r b y r e v e r s e d phrases, which cause the declared s e f s ordering t o be
the opposite o f the containing s e f s ordering. A l i o f these phrases may be used ehher
with a subset supplied in the data. i>r with a subset defined by an expression as in the
example above.

Predefined sets and interva! expressions

A M P L provides special names and expressions f o r certain c o m m o n intervals and other


sets that are either infinite or potentially very large. Indexing expressions may not iterate
over these sets. but they can be convenicnt for s p e c i f y i n g the condhional phrases in s e t
and p a r a m declaralions.
A M P L intervals are sets containing ali numbers between t w o bounds. There are inter-
vals o f real <fk>aiing-point) numbers and o f integers. introduced by the keywords
i n t e r v a l and i n t e ^ e r respectively. They may be specified as ckxsed, open, or half-
open, f o l l o w i n g standard mathematical notation.

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

lhe keyword i n t e r v a l may be omitted.


A s an cxamplc, in decbring Chapvrr I 's paramctcr r a t e . you can declare

param r a L e (PROD} in inLorval <0 .nvaxraLe J :

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

param r a L e (PROD} in (O.maxraLcl:

or equivalenily ai

param r a L e (PttDD} > 0. <= m a x r a L e ;

An open-ended interval can be specified by using lhe predefined A M P L parameter


I n f i n i t y ai the right-hand bound, or - I n f i n i t y as the left-hand bound, so that

param r a L e ( PROD} in ( 0. I n í i n i Ly 1;

mcans exactly the same thing a*

param r a L e (PROD} > 0:

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

livpljLin Any evidma? af rciurxl mg error in yotr coaifaitcr'* aritfimctic.


88 S H F L E S E T S Af*} N D E X N G CHífTÇRS

<b) Trv t h : following commancfc fam Sections 5.2 and 5 4 o n your computer:

anpl: M t HLOfi - 1 . • 1#7/


anpl: diapléy card (HUCE) /

W h e n A M P L rum out o f memory. h o w many b j t e s does * » y w n ? availibk-? (If your computer


nrally does h i v e enough memory, try 1 . . I e 8 . ) Espcrimenl to sec how big a set \TJGE your a i m
puta- can h:>kl without runniqg <,ut memory.

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.

5 - 3 . U t e t h : d i . c p l a y commaixJ. fcigether with irxlexing exprewioro as demonstraled in Scction


5 5 , Io determine the folkiwirç; sets rx-liting Io the dirt model of Fçurex 5 1 and 5-2:
- Ixxids thit h i v e a unit catt greatex than 52XK1.
- Ixxids that have a sodhim (NA)eontent o f nure than KKK).
- 1'ocids thit contribute mere thin 110 lo the fcitil ocut in the optimal solution.
- Ixiock that an? purclused at nure thin the nünimum le\el but lew thin the maximum l e w l «n
the optimal sohition.
Nutrients thit the tipfmaldkt supplies in exactly the núnmium alkiwabk- amount
Nutrients thit the optimal d k t supplies in exactly the maximum aUowaMcamount.
Nutrients thit the Optimal d e t supplies «n nwre thin the minimum alkiwabk- amount but l e w
than the maximum allcvwafale anwiunt.

5 - 4 . Thrs exercwe refers Io the mukiperkid produetion nuxlel of Figure 4


( a ) Suppote thit w e define twoadcfitional s c a l a i p n m e t e n ,

parair. Cfcaqín l n t e ç a r > - 1;


parair. Twnd i n t a g a r > <- T;

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.

porair. Caçg intagar >- 1;

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.

5-6. M a d i f y the model of Figure 5 3 to merge the B a l a n c o O anJ B a l a n ç o constramfe. as «n


figure «i-4. liint: D. . T a n d 1 . . T an: araüqgous ki

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

M a u linear programming m o d e b in v o l v e indexing o v e r c o m b i n a i i o n s o f m c m b e r s


f r o m several diíTerent sets. Indeed. the interaction o f indexing sets is often the most c o m -
plicaied aspeet o f a m o d e l : once y o u h a v e the arrangement o f sets w o r k e d out, the rest o f
the model can be written ckrarly and concisely.
A l i but the simples! m o d e l s e m p l o y c o m p o u n d sets w h o s e member s a r e pairs, triples,
quadruplcs, or e v e n longer " t u p l e s " o f objects. T h i s chapter begins with the declaraiion
and use o f sets o f ordered pairs. W e concentrate first on the set o f ali pairs from t w o s e n .
then m o v e on t o subsets o f ali pairs and t o " s l i c e s " through sets o f pairs. Subsequent
soctions explore sets o f longer tuples, and extensions o f A M P L * s set operators and i n d e x -
ing expressions t o sets o f tuples.
T h e final section o f this chapter introduces sets thai are declared in collections
indexed over other sets. A n indexed colleetk>n o f s e t s o f t e n p b y s much the same role a*
a set o f tuples. but it representa a s o m e w h a t diíTerent w a y o f thinking about the f o r m u l a -
tion. Each kind o f set fc appropriate in certain situatk>ns, and w e o f l e r s o m e guidelines
for c h o o s i n g b e t w e e n t h e m

6.1 Sets of ordered pairs


A n ordered pair o f o b j e c t s , whether numbers o r strings, is written with the objects
separatcd by a c o m m a and surrounded by parentheses:

< - P I T T - . -STL-J
(-bandas". Sj
(3.101)

As the term "ordered" sug^ests, it makcs a difTerence w h i c h object c o m e s first;


< ' S T L ' . •P I T T ' ) is not the same as { 'PITT'. 'STL'}. T h e same object m a y
appear both first and s e c o n d , i n {' PITT'. • PITT'>.
Pairs can be c o l l e c t c d into sets. just like single o b j e c t s . A comma-separated list o f
pairs may b e e n c l o s e d in braces t o d e n o t e a literal set o f ordered pairs:

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}

Variouscollections o f nnxlel components, such av the parameter r e v e n u e and the vari-


able S e l l , are indexed over this set. W h e n individual components are referenced in the
nnxlel, they must have t w o subscripts, ai in r e v e n u e ( p . t j or S e l l l p , t ) . The
order o f the subscripts is ahvays the same as the order o f the objects in the pairs: in this
case the first subscript must refer to a string in PROD, and the second to a number in
1. .T.
A n indexing expression like ( p i n PROD. t i n 1 . . T ) isthe A M P L transcription o f
a phraie like " f o r ali p in /= I T M from algebraic notation. There is no c o m -
peli ing rcason to think in ter nu o f ordered pairs in thiü caie, and indeed W Í did not men-
tion ordered pairs when introducing the multiperiod produetion nnxlel in Chapter 4. On
the other hand. w e can nnxlify the transpor tatk>n nxxlel o f Figure 3- Ia to cmphaüize the
role o f origin-destination pairs as " l i n k s " between cities, by defining this set o f pairs
explicitly:

s e t LINKS = (ORIG . DK5?r } :

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

sei ORlG: 4 origins


sot DE57T: 4 d e s t i n a L i o ns
s e L LINKS = (ORlG, DEST}:

param s u p p l y (ORlG} >=0: 4 amounLs a v a i l a b l e aL o r i g i n s


p a r a m demand (Cli.ST} >=0: 4 amounLs r e q u i r e d aL d e s t i n a L i o ns
check: sum ( i i n ORIG} supply[ij = sum ( j i n DEST} demand[ j ] ;
p a r a m c o s L ( L I N K S } >= 0 : 4 shipmcnL c o s L s p e r u n i L
v a r T r a n s ( L I N K S } > = 0: 4 uniLs Lo he shippcd

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 :

Ffcure 6-1: Transportation nnxlel with ali pairs< t r a n s p 2 .rr>cd).

6.2 Subsets and slices of ordered pairs


In many applications, w e are concerncd only whh a subset o f ali ordered pairs from
t w o sets. For example, in the transponation nnxlel, shipments may not be possible from
every orjgin to every destination. The shipping costs per unit may be provided only for
the usable orjgin-destination pairs, so that it is desirable to index the costs and the vari-
ables only o v e r these pairs. In A M P L terms, w e wanc the set L I N K S defined above to
c\>ntain just a subset o f pairs that are given in the data, rather than ali pairs from O R I G
and DEST.
It is not sufficient to declare s e t L I N K S , because that declares only a set o f singkr
members. At a minimum. w e need tosay

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

sum ( ( i . j J i n L I N K S } costli.jl * Transli.jl

w i l l represem a sum over the specified pairs only.


94 OOWFCXWD SETS AND NC€X NQ CHífTÇRÔ

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:

This does not w o r k when L I N K S i s a subset o f pairs, because f o r each i in O R I G it triei


t o sum T r a n s I i . j J over e v e r y j in DEST, while T r a n s [ i . j ] is defined only f o r
pairs { i . j } in L I N K S . If w e try it. w e get an error mcssage like this:

error p r o c e s s i n g consLrainL Supply['GARY• 1 :


invalid subscripL Transi'QASY'.'PR A' 1

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:

Because { < i . j } i n L I N K S ) appears in a context where i has already been defined.


A M P L imerprets this indexing expression ai the set o f ali j such that { i . j > is in
L I N K S . T h e dcmand constraint is handkrd s i m i b r l y , and the entire revised version o f the
nnxlel t% shown in Figure 6-2a. A small represe ntative colkrction o f data f o r this mixlcl is
shown in Figure 6-2b; A M P L o f l e r s a variety o f convenicnt ways t o speeify the member -
s h i p o f compound sets and the data indexed over them, a s e x p l a i n e d in Chapirr 9.
Y o u can see from Figure 6-2a that the indexing expression

(<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:

PRA BBV LAN WIN STL PRK LAP


QAKY x x x x
CLKV x x x x x x
PITr x x x x

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

soL ORIG: * origins


SOL CliST: A dosLinaLions
SOL L I N K S w i L h i n ( O R I G . DKST} :

param s u p p l y (ORIG} >= 0; A a m o u n L s a v a i l a b l o aL o r i g i n s


p a r a m demand (DliST} >= 0; A amounLs r o ^ u i rod a L d o s L i n a L i o n s
check: sum (i i n ORIG} supply [ il = sum ( j in OBST} d o m a n d [ j J ;
param c o s L ( L I N K S } > = 0 : 4 shipmcnL c o s L s p e r uniL
v a r T r a n s { L I N K S } >= 0: 4 u n i L s Lo be s h i p p e d

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:

F i g u r e 6 - 2 a : Transportation model withsekrctcd pairs ( t r a n s p 3 . r » c d ) .

param: ORIG: supply : =


OARY 1400 CLKV 2600 PlTr 2900 :

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

PITT FRA 24 P I T T WIN 13 PlTr STL 28 PITT FRK 9 9 :

F i g u r e 6 - 2 b : Data f o r transponaiion nnxlel < t r a n s p 3 . d a t ) .

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

(< -GARY-. j ) in LINKS}

fc>r example. t o represem the pairs in the first r o w o f the table.


96 OOWFOUNDSETS AND NC€X N 3 CHífTÇRÔ

Similarly, where j ha* already been defined. such a * i n lhe D e m a n d constraint

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).

6.3 Sets of longer tuples


A M P L ' s notation for ordered pairs extends in a natural w a y t o triples, quadxupbs, or
ordered lists o f any length. A l i tuples in a set must have the same dimension. A set can't
contain both pairs and triples, f o r example, nor can the determination ai t o whether a set
contains pairs or triples be made according t o s o m e value in the data.
T h e multicommodMy transponation mixlel o f Figure l-1 o f f e r s s o m e examples o f h o w
we can use ordered triples. and by extension longer tuples. In the original v e r s i o n o f the
mixlel. the costsand amounts shipped are indexed over origin-dcsiinaiion-produci triples:

p a r a m c o s L ( O R I G . DEST. PRQD} >= 0 :


v a r T r a n s ( O R I G . DEST . PWDD } >= 0 :

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:

sol liwks within (ORlG.DESr):

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

A s a final possibility, it m a y be lhai only cenain c o m b i n a i i o n s o f origins,destinations,


and products are workable. T h e n h m a k c s s e n s e t o d e f i n e a set that contains only the tri-
ples o f a l k n v e d combinations:

s e t ROUTKS w i t h i n ( O R I G . DIÍST. P R O D } :

T h e costs and aniounts shipped are indexe d o v e r this s e t

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 :

Individual triples are written, by anak>gy with pairs, ai a porcnthesized and c o m m a -


separavrd list { i . j . p > . L o n g e r listsspecify k>nger tuples.
In the three constraints o f this model, the summations must be t a k e n o v e r three difTer-
ent slices through the set R O U T E S :

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 Dcmarxi ( j i n DEST, p i n PROD} :


sum ( ( i . j . p j i n ROUTKS} T r a n s l i . j . p l = dcmandlj.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:

In the S u p p l y constraint, for instance, Índices i and p a r e d e f i n e d before the aurt, s o


{ < i . j .p> i n ROUTES} refeís t o ali j such that ( i . j , p > is a triple in R O U T E S .
A M P L a Ho ws comparable slices through any set o f tuples, in any number o f dimensions
and any c o m b i n a t i o n o f coor d inales.
W h e n you declare a h^gh-dimensk>nal set such as R O U T E S , a phrase like w i t h i n
{ O R I G . D E S T . P R O D } may specify a set whh a huge number o f members. NVith l O o r i -
gins, 100 destinatk>ns and 100 products. f o r instance, this set poirntially has 100,000
members. Fonunately, A M P L does not creaie this set when it processes the declaratk>n,
but merely checks that each tupkr in the data f o r R O U T E S has its first component in
O R I G , its second in DEST, and iti third in PROD. T h e set R O U T E S can thus be handlcd
efficiently so long as it does not itself contain a huge number o f triples.
W h e n using high-dimensional sets in other oontexts, you may have t o be more careful
that you d o not inadvenently force A M P L *> generate a large set o f tuples. A s a n e x a m -
ple, consider h o w you couldconstrain the volume o f aD products shipped out o f e a c h o r i -
gin t o be less than some amount. Y o u might write either

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 | :

or, using the more compact slice notation.


98 O O W F C X W D S E T S A N D N C € X NQ CHífTÇRÔ

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.

6.4 Operations on sets of tuples


Operatk>ns on compound sets are, much possible, the same as the operations
introduwd for s i m p l e sets in Chapter 5. Sets o f pairs, triples, or k>nger tuples can be
combined with uníon. inter, difí, and syrdiff: can be tested by in and
w i t h i n : and can be counted with c a r d . D i m e n s i o n s o f operands must match appropri-
aiely, s o f o r e x a m p l e you may not f o r m the unk>n o f a set o f pairs with a set o f triples.
A l s o , compound sets in A M P L cannot be d e e b r e d ordered or c i r c u l a r , and
hence a b o cannot be arguments t o funetions like f i r s t and n e x t that take only
ordered sets.
Another set operator, c r o s s , g i v e s the set o f ali pairs o f its arguments — the cross or
C a n e s b n product. Thus the set expression

ORIG c r o s s DBST

represents the same set as the indexing expression ( O R I G , D E S T ) , and

ORIG c r o s s DEST c r o s s PttDD

is the same as { O R I G . D E S T . PROD ) .


Our examples s o far have been constmcted s o thai every compound set has a domain
within a cross product o f previousty speeified simple sets: L I N K S lies within ORIG
cross DEST, for example, and R O U T E S w h h i n O R I G c r o s s DEST c r o s s PROD.
This practice helps t o produee clear and correct models. Nevartiele&s, if you find it
incx>nvenient *> s p e c i f y the domains as pan o f the daia, you may d e f i n e them instead
within the nnxlel. A M PI. provides an iteraied s e t o i operak>r for this purpose, as in the
f o l l o w i n g example:

s e t ROUTES d i m e n 3;

s e t PROD = s e t o í ( < i . j , p ) i n ROUTES} p :


s e t L I W X S = s e t o í ( < i . j . p j i n ROUTKS} <i.j):

L i k e an iterated s u n operator, s e t o f is followxxl by an indexing expression and an


argument, which can be any expressk>n that evaluates t o a legal set member. T h e argu-
ment i s e v a l u a i e d for each member o f the indexing set, and the results are combined into
a new set that is returned by the operator. Duplicate mcmbers are ignored. Thus these
SEC7CN6 4 O F E R A T C U S C N SETS CF TUPLES 99

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

s e t DEMAND = ( j i n DEST. p i n PROD: d o n a n d l j . p l > 0} :

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:

s e t TRANSI' = ( i l i n ORlG. i 2 i n ORIG: il i2> :

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:

In this case, there is a simpler way to writc the indexing expression:

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

Here the dummy index defined by t i n 1 . . T is immcdiately used in the phrase a in


t * l . . A. In this and other cases where an indexing expression specifies t w o or more
sets. the comma-separatcd phrases are evahiated from left to righL Any dummy index
defined in one phraie isavailable for use in ali subsequent phrases.

6.5 Indexed collections of sets


Ahhough declarations o f individual sets are mo&t common in A M P L models. sets may
also be declared in collections indexed over other sets. T h e principies are much the same
av for indexed collections o f parameters. variables orconstraints.
A s an example o f how indexed collections o f sets can be use fui, let us extend the mui-
tiperiod pnxluction nnxlel o f Figure 4-4 torccognizediffcrent market arcas for each prod-
uct. W e begin by declaring:

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:

param m a r k e t ( p i n PttDD. ARl£A[pJ . 1 . . T } >= 0:


param r c / c n u c ( p i n PROD. A R K A l p l . 1. . T } > = 0 :
v a r S e l l ( p i n PROD. a i n A R K A l p l . t i n 1 . ,T>
> = 0 . <= m a r k e t l p . a . 11 :

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:

The only other change is in the B a l a n c e constraints, where S e l l [ p . t ) is similarly


replaced by a summation:

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

smt PttDD: * products


s e t ARKA ( P R O D } : < market arcas £or oach product
p a r a m T > 0: * numbcr o£ w e e k s
param r a t e (PROD} > 0: 4 t o n s per hour producod
param i n v O (PROD} > = 0 : * initial inventory
param a v a i l ( 1 . . T } >= 0 ; * h o u r s a v a i l a b l e i n wock
param mar k e t ( p i n PttDD. AR EA [ p ] ã 1 . . T } >= 0 ;
* l i m i t on t o n s s o l d i n w o e k
p a r a m prockxDSt (PttDD} >= 0 ; * c o s t per ton produced
p a r a m i n v e o s t (PROD} > = 0: * carrying cost/ton oí inventory
p a r a m r e v e n u e ( p i n PROD. A R K A l p j . 1. . T } > = 0:
* revenue per ton sold

var Make ( P R 0 D . 1 . . T } > = 0: * t o n s producod


var I n v (PttDD. 0 . . T } >= 0 : * tons inventoried
var S e i 1 ( p i n PROD. a i n A R K A l p | . t i n 1. . T > A tons sold
>= 0 . <= m a r k e t ( p . a . t ] :
maximize T o t a l _ P r o f i t :
sum ( p i n PttDD, t i n 1 . . T }
(sum ( a i n ARIi>\lp| } r e v e n u e l p . a . t j * S e l 1 l p . a . t ] -
p r o d e o s t lp 1 " M a k e l p . 11 - i n v e o s t ( p | * I n v l p . t ] J:
4 Total revenue less costs for ali products in a l i weeks

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

subjoct to 1nit_Inv ( p i n PROD}: lnvlp.01 = invOlpI:


4 Initial i n v e n t o r y must e q u a l given value
s u b j o c t t o B a l a n c e ( p i n PROD, t i n 1 . . T } :
Makelp.t) + l n v l p . t - 1 )
= sum ( a i n A R K A l p ) } S e l l l p . a . t l + I n v l p . t J ;

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

Figure 6-3: Multipcrkxl pnxluction with indexed sets < s t e e ! T 3 .r>cd).

The complete nnxlel is shown in Figure 6-3.


In the daia for this nnxlel, each set within the indexed colleetk>n A R E A is specified
likeanordinary set:

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 a v a i l := 1 «10 2 «10 3 32 4 40 ;

param r a t e := barxis 200 coils 140 :


param i n v O := barxis 10 coils 0 :

param p r o d c o s L := bands 10 coils 11 :


param i n v c o s L := bands 2.S coils 3 ;

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

smt ORlQ: 4 origins


s e t DEST: * destinations
s e t PttDD: * produets
set o r i g (PROD} w i t h i n ORIG:
set d e s t (PROD} w i t h i n DILSr:
set l i n k s ( p i n PttDD} = o r i g l p l cross destlpj:

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 ;

param l i m i t (ORIG . DEST } >= 0:

p a r a m c o s t ( p i n PROD. l i n k s l p ] } >=0: * shipment c o s t s per u n i t


v a r T r a n s ( p i n PttDD. l i n k s lp 1 } >= 0: * units t o be shippod

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:

F i g u r e 6-5: Multicomnnxlhy transportatk>n with indexed sefc ( r n u l t i c .r>cd).

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:

The declaration o f l i n k s demonstra te s that it is possible k> have an indexed colfection


o f oompound sets, and that an indexed collectk>n may be defined through set o p e n t i o n s
from other indexed cx>)lcctions. In addition to the operations previously mentioned. there
are ileraied union and intersection opera tors that apply to sets in the same way that an
iterated sum appliei to numbers. K>r example, the expressions

union (p in PROD} origlpl


inter (p in PROD} origlpl

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|;

l l e r e it is necessary. f o l l o w i n g a u r ^ t o use a somewhat awkward indexing expression t o


describe a set that does not match the hicrarchical organi/ation.
In general, almost any n*xlcl that can be written with indexed eollections o f sets can
also be written whh sets o f tuples. A s our exaniples suggest, indexed collectk>ns are most
suitable for enthies such as products and arcas that have a hierarchical relationship. Sets
o f tuples are preferabkr. on the other hand. in dealing with entities üke origins and desti-
nations that are related symmetrically.

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

a n p l : dimplãy (J in DEST, p in VftOD: dtwar.d ( J > 500)/


aar. [J í n DEST, p í n PROD: d « m a n d r j , p l > bOfl)
(DE?,COÍlfl) (S*IL,banda) (STL,COÍlfl) (FRE,COllfl);

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.

6 - 4 . To try the folkiwirç; experiment. firsl enter these dcciiratians:

anpl: «*£ Q - (1..10,1. .10,1. .10,1. .10,1..10,1. .10)/


a o p l : M t 9 within Qf
ampl: <3àtã/
ampl: ã*tS:- 123345 2 3 4 4 5 6 3 4 5 5 6 7 4 5 6 7 8 9/

(a> Now try the folkiwirçg two commands:

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

fl*t CIVE W i t h i n {XXJTH^FCOD);

to define a subset of juirs ( i . j j such that nutrienl i canbe found in f « » d j .


<b) RefcmiuLUe the dict model so thit ituses adccltralktn
106 O O W F C X W D S E T S A N D NC€X NQ CHífTÇRÔ

aat FX (KUTR) within FCOD;

Co define, f o r each nutrient i . C h e sei FM ( i ] o f ali foods ChaC can supplychic nuCrímt

( c ) Reformula*? #ie diet model so thac * m e s adcclaratian

fl*t K F {FCOD) Within WUTR;

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.

<b) Use a subset ROlTTBS of ( r i g i n descmation product triples.


( c ) U s e a subset MARKKTS of destiiutkin producl juirs. with Ch: property ChiC p r o d u z p can be
saldai desCinatian j if and only if < j . p j i s i n lhe subset.

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

fl*t DE2<Wn> - fj i n DES?, p in PJDD: d í i r a n l l ^ p l > 0) ;

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.

<b) A d d the declorotians

fl*t LXWCS w i t h i n f ORIG, D ES TI ;


fl*t T R W S F - f i l i n ORIG, i2 i n ORIG: il <> i 2 ) ;

Define variables ova L l í l X S to represem shipmenls lo desfarulkim. and o ser T R A N S F to lepre


scnC shipmenls betwecn <rigiro. T h : cansCrainC at each crigin naw musc xiy thac CoCal shipmenfc
out — to other <rigin* as « v i l as Io descinatians — mu<C equal supply plus shipmenls m f r o m other
o n g i m . Complete the formuljtian f o r Chis case.

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

i m o c s t e g o f y c : in g e n t i l , a papex can fil i r t o scvcval c M e g o r i n . T h : set Wi l l i r > g contiins a


p á r ( r . c J if referec r is will mg lo hindlc papeis in c M e g o i y c .
( a ) W h i l is the dimcnsicinof lhe set

f (r,e) in Willinç, (p,c) in Pap*rKirKl)

anJ w t u l i s l h e s i g n i f i c a r v e o f lhe tuplcs cortamcd in this sei?


<b) Based o n y o u r i n w c i Ia <*>, expiun why the d e c l m t i a n

oat C A i f U n d l * - oatoi f(r,c) in Willing, (p,e) in teparXlnà) <r,p);

g i v « th? set a f juirs < r . p j such éialreferee r o o h c assiened pape* p .


Your model could use juramelcrs p p r e f aixi variibles R c v i e w indexed o v e r C a n l i a r > d l o ;
p p r e f I r . p 1 would be lhe pn.-fen.ncx: of rcfercc r for pipex p , JLTKi R e v i e w I r . p 1 would be 1
i f JVfeive r w c i e am^gned papei p . cr 0 otherwKc. Assuming higherpfcfcccncps an: better. write
out Éie decliralions for these componeiUs axxl for an o b j e c t i w funrtkin Ia m a u nu/r lhe suni o f
p r f e i e n c e s of ali assienments.
( c ) Unfortunatcly, you d o n ' l ha\e lhe nrfeiecs' prefeiencrs f<r indivxluil papeis,since lhey luven'1
scen any j u p e r s y c i W h i l you h i v e an: lheir pnrfenmcrs for differem categorias:

parair. c p r a í {Willing) intaçar >- 0, <- 5;

lixplain why il woukl make sen se l » replice p p r e í [ r . p l «n your objective by

rr-ax f ( r , c ) In W i l l i n ç : (p,c) in PaparKlnd) cprafrr,c]

( 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:

parair. m r a f a r a a f l i n t a g a r > Q; * r a i a r a a a naadad p a r papar


parair. crlnvrc>r)c i n t a g a r > 0 ; * tr.ín p j p e r f l t o rafaraa
pararr. rray.worV. i n t a g a r > m i n w o r X ; « rrax p j p e r f l t o raiara*

l o r m u l J e lhe approprúle assignmcnt constrainls. Complete lhe m o d e l by fcmiulitini; constraints


Ihil each piper musl h i v e lhe required number o f r e f e n x s . aixl Ihil each refevee musl be assigned
an acceptable number of jupers.
Copyright O 3 K B by Robcrt Fourcx, David M . G a y and B r i » W . K o n ç l a n

7
Parameters and Expressions

A large optimi/atk>n nnxlel invariably uses many numérica) values. A s w » have


cxplaincd before, only a c o n c i s e symbolic descriplion o f these values need appear in an
A M P L n n x l e l while the explicit daia values are given in separaie daia staiements. t o be
described in Chapter 9.
In A M P I . a single named numerkral value is calted a / x m t m t i t r . Although s o m e
parameters are defined as individual scalar values. most occur in vectors or matrice* or
other collections o f numérica! values indexed over sets. W e wiD thus loosely refer fc> an
indexed collection o f parameters a> " a parameter" when the meaning i s c l e a r . T o begin
this chapter, Section 7.1 describes the mies for declaring parameters and for referring t o
them in an AMPI. nnxlel.
Parameters and other nume rica 1 vahies are the building bKx-ks o f the expressions thai
make up a m o d e l ' s o b j e c t i v e and constraints. Sections 12 and 7.3 describe arithmctic
expressions, which have a numérica] value, and logical expressions, which evahiate t o
true or false. A l o n g with the standard unary and binary operators o f conventk>nal alge-
braic notaiion, A M P I . provkles iteratoJ operators like surn and p r e d . and a conditional
( i £ - t h e n - e l s e ) operator thai chooses between twoexpressions, depending on the tnith
o f a third expression.
T h e expressions in objectives and constraints necessarily i n v o l v e variables. whose
declaraik>n and use will bediscussed in Chapter 8. There are several c o m m o n uses f o r
expressions thai involve only s e h and parameters, h o w e v e r . Section 7.4 describes h o w
logical expressions are used t o test the validhy o f data, either directly in a parameter dec-
laraiion, t>r separaiely in a c h e c k statement Section 7 5 introduces feaiures f o r defining
new parameters through arithmetic expressions in previously declared parameters and
sets, and 7/> describes randomly-generaied parameters.
A h h o u g h the k e y purpose o f parameters is k> represent numerical values. they can
also represent logical values or arbitrary strings. These possibilities are c o v e r e d in Sec-
tions 7.7 and 7.8, respectively. A M P I . provides a range o f operators for strings, but as
they are most often used in A M P I . c o m m a n d s a n d programming raiher than in nnxlek, w e
defer their introduction t o Sectk>n I3.7.

109
110 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7

7.1 Parameter declarations


A parameter declaration describes c a t a m data rcquircd by a n n x l e l and indica tos h o w
lhe mixlel w i l l refer t o daia values in subsequent expressions.
T h e simplest parameter declarai i o n c o n s i a s o f t h e k e y w o r d p a r a n and a name:

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

If the indexing is over a simple set o f objects a s d e s c r i b e d in Chapter 5, there i s o n e sub-


script. If the indexing is o v e r a set o f pairs. triples. or longer tuples as described in Chap-
ter 6. there must be a corresponding pair, triple. or longer l&t o f subscripts separated by
commas. T h e subscripts can be any expressions. s o long as they evaluate t o members o f
the underlying index s e t
A n unindexed parameter t% a scalar value, but a parameter indexed over a simple set
hav the characteristics o f a vector or an array: when the indexing is o v e r a sequence o f
integers. say

param a v a i l (1. .T>;

the individual subscripted parameters are a v a i l [ 1 ] , a v a i l 1 2 ] a v a i l [ T ] , and


there is an obvious analogy t o the vectors o f linear algebra or the arrays o f a program-
m i n g language like Hwiran or C . A M P I . ' s concept o f a vector is m o r e g e n e r a l howxrver.
since parameters may also be indexed o v e r sets o f strings. which nced not e v e n be
ordered. Indexing over sets o f strings is best suited for parameters that corrcspond t o
places. products and other entities f o r which n o numbering is espeeially natural. Indexing
over sequences o f numbers is m o r e appropriate for parameters that correspond to weeks,
stagcs. and the like. which by their nature tend t o be ordered and numbercd: even f o r
these, you may prefer t o use ordered sets o f strings as described in Section 5J6.
A parameter indexed o v e r a set o f pairs is like a two-dimensional array or matrix. If
the indexing i s o v e r ali pairs from t w o sets, as in
SECT-GN 7 2 A R T W E T C EXWESSONS 111

seL ORIG:
s e t DEST:
param c o s t ( O R l O , DEST} :

then lhere is a parameter c o s t l i . j ] for every combination o f i from O R I G and j


f r o m D E S T . and the analogy t o a matrix isstrongcst — although again the subscripts are
more likely t o bestrings than numbers. If the indexing is over a subset o f pairs. h o w e v e r :

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.

7.2 Arithmetic expressions


Arithmetic expressions in A M P L are much the same ai in other computer languages.
Literal numbers consist o f an opcional sign preceding a sequence o f digits. which m a y or
may not include a decimal point ( f o r example. - 1 7 o r 2 . 7 1 8 2 8 o r • . 3 ) . A t the end o f
a literal there m a y also be an exponent, consisting o f the letter d . D, e , or E and an
opcional sign folk>wod by digits < l e 3 0 or 7 . 6 6 4 3 9 D - 0 7 ) .
Literais, parameters. and variables are c o m b i n e d into expressions by the standard
operations o f addition <•*-). subiraction multiplicatk>n < • ) , d i v i s i o n ( / ) , and exponen-
tiation ( " ) . T h e familiar conventions o f arithmetic apply. Exponcntiation has higher
precedence than multiplication and division. which have higher precedence than addhion
and subtractk>n: successive operations o f the same precedente group t o the left, except
for exponcntiation. which groups t o the right. Parentheses may be used t o c h a n g e the
order o f e v a l u a t i o n .
Arithmetic expressions may also use the d i v operator. which returns the truncated
quotient when hs left operand is divided by iti right operand: the r>cd operator. which
computes the remainder: and the l e s s operak>r. w h i c h returns its left operand minus its
right operand if the result is positive, or z e r o othenvise. K>r pur poses o f precedence and
grouping. A M P L treati d i v and rr»cd like divisk>n. and l e s s like subtraction.
A list o f arithmetic operators <and logical opera k>rs. t o be described s h o n l y ) is given
in T a b l e 7-1. A s much ai possible. A M PI. f o l l o w s c o m m o n programming languages in hs
c h o i c e o f operator symbols. such ai * f o r multiplication and / for division. There is
sometimes more than one standard, howvrver, ai with exponcntiation. where s o m e lan-
guages use * while others use In this and other c a i e s . A M PI. provides al terna te
for ms. T a b l e 7-1 shows the m o r e c o m m o n for m i t o the left, and the alternatives ( i f a n y )
112 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7

l*Ull akcrrntivc typc o f typc cif


«tyfc »«yk upcrjLnJx IXTVUk

if»thcnclsc Iqgical.arítfimctc JLhtfiniCtíC


or II ktgic.il lagic.il
exists íorall kigical lagic.il
and && kigical lagic.il
not (ititty) i ktgic.il lagic.il
<<= = < > > > = < <= s s l= > >= juithniclic lagic.il
in not in abjecl. sc* lagic.il
• - 1 cr. s juithniclic ariéimctic
sum p r o d min max juithniclic JLhtfiniCtíC
* / div mod juithmrtic ariéimctic
• - (unarv) juithniclic ariéimctic
A ftft •ihthmrtic ariiimctic

Exponrntiatian and i £ - t h e n c l s c ase right issociilivc: the otficr opcrjAcrs an:


Icft .roaci atire. The Iqgical operand of i f - t h e n c l s c appcars aftev i í . oixl the
jLrühnu^ic «pcrjLnJs ifter L h e n a n d (optionally) c i s e .

T a b l c 7-1 s Arithmetic and lógica! operators. in incre&ving precede nce.

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

a b s <.tj •ibttihilu' valu-, |.T|


aOOS(*) invcrse c(Mnc. co*" 1 ( * )
aoosh(x) invcrsc hypLitx»hc cosinu\ « k h 1 <r>
asin(r) invcrse « i r , sin <JT)
asinh(x) inveiNu-h\pcjfcihcsine,sinh '(.t)
aLan(.vJ invcrse t i n a m . tin 1 <JT>
atan2 (y, r j invcrsc t i n a m . tin 1 (y/x)
aLanh(*J invcrsc h> pL*itx»hc tinccnl. lanh ' 1 <r )
c o s UJ cará ne
COSH(.TJ hypcxtxiKc CCKÔIC
cxpUJ cxpcincntijLl r '
l o ? <*) n^turjil kig&rithin, log , . ( * )
loglO(jr) c o r a m » Iqgarithm. kig, n <r)
max <.t, >\... J nLiximum (2 cw tncte argumento >
min (.*, >\ ... J mi ri num (2 or mote axgumrnlx)
s i n UJ síne
s in h ( r J hypcxtxiKc «nu*
sqrt(x) SCJ1I0JC KKlt
t a n <x) tangem
tanb<xj hypcxtxilic tingu-nl

Tablc 7-2: Built-in arhhmctic functions for use in nuxlels.

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 ( i in QR1G} supply l i 1

T h e k e y w o r d s u n may be f o l l o w e d by any indexing expression. T h e subsequent arith-


meiic expression is evahiated once f o r each member o f lhe index sei, and ali the rcsuliing
values are added. Thus the sum above, from the transponation nnxlel o f Figure 3- Ia, rep-
resents the total supply available, at ali origins. T h e s u m operator has l o w e r precedence
than s o the objective o f the same nnxlel can be wrkten

sum ( i in ORIG. j in DBffT> c o s t l i . j l * Transli, jj

t o represent the total o f c o s t [ i . j ) * T r a n s [ i . j ] over ali c o m b h a t i o n s o f origins


and destinations. T h e precedence o f s u m is higher than that o f •*• or however, s o f o r
the o b j e c t i v e o f the multíperiod produetion nnxlel in Figure 6-3 w e must w r i t e

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

Other heruieJ arithmetic operators are p r c d f o r muhiplicaiion, m i n for minimum,


and .-riàx f o r iraximum. A s an example, w e could use

max ( i in ORIG} supply l iJ

t o describe the greatest supply available ai any origin.


Bear in mind thai, while an A M P I . arithmctic function or operator may be applied t o
variables ai w e l l ai t o parameters or t o numeric members o f sets, mo&t operations on vari-
ables are not linear. A M P I / s requircmcnts for arithmetic expressk>ns in a linear program
are described in Section 8.2. S o m e o f the nonlinear functk>ns o f variables thai can be
handled by certain solvers are dticussed in Chapter 18.

7.3 Logical and conditional expressions


T h e vahics o f arithmetic expressions can be tesied against each other by comparison
operators:

= 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

sum ( i in OK1G} s u p p l y l i 1 = sum (j in DBST} dcmandljl

is true if and only if lotai supply cquals total demand.


Compartions are one example o f A M P l . ' s logical expressions, which evaluate t o tme
or false. Set membership tests using i n and v i t h i n , described in Section 5.4, are
another example. M o r e complex logical expressions can be built up with logical opera-
tors. T h e a n d operator returns tme if and only if both its operands are true, while o r
returns true if and only if at least one o f its operands is t m e : the unary operator n o t
returns false for true and true f o r false. Thus the expression

T >= 0 and T <= 10

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 tme if i is a member o f MÀXRBQ, or n _ m i n [ i ] is positive, or both. W h e r e several


operators are used together, any comparison, membership or arithmetic o p e n t o r has
higher precedence than the logical operators: a n d h^i higher precedence than o r , while
n o t has higher precedencethanehher. Thus theexpression

i»L i i n MAXRBO o r n _ m i n l i l > 0 and n _ m i n l i l <= 10


SECT-ON 7 3 LOS C/C AND OOND T-GN ti. E>FFESSOUS 115

is interpretei] a*

(not <i i n MAXRKQ J) or <<rx m i n l i ] > Oj arxi <n_minli] <= 10JJ

Altcrnatively, lhe n o t i n o p e r a i o r could be used:

i noL i n MAXRI33 o r n _ m i n [ i ] > 0 and n _ m i n l i l <= 10

The precedentes are sumroari/ed in T a b l e 7-1, which a l s o g i v e » altcrnative forros.


Like • and lhe operator s o r and a n d have ileraied versions. The iteratcxl o r is
denoted by e x i s t s , and lhe iteratod a n d by ü o r a l l . F o r e x a m p l e . lhe expression

cxisLs (i i n O R I G } dcmand l i 1 >10

is irue if and only if ai least one origin has a deroand greater lhan 10, while

íoral 1 (i i n O R I G } dcmand l i 1 >10

is true if and only if e v e r y origin has dcmand greaier lhan 10.


Anolher use f o r a logical expression is a s a n operand to the conditional ot i £ - t h e n -
else operator, which returns one o f t w o different arithmetic values depending on
whether the logical expression is true or f a b e . Considcr the t w o collections o f inventory
balance constraints in the muhiperkxl pnxluction model o f Figure 5-3:

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: o r d < t J > 1>:


Hakelp. t| + I n v l p .prev ( t J | = S e l l l p . t l + I n v l p . t J ;

The B a l a n c e O constraints are hasically the B a l a n c e constraints w h h t set to


f i r s t { W E E K S } . The only difference is in the second term, which represents the previ-
ous \vvek's inventory: it i s g i v e n a s i n v O [ p ] f o r the first \vx£k<inthc B a l a n c e O con-
straints) but isrepresented by the variable I n v [ p . p r e v { t > ] f o r subsequent wxreks <in
the B a l a n c e constraints). W e woukl like k> combine these constraints into one declara-
tion. by having a icrm that takes the vahie i n v O [ p j when t is the first wvxrk, and takes
the value I n v [ p . p r e v < t ) ] othenvise. Sucha terro is wrhten i n A M P l . as:

i£ t = f i r s t (WKKKSJ Lhen i n v O l p l else I n v l p . p r e v < t J1

P b c i n g this expression into the constraint declaration. can wrhe

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.

7.4 Restrictions on parameters


I f T i s intcnded torepresent the number o f \reeks in a muhiperiod m o d e l h should be
an inicger and greaier than I. By including these conditions in T ' s declaraik>n.

param T > 1 intc^er:

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:

param dcmand (DEST. PROD} >= 0:

If you include dummy índices in the indexing expression. however, you can use them to
specify a dilTerent resiriction for each para meter:

param f _ m i n (FOOD} > = 0:


param £ nvax ( j i n FOOD} > = £_minlj| :
S E C T tON 7 4 R E S T R C T O M S ON P / f W V E T E R S 117

T h e e f i e c f o f these dcclaraiions is t o define a pair o f parameters £ _ m a x [ j ] >=


tjxiLnli ) f o r e v e r y j in the set FOOD.
A restriction phraie f o r a paramcicr dcclaration m a y be the \v\>rd Lntegez or
bínary or a comparison operator f o l f o w e d by an arithmetic exprcssion. While
i n t e ^ e r restricfc a paranieter k> integral <whokr-number) values. b i n a r y reuricts it t o
zero or one. T h e arithmetic expressk>n may refer t o sefc and parameters prcviously
defined in the nuxlel. and t o dummy Índices defined by the currcnt declarai ion. There
may be several restriction phrases in the same dcclaration. in which c a i e they may
optionally be separated by c o m m a * .
In special circumstances. a restriction phrase may e v e n refer t o the parameter in
whose dcclaration it appears. S o m e multi period pnxluctk>n models. for example. are
defined in terms o f a parameter c u n u l a t i v e _ : n a r k e t [ p . t ) that represents the
cumulative demand for pnxluct p in weeks I through t. Since cumulativo demand d i x s
noi decre&ie. you might try ii> write a restriction phrase like this:

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

For the parameiers c u n u l a t i v e _ m a r k e t [ p . 1 J , h o w e v e r , the restriction phra*e will


r e f e r t o c u n u l a t i v e _ : n a r k e t [ p . 0 ) , which isundefined: A M P l . will reject the decla-
ratk>n whh an error message. W h a t you need here again fc a conditional exprcssion thai
handles the first period specially:

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:

T h e same thing coukl be written a little more compactly as

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 | :

since " e l s e 0 ° is as&umed. A l m o s t always. some f o r m o f i f - t h e n - e l s e exprcssion


is needed t o make this kind o f self-reference possible.
A s you might su&pect f r o m this last example. sometimes h is desirableto place a more
complcx restriction on the model*s data than can be expressed by a restriction phrase
within a declara ti on. Thi* is the p u r p o s e o f the c h e c k statrment. For example, in the
transportalion nuxlel o f Figure 3 - I a . k>ial supply must cxjual tolal demand:

check: sum ( i in ORlG} supply l i j = sum ( j in Di£Sr> dcmandljl:

T h e multicomnnxlity version. in Figure - l - l . uses an indexed c h e c k t o say that total sup-


ply must equal total demand for each pnxluct:

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.

7.5 Computed parameters


lt is seldom possible toarrange thai the data values avaibble to a nnxlel are precisely
the coefficient vahies required by the objective and constraints. Even in the simple pro-
duciion nnxlel o f Figure I -4, for example. wxr wrote the constraint as

sum ( p in FROD} (1/raLclplJ * Make[pl <= avail;

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:

param s h a r e ( D l í S r } > = 0. <= 100;


param t o t _ s h = sum ( j i n Dl£Sr} n h a r e l j J;

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

param t o t . dem (PROD} > = 0 ;


param demand ( j i n DIíST. p i n PROD}
= sharoljl * tot.demlpl / tot_sh;

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:

s u b j o c t t o Demand ( j i n DIíST. p i n PROD} :


sum ( i i n O R I G } T r a n s l i . j . p l = d c m a n d l j . p l :

W e could avoid compuied parameters by substituting the formulas for t o t _ s h and


d e m a n d [ j . p ] directly into this constraint:

s u b j o c t t o Demand ( j i n DIíST. p i n PROD} :


sum ( i i n O R I G } T r a n s l i . j . p l
= s h a r o t j l * t o t d o m l p l / sum ( k i n DIíST} sharo[kl:

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:

param m a r k o t (PWDD. 1 . . T * 1 } >= 0 ;

and then declare


param m i n i n v ( p i n PttDD. t i n 0 . , T } = í r a c * m a r k o t l p . 14-1 j :
v a r I n v ( p i n PWDD. t i n 0 . , T } >= m i n i n v l p . t l :

to define and use parameters m i n i n v l p . t ) thai represent the minimum inventory o f


pnxluct p for week t . A M P I . keeps ali = definitk>ns o f parameters up to daie throughout
a session. Thus for example if you change the value o f £ r a c the vahies o f ali the
m i n i n v parameters automatically change accordingly.
I f you define a computed parameter ai in theexamples above, then you cannot also
specify a data value for h. An atiempt t o d o so will resuh in an error message:

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

( A M P L uses ' V in a data statement to indicatc an omitted entry. as expiained in Chapter


9 a n d A . 12.2.)
T h e expression that give* the default value o f a parameter is evaluated only when the
paramcter's value is first nceded. such ai when an objective or constraint that uses the
parameter is processed by a s o l v e command.
In most = and d e f a u l t phrases, the operator is f o l b w e d by an arithmetic expression
in previously defined sets and parameters (but not variables) and currently defined
dummy Índices. Some parameters in an indexed collectk>n may be given a computcd or
default value in terms o f others in the same collection. however. A s an example. you can
smooth out some o f the varialion in the minimum inventories by defining the m i n i n v
parameter to be a running average like this:

param m i n i n v ( p i n PWDD. t i n 0 . ,T> =


i £ t = 0 Lhen i n v O l p l
0.S * (mininvlp. t-11 + í r a c * market lp. t « - l l J :

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 m i n i n v ( p i n FWDD. t i n 0 . ,T>


= írac * marketlp.t«-ll . >= 0:
SECT-GN 7 6 FWCOWLYGENBWTEDP/RAVETERS 121

w i l l cause an enroc t o be signaled if the computod value o f any o f the m i n i n v parameters


is negative. This check is triggered whenever an A M P L session uses m í n i n v f o r any
purpose.

7.6 Randomly generated parameters


W h e n y o u ' r e testing out a n n x l e l especially in the early stage s o f development, you
may find it oonvenient t o let randomly generated daia stand in for autuai dato t o be
obtaincd later. Randomly generated parameters can a l s o be useful in experimenting with
alternative model formubtk>ns o r s o l v e r s .
Randomly generated parameters are like the computed parameters inaroduced in the
preceding section. except that their defining cxpressions are made random by use o f
AMPL V S built-in random number generation funetions listod in Table A - 3 . A s a n example
o f the simplest case. the individual parameter a v a i l representing hours available in
s t e e l .rr»c<l may be defined k> equal a random funetion:

param a v a i l mean > 0 :


param a v a i l _ v a r i a n c e > 0. < a v a i l mean / 2:

param a v a i l = max ( ? t o r m a l < a v a i l mean. a v a i l _ v a r i a n c e j . Oj :

Adding s o m e indexing g i v e s a multi-stage version o f t h i s nnxlel:

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 moan ( 5 T A Ú B } > 0 ;


param a v a i 1_ v a r i a n c c ( s i n S f A G E } > 0 . < avail meanlsl / 2;

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 ;

p a r a m t o t . dem (PROD} > = 0 ;


param demarxi ( j i n DEST. p i n PROD}
= s h a r e [ j J * t o t demlpl / t o t _ s h :
122 F A R A I ^ T E R S AND E X F F E S S CfíS CHífTÇR7

Parameters t o t _ s h and d e m a n d then i l s o become random. because they are defined in


terniv o f random parameters. In the multipcriod productk>n n n x l e l you can define the
demand quantities m a r k e t t p . t l in terms o f an initial value and a random amount o f
incrcaie per perkxl:

param m a r k e t l (PROD} > = 0 ;


param max i n c r (PttDD} >= 0:

param m a r k c t ( p i n PWDD, t i n 1. .T«-l> =


i f t = 1 then m a r k e t l [ p )
• l f i t t U n i í o r m ( 0 . max. i n c r J * m a r k c t l p , t - 1 1 :

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.

7.7 Logical parameters


Ahhough parameters norma D y represem numeric values, they can optionally be used
tostand for tnie-false values or for character strings.
Thecurrent version o f AMPL does not support a full-tlcdged ' 'logical" type o f param-
eter that would stand for only the values tnie and false, but a parameter o f type b i n a r y
may be used to the same effect. As an i Ilustra ti on. w e describe an application o f the pre-
ceding inventory example to consumer goods. Certain pnxlucfc in each wede may be
specially promoted. in which c a i e they require a higher inventory fraction. Using param-
eters o f type b i n a r y , can represent this situaiion by the foDowing dccbrations:

param f r _ r « > 3 > 0: 4 regular inventory fraction


param f r _ p r o > f r _ r c g : i f r a c t i o n f o r p r e m o t e d item.*:

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;

W e can also say the same thing more concisely:

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 :

When an arithmetic expression like p r o r > o t e [ p . t ] appears where a logical expression


is required. AMPL interpretv any non/ero value as tme, and zero as false. You do need to
exercise a Ihtle caution to avokl being tripped up by this implich conversion. For exam-
ple, in Sectk>n 7.4 w e used the expression

if t = 1 Lhen 0 e l s e cumulativo market[p.t-11

If you aceidcntally wrile

if t Lhen 0 e l s e cumulativo markeLlp. L - l 1 * DIPFKRENT

it's perfectly legal, but it doesn't mean what you intended.

7.8 Symbolic parameters


Y o u may permit a para meter to represent character string values. by including the
keyword s y m b o l i c in its declaratk>n. A symbolic parameters values may be strings or
numbers. just like a set's members. but the string values may not panicipate in arithmetic.
A major use o f symbolic parameters is to designate individual set members that are to
be treated speciaDy. H>r example. in a nnxlel o f traffic Ilow, there is a set o f intersec-
tions» \wo o f whose members are designated as the entrance and exit. Symbolic parame-
ters can be used to represent these t w o members:

seL IWTKR:

param e n L r symbolic in IMTKR;


param e x i L symbolic in IMTBR, o enLr;

In the data staiements, an appropriate string isassigned to cach symbolic parameter:

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:

T h e n in the data w e could s p e c i f y

param: ORIG: o r i g name supply : =


QARY "Gary. Indiana" 1400
CLKV "Cleveiarxi. Ohio* 2G00
PITT -Pittsburgh. Pennsylvania- 2 900 :

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

- The number o f «ccfcx is a positive integer gnmer than 1.


- The inicial inwntofy of a product ckies not exceed the total market demanJ for thit prodiKt
o ver ali w c à x .
- T h : inventory cost for a product is neve* mote thin l(Kf of the expccted revenue for thit prod-
ucl in any one wevk.
- T h : number o f hours in a week is between 2A aixJ 40. aixl does r*»t chance by mcre than 8
hourc from one wcek to the next.
- l r or each producl the expccted revenue ne\er decnrases from one weekto the next.

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

if t - fírflt(WEEXS) tfcan ...

Iind an equivak-nt expression thil uses the functkmord < t j .


<b) Combine the D i c L Min x\d D i o L . Max constraints of l"igun:5-l's diet modcl intoonc con*
straxnt ckrclaration.
(c> In th- multiccinmoditY transp<»ta«ion model of Figure «4-1, imagine that there is nure demand
at th- dcstirulkins than we can meet from the supply produced at th- crigins. To make up th- dif*
fenmce, a Imülcd number o f additkirul tons can be purchased (rather thin manufactured) f<r ship
ment at certam erigira.
To model thissitiulkin. supp<ise thit we dcclare a subset o f origins.

fl*t EUY__ORIG W l t h i n ORIG;

where the additional kins can bc bought The relevant dita vahies and dccision vaxiibk-s coukJ be
indeied over this subset:

par Air. fcuy_fl^>ply {EUY_pRIG,PROD) > - Q; « i V A l l a b l â Zox putrcJufl*


parair. touy_coot {KTY_ORIG, PK>D) > fl; • purcíiafla ca* t p-ar ton
var Buy f i In BUY__ORIC, p In P R t f » >- 0 , < - r Í,p3 ;
* Atr&vxit t o iAiy

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:

fl*t OR2G; * origine


fl*t DES?; * dafltinationfl
fl*t PRCD; * productfi
pararr. uupply {ORIG, PRCD) > - 0;
pararr. darr-and (DES?, PRCD) > - 0;

<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

- dosL d e m a n d l j | « l h e (atai demand fcrall produets a< destirutkin j .


- L r u o _ l i m i L l i . j .pl K the largest quintity o f prodirt p thit can be shipped from i Io j
— that is. the largest value that ckics not exceed l i m i L [ i , j J , or <he supply cif p at i , « the
demand f<r p at j .
- ma x. s u p p l y l p l K the largest supply Of producl p avaibbk* at any crigin.
- max^dif f Ipl is the largest d i f f e i e n c e , o v e r ali combiiutkim of origins aixl ckstrutx»m.
bdwxn the supply aixJ dcmarxl ícr producl p.
<b) Write c o t decUratxins. using the = operator, to compute these sets:
- Products p whose demand at k-ast5(K) at some destination j .
- Products p whote demand K at k-ast 250 at alldestinations j .
- Products p whcKc demand equal lo 500 at some destirutkin j .

7 - 5 . A M H . p r a n e t e r x can be defined t o contam many kmd< of series, especially by using recur


sive defmitxtro. Fcr evampk-. w e can make r.I j l equal the sum of the first j integers. f<* j from
1 Io s o m e given hmit N, bv writmg

parasr. X;

parair. o { } In 1 . . K ) - aum ( J J ín 1..J) JJ;

or. usirçg a formula f<* the sum.

parair. fl f ) i n 1 . ,K) - } • (J*l> / 2;

or. usirçg a i e c u r â w definitiun.

parair. a f J i n 1 . .K) - if J - 1 Own 1 * 1 Í » fl[J-l] •

Thi< exercite asks you Io play with some other potsihilitics.


(a> D e f i n e f a c L l n l Ki be n farto rui. the product o f the first n mlegers. G i w txith a lecursive
aixl a rxinrecursiwdefinitkin as abo\e.
<b) l h e r i b o m c c i numbers are defined mathematically by fn = / , = 1 and /M = / u _ , + fu_2.
t><«ng a recursiw deciiratxin. define í i b l n l «n A M H . to equal the n th ]°4ionacci number.
U s e another A l ü t - dcclaration lo \erify thit the n th H b o n a x i number equils the ckwest integer
to ( / I + Z I N T > U A T .
( c ) Here's another recursive definitxin. called Ackexmann's funrtkin. f<* p o ã t i w integers i and j:

A(J\0) = i + l
A(0,;+ 1> = A( 1, j )
A(i+ 1 , / + 1> = A ( A ( i \ ; + !>,/>

Using a l e c u r â w deciiratxin. define a c k f i , j 1 in A M P l . s o thit it will equal /t(í, f ) . Use


diaplay Io print « a c k l O . 01, a c k ( l , 1 K a c k [ 2 . 2 1 arxl so forth. W h i t diffícuky ck» you
encounler?
( d ) Wh at an: the values & ± j l i 1 defined by the foDowing odd dechratiofl?

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;

pATdir. p*r*d f i í n KODES áiiZ ( R o o c ) ) ayu2x>lic in XOEES d i f f fi);

Kvery nade i , except R o o U h i s i pitdectssar p r o d l i J.


Hie ck-pCh of a nade K the numbcr af p f e d m x m that you encaunlcr <«i tracine back Ca the raaC;
Ch: depth af th: raat k 0. Give an A M H . ckTmitkin kw d o p L h l i 1 thit cufnxtj) 1 computes the
depch af each nade i . Ta check your answex. *pplv yaur defmitkin Co AMH. dita kw the trte
depicled atxtw; aftexreadirçg inChe dita, use d i s p l o y Ia view the paranie^i d o p L h .
An emir inche diCacoukJ give a Cite phisa disca imecli-d cycle, hle Chis:

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:

v a r Make (p in PROD} >= 0. <= marketlpl;

This declaration a c a t e s an indexed collection o f variables M a k e [ p ] , one f o r each mem-


ber p o f the set P R O D : the rules in this respect are exaetly the same as for parameters.
T h e e f f e c t o f the t w o qualifying phrases is t o imposc a restriction. or constraint, on the
permissible values o f the variables. SpecificaDy, > = 0 implies that ali o f the variables
>íake[p* must be assigned nonnegative values by the optimi/ing algorithm, while the
phrase < = m a r k e t [ p ] says that, for each product p , the value given t o J í a k e [ p ] may
n o t e x c e e d the value o f the parameter m a r k e t [ p ] .
In general, either > = or < = may be f o l l o w e d by any arithmetic expression in previ-
ously defined sets and parameters and currently d e f i n e d d u m m y índices. M o s t linear pro-
grams are formulatoJ in such a way that every variable must be nonnegative: an A M P L
variable declaration can specify nonnegaiivity either directly by > = 0, or indirectly as in
the diet nnxlel o f Figure 5-1:

param £_min (FOOD} > = 0:


param £ nvax ( j i n FOOD} > = £_minljl :

var Buy (j in FOOD} >= £_min[j|. <= £ ovaxljl:

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 :

T h e objective would then be the sum o f these three defined variables:

maximize ToLal. P r o í i L :
ToLal_Revenue - ToLal_Prod_CosL - ToLal_Inv_CosL:

T h e structure o f the objective is clearer this w a y . A l s o the defined variables are c o n v e -


niently available t o a d i s p l a y statement t o show lu>\v the three main components o f
profit compare:

a m p l : diaplay Total Sovonuo, Total Prod Coat, Total Inv Coatj


T o L a l R e v e n u e = 8013 85
T o L a l _ P r o d _ C o s L = 285643
T o L a l _ I n v _ C o s L = 1221

IXrclarations o f defined variables like these d o not g i v e r a e t o additk>nal constraints in


the resulting problem instance. Rather, the linear expression k> the r i g h t o f the = is sub-
sthuted for e v e r y occurrence o f the defined variabke in the objective and constraints.
IXrfincd variables are even more useful for nonlinear programming, where thesubstitu-
tion may be only implich, s o w e wiD return t o this topic in Chapter IH.
I f the expression *> the right o f the = operau>r contains n o variables, then you are
merely defining variables t o be f i x e d t o values given by the data. In that caie you should
use a p a r a r » declaratk>n instcad. On the other hand, if you only want *> f i x some vari-
ables temporarily while d e v e l o p i n g or analy/ing a model, then you should leave the dec-
larations unchanged and instcad fix them with the f i x command described in Section
11.4.
A : = or d e f a u l t phraie in a variable declaration gives intúnl values t o the indi-
cated variables. Variables not assigncd an initial value by : = can a I s o b e assigncd initial
values from a daia file. Initial values o f variables are normally changed — ideally t o
optimal values — when a solver is invoked. Thus the main purpose o f initial values o f
variables is t o g i v e the solver a g o o d staning solution. *Solvers for linear programming
can seldom makc g o o d use o f a staning solution, howxrver, s o defer funher discussion
o f this topic t o Chapter l 8 o n nonlinear programming.
Finally, variables may be declared as i n t e ^ e r s o that they must take whole number
values in any optimal solution, or as b i n a r y sothat they may only take the values Oand
132 L N E A R F T O 3 R W S V / « A f i l £ S . C e J E C T V E S AND OOttSTRA NTS CHífTÇR3

I . M o d e l s that contain any such variables are integer programs. which are the topic o f
Chapter 20.

8.2 Linear expressions


A n arithmetic expressk>n is tintar in a given variable if, for every unh incr cate or
decreaie in the variable, the value o f the expression incr cases or decreases by s o m e f i x e d
amount. A n expressk>n that t% linear in ali ifc variables is called a linear expressk>n.
(Strictly spcaking, these are ajfine expressions. and a linear expression & an aííine
expression with constant term zero. K>r simplicity, wxr will ignore this distinction.)
A M P L recognizes as a linear expression any sum o f ter n*v o f the form

contiMle.xpj-
wvkiNtrtf
(.conskini rxpr) * wukible rtf

provided that each con&ianfrexpr is an arithmetic expressk>n that contai ns n o variables.


while var-ref is a reference (possibly subscripted) t o a variable. T h e parentheses around
the consíans-txpr may be omitted if the result is the same according t o the r u l e s o f opera-
tor precedence (Table A - l ) . T h e f o l l o w i n g examples. from the constraints in the multi-
period pnxluctk>n nnxlel o f Figure 6-3, are ali linear expressions under this definitk>n:

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.

RUBI ( p in PROD. t in 1..T}


(RIAN ( a i n A R B A l p l } r e v e n u e l p . a . t j * S e l l l p . a . t J -
prodcostlpl * M a k e l p , Ll - i n v c o s t l p l * Xnvlp.tjj

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

may be written in a linear program av

Makelp.tJ / raLelpI

T h e order o f multiplicai ions is irrelevant, s o t h e ivrWoMf-ri/neod not c o m e at the end o f


a term: f o r instance,

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

A s an example combining these principies, imagine that r e v e n u e [ p . â . t ] is in dolbrs


per metric ton, while S e l l remains in tons. If define conversion factors

param m t _ t = 0 . 9 0 7 1 8 4 7 4 ; 4 metric tons per ton


param t _ j n t = 1 / m t _ t ; 4 tons per metric ton

then both

sum ( a i n ARKA[p| } m t _ t * r e v e n u e l p . a . t j * .Sell l p . a . Ll

sum ( a i n ARKA[p| } r e v e n u e l p , a . 11 * S e l l l p . a . t l / t_mt

are linear expressions for total revenue.


T o continue our example. if costs are a b o in dollars per metric ton. the objective
could be written as

m L _ t * sum ( p i n PttDD. t i n 1. , T >


( s o n ( a i n A K 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 * M a k e l p , 11 - i n v c o s t l p l * X n v l p . t j j

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

minimize ToLal_CosL: sum ( j i n FODD} c o s L l j l * Buyljl:

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

a m p l : diaplay ( j in FOOD) 100 • coet[j) • Buy[j) / Total Coatj


100*cosL[j|* Buy[j1/ToLal_CosL l» 1 : =
BKKK 14.484S
C1LK 4 . 3 87 62
F1S11 3.8794
JJAM 2 4 . 4 7 9 2
MCli 16.0089
MTL 16.8S59
SB3 1S. 6862
TUR 4.21822

to show the pereentage of the total cost spent on each food.


Ahhough a panieular linear program must have one objective funetion. a mixlcl may
c\>ntain more than one objective declaratk>n. Moreover, any m i n i m i z e or m a x i m i z e
declaration may define an indexed collection o f objective functk>ns, by including an
SEC7CNÔ3 CEJECTVES 135

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:

minimize Total_NA: sum ( j i n FOOD} a m t l " ? L \ - . j l * Buyljl:

< 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:

ampl: xzodol diot.xaod;


ampl: data diot2a .dat;
ampl: diaplay n zzax["NA");
n nvax l ' N>V 1 = S0000

a m p l : ainlxsdza Total NA: SUE { j in FOOD) axst [ "NA", j ) • Buy[j)j


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 o r a t i o n s . o b j o c t i v c 1 1 8 . 0 S 9 4 0 3 2
Objoctivo = Total_COst

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:

a m p l : diaplay Total NA;


T o t a l _NA = S0000

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: objoctivo Total NA;

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

a m p l : diaplay Total Coat;


T o L a l _ C o s L = 12 3 . G27

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

a m p l : i s o d o l tranap.mod; data aaaign .dat; aolvo;


CPLlüC £ . 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 2 8
24 d u a l s i n r o l c x i t c r a t i o n s <0 i n p h a s « 1J

ampl: option diaplay lcol 1000, andt zoro rowa 1;


ampl: option diaplay opa .000001 ;

a m p l : diaplay Total Coat,


ampl? { i in ORIG, j in DEST) coat[i,j) • Trana[i, j);
T o t _ a l _ C o s L = 28

costli. jl'Trans li. j] : =


Co u l l a r d C l 18 6
lia s k i n D2 41 4
11a z c n C24G 1
Itopp D2 37 1
Iravani C l 38 2
Linotsky C2S0 3
Mehrotra D2 39 2
lson C140 4
â n i l o w i t z M233 1
Tamhano C2S1 3
Whitc M239 1

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:

ampl: aubjoct to Stay Optimmlt


ampl? SUE ( i in ORIG, j in CE ST)
ampl? coat[i,j) • Trano[i,j) - 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

sum ( j in DI£Sr> c o s L l i . j l * Transli.jl

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:

a m p l : minixslzo Prof of ( i in ORIG) t


ampl? SUE {j in DEST) coat[i,j) • Trana [i, j) j

Thisstatement creates. f o r each person i , an objective P r e £ _ o £ [ i j that m i n i m i z e s the


ranking o f i for the room that i is assigned. Then \v\r can select any one person and opti-
m i z e h i s o r her ranking in the assignment:

a m p l : objoctivo Prof offCoullard");


ampl: aolvo;
CPLlüí 8 . 0 . 0 : o p t i m a l solution: objcctivc 3
3 simplex i t c r a t i o n s ( 0 i n p h a s o IJ

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

a m p l : diaplay Total Coat,


ampl? ( i in ORIG, j in DEST) cost[i,j) â Trana[i, j);
T o L a l _ C o s L = 2B

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;

or in each w x k t (Figure 4-1):


154 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

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:

This says that if a v a i l ( t J is specified ai zero in the data f o r any week t , it is to be


interpreted ai meaning 4 'iu> constraint on time available in week t * * ralher than ' l i m i t o f
zero on time available in week t M . In the simpler c a i e where there is just one Tirr»e con-
straint not indexed over weeks. you can specify an analogous condhional definition ai
follows:

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:

The pseudo-index ing expression { i £ a v a i l > 0 } causes one constraint. named T i m e .


to be generated if the condhion a v a i l > 0 is tnie. and no constraint at ali to be gener-
ated if the condhion is false. (The same notation can be used to conditionally define
other nnxlel components.)
A M P l . ' s algebraic description o f a constraint may coo&kt o f any t w o linear expres-
sions separated by an equality or inequality operator:

linear expr <= linear-expr


Unear expr - linear-expr
linear expr >= linear-expr

While it is cusiomary in mathematical descriptions o f linear programming to place ali


terms containing variables to the left o f the opera tor and ali other terms to the right (as in
constraint T i m e ) . A M P L imposes no such requirement (as seen in constraint B a l a n c e ) .
SEC7 CN 3 4 ooNSifVKtns 139

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

cansâ-rxpr <= Dntar-expr <= consl-rxpr


can ti -rxpr >= tintar txpr >= consl-rxpr

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|:

then AMPL does recognize it as linear.


A M P L simplifiesconstraints as it prepares the nnxlel and data for handing to a solver.
For example. it may eliminate variables fixed at a value, combine single-variable con-
straints with the simple bounds on the variables, or <kop constraints thai are implied by
other constraints. You can normally ignore this presolve phase, but there are ways to
observe itselTeets and modify its actions, asexplained inSectk>n 14.1.
140 L N E A R F T O 3 R W S V / « A f i l £ S . C e J E C T V E S AND OOttSTRA NTS CHífTÇR3

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;

Th rs c o m trair* is not i m r because il applies lhe a b i : funetion l o an expression involving vari-


ables. Formula*; a i n r conslraint lhal has lhe « m e e f l e c t

( 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 .

- In ( c M h e parameter m a x _ i n v _ r a L i o is replaced by a n e w vambk-, K a L i o [ L 1.

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:

parair. coar. {SCORE, FCOD) > Q;

A separale objective funetion may lhen be defined fer eachslore:


m i n i mi » a * l * c a l _ c o o c [ a í n STORE):
sum [ } í n FCOD) c o f l t [ f l , J ] • B u y l j l ;

Considcr lhe f o l l o w i n g d a t i fer three skres:


SECT CN8.4 OOUSTRfcNTS 141

fl*t STCRE :- JEKE2, VCKS ;


pararr. o a f l t : EEEF CIOC FISH HAN KCH KTL SPU WR
-JJ.P* 3.19 2 . !»9 2.29 2.89 1.B9 1.99 1.99 2.49
JWEL 3.09 2.79 2.29 2.S9 1.59 1.99 2.09 2.30
\CtfS 2 . !»9 2.99 2.49 2.69 1.99 2.29 2.00 2.69 ;

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).

8 - 4 . This exercite reUtes Io the assisnmenl example of Scclion 8 J .


<a) Whit is the best rankingoffice that vou can avsign lo each individiul. given that the total of the
ranking* must st»y at the optimal vahie of 28? How many different optnMl assignments do there
seem Io be. and which individuais gctdilfexent officesin differerU assignments?
<b) Modify the assignment example so thit it will fmd the best rankirçg office thit you can assign Io
each individual gi\en thit the tolal of the rankings may inexease from 28. but may not exceed 30.
( c ) After making the rnodificatkin suggested in (b>. the person in charge o f a-«igning offices hxs
taed a^iin ki mini mi/r the objecti\e P r c £ _ o £ l " C o u l l a r d " 1. This time. the rep<rtcd solution
isas follows:

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

Ihin w o r s t [ i j . ( S o e lhe comtrainl T i m e in Scclion f<r a smuLu example.) In lhe asâgn


menl íntcrprclatum o f Ihrs model. w h i l d o lhe new canslraint* mean?
<b) lJ<e lhe model Í r a m U ) ki shciw lhal Ihere K an oplinuil salulKin. with lhe abjeclive equil l o 28,
in which no e n e get* an a f f i c e w a n e lhan Ihcir fiflh chaice.
( c ) Uxe éie model f r o m ( a ) l o show thil ai krasl one persan num gel an o f l i c e warxe thin fourlh
chciíce.
(d> lJ<e lhe model Í r a m U ) *» *hc»w lhal if you g i v e N e h a n hw f i m chaicv, w ã k i i * any reslriclkim
a n lhe adier individuais' choice*. lhe abjeclive cannot be made smallex lhan 31. Determine simi»
larly how smalllhe abjeclive can be made if each alhex individual is gi\vn firsl chciice.
CopvrishtO 2003 by R<*>crt Four», DavidM. Oay and Brian W. K a n ç h v i

9
Specifying Data

A s we emphaii/e througbout this lxx>k, there isa distinction between an A M P L nnxlel


for an optimi/ation problem, and the data values that define a particular instance o f the
problem Chapters 5 through 8 focused on the dcclaratk>ns of sets, parameters. variables,
objectives and constraints that are necessary to describe nnxle k. In this chapter and the
next, takea closer kx>k at the statements that specify the data.
Examples of A M P L díikt stait/nenis appear in almost every chapter. These statements
ofler several formais for lists and tables o f set and parameter values. Some formate are
most naturally created and maintained in a text editing or word processing environmeni
while others are easy ii> generate from programs like datahase systems and spreadsheefe.
The d i a p l a y command <Chapter 12) also pnxluces output in these formats. Wherever
possibke, similar syntax and concepfc are used for both sets and parameters.
T h i i chapter first explains how AMPL's d a t a command isused, in oonjunction with
data statementv, to read data values from files such as those whose names end in . d a t
throughout our examples. Options to the d a t a command also alk>w or force selected
sets and parameters ii> be read again.
Subsequent sections describe data statements, first for lists and then for tables o f set
and parameter data, f o l b w c d by brief sectk>ns on initial values for variables. values for
indexed collections o f sets, and default values. A sum mar y of data statement formais
appear s in Section A . 12.
A final sectk>n describes the r e a d command. which reads unfornuiUed lists of values
intosefc and parameters. Chapter 10 t% devoted t o AMPL's features for data stored in
relational data bate tables.

9.1 Formatted data: the data command


Declarations like p a r a m and v a r . and cx>mmands like s o l v e and d i s p l a y , are
executed in model tm/ilt, the standard nnxle for most modeling activity. But nnxlel nnxle
is inconvenient for reading k>ng lists of set and parameter vahies. Instead A M P L reads hs

143
144 3=ECFYNGDATA CHífTÇRO

tlaia statements in a duki trunfo lhai is initiated by the d a L a c\>mmand. In ifc m o s t c o m -


mon use, this command consists o f the key word d a L a f o l l o w e d by the nanie o f a file.
For example,

ampl: data diot.dat;

r e a i s data from a file namod d i e t . d a t . Filenames containing spaces. semieolons. or


nonprinting eharaeters must be cncloscd in quoies.
W h i l e reading in data mode. A M P L treats while spaee. that is, any scqucncc o f space.
tab, and " n e w l i n e " eharaeters. ai a single space. C o m m t t separa ti ng stringsor numbers
are a b o ignored. Judicious use o f these separators can help lo arrange data into easy-to-
read lists and tables: our examples use a combinaiion o f spaces and newlines. If data
statementv are pnxlucvrd as output from other data management software and sem directly
t o A M P L , howxrver, then you m a y ignore visual appearanee and use whatever for mat is
convcnicnt.
Data f i l e s often contain numerous character strings, representing set members or the
values o f symbolic parameters. Thus in data mode A M P L does not, in general, require
strings t o be enelosed in quotes. Strings that include any character other than letters. d i g -
its. underseores, perkxl. • and - must b e q u o t e d . howvrver, as in the case o f U P . You
may use a pair o f either single quotes ( ' À & P ' ) or double quotes ( " À & P " ) , unless the
string contains a quote. in which case the other kind o f quote must surround it
(• D Q X I N I C K ' S •) or the surrounding quote must be doublod within it
('DOMINICK' 'S')«
A string that looks like a number ( f o r example ' • or • 3 e 4 ' ) must also be quoted.
t o distinguish it from a set member or parameter value that is actuaüy a number. Num-
bers that have the same internai representai ion are oonsidcrcd t o be the same. s o that f o r
example 2, 2 . 0 0 , 2 . e 0 and 0 . 0 2 E + 2 ali denote the same set member.
W h e n A M P L finishes reading a file in daia mode, h normally reverts t o whatever
nnxle it was in before the d a t a command was executed. I ience a daia file can itsclf c o n -
tai n d a t a commands that read daia from other files. If the last data statement in a data
file lacks its ter mi na ti ng scmicolon, h o w e v e r , then data nnxle persists regardless o f the
previous nnxle.
A d a t a command with n o filename puts A M P L into data nnxle, s o subsequent input
is taken as daia state me nts:

a m p l : xzodol dia tu .aodj


ampl: data;
ampl cia L a : sot KIKREQ i» A BI B2 C CAL;
ampl d a L a : sot KAXREQ t» A KA CAL;
ampl d a L a : diaplay NUTRj
s o t NITTR : = A B l B2 C CAL N A ;

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.

9.2 Data in lists


For an unindexed (scalar) parameter. a data statement assignsone value:

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.

Lists of one-dimensional sets and parameters

For a parameter indexed over a one-dimensional set like

c o t PROD:

param r a t e (PROD} > 0:

the specification of the set can be simply a listing o f its members:

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 : = b a n d s 200 coils 140 plate 1G0 :

The parameter specificatk>n could equally well be written


146 3=ECFYNGDATA CHífTÇRO

param r a t e : =
bands 200
coils 140
plaLc 160 :

since extra spaces and line breaks are ignored.


If a one-dimensional set hai been declared with the anribute ordered or
c i r c u l â r (Section 5J6), then the ordcring o f its members is taken from the daia state -
ment that defines it. For example, w e specified

SOL WKKXS := 27sop 04oct llocL lBocL ;

ai the membership o f the ordered set WEEKS in Figure 5-4.


Members o f a set must ali be dilTerent: A M P L will warn o f duplicates:

duplicaLo membor c o i l s £ o r soL PWDD


conLoxt: s o t PttDD : = b a n d s c o i l s p l a L o coils » > ; « <

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:

r a L o [ 'bands* 1 a l r o a d y doí inod


conLoxt: param r a L o : = b a n d s 2 0 0 b a n d s 160 » > : < «

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

Lists of two-dimensional sets and parameters

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:

soL ORIG: * origins


s o L DIíST: < dosLinaLions

s o L L1WKS w i L h i n ( O R I G . DESV > : * transpor LaLion links

The members o f O R I G and D E S T can be given ai f o r any one-dimensional sets:


SOL O R I G : = GARY CLKV P I T T ;
SOL DEST : = FRA DKV LAÍJ WiM STL FRK LAF •

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

o r « a list o f pairs. whhout the parentheses and commas:

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 ;

A n expression such ai { G A R Y . * } or { * , F R A ) , resembling a pair but with a component


rcpkiLvd by a is a data lemplait. Each template is f o D o w e d by a list, whose entries are
substhuted for the * t o gcncratc pairs: these pairs together make up a siice through the
dimension o f the set w h e r e t h e • appears. A tuple whhout any • ' s . l i k e {GARY, DET},
is in e f i e e t a template that s p e c i f i e s o n l y itself, so it is not follo\rcd by any values. A t the
other extreme, in the table that consists o f pairs ak>ne,

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 ;

a default template { • , • ) applies t o ali entries.


For a parameter indexed o v e r a two-dimensional s e t the A M P L list formais are again
derived from those for sets by placing parameter vahies after the set members. Thus if \v>í
have the parameter c o s t indexed over the set L I N K S :

param c o s L (LINKS} >= 0:

then the s e t data statement f o r L I N K S isextended t o b e c o m e the f o l l o w i n g p a r a m data


statement for c o s t :

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

Lists o f slice» Uuough a sei extend s i m i b r l y , by p h c i n g a parameter value after each


implied sei member. Thus. corresponding t o our concise data statement for L I N K S :

L HNXS : =
<GARY. * ) Dar LAN SVL L A P
(CLEV, * ) KRA DtfT LAN W I N STL LAK
(PITT, *) KRA WIN STL KRK ;

there is lhe f o D o w i n g staiement f o r lhe v a h i e s o f c o s t :

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

Y o u can even think o f the list-of-pairs example,

param c o s t : =
GARY DBT 14 GARY LAN 11 GARY STL 16 GARY LAF B

ai also being a case o f this f o r m , corresponding t o the default template t * . * ] .

Lists of higher-dimensional sets and parameters

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:

c o t ROUTES w i t h i n ( O R I G . DEST. PROD) :


p a r a m c o s t (ROUTES} >= 0:
SECT-GN 9 2 QftTA N L S T S 149

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

(GARY.* . c o i l s j LAN 5>FL L A F


(CLKV.* . c o i l s j FRA DKT LAN WIN STL
(PITT.* .coilsj 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

Since these l e m p b t e s h a v e t w o • ' s . t h e y must be followxrd by pairsof componcnts, which


are substituied from left t o right to generate the set members. For instance the templaie
{ • . F R A . • > f o l b w e d by C L E V b a n d s specifies thai { C L E V , F R A , b a n d s } is a m e m -
b e r o f the set.
150 3=ECFYNGDATA CHífTÇRO

A n y o f t h e a b o v e forms suffices f o r g i v i n g the vahies o f parameter c o s t ai w e l l . We


oould write

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

[ * . c o i l s l OARY LAN 11 GARY STL 1G GARY LAF B


CLKV FRA 23 CLKV D Kl* B CLKV LAN 10
CLKV WIN 9 CLKV STL 21 P I T T FRK B I

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

ai already shown above.)


M o r e generally. a template f o r an /i-dimensional set or parameter in list f o r m must
have n entries. Each entry ti either a legal set member o r a Templates for sets are
enclosed in parentheses ( l i k e the tuples in set-expressk>ns) and l e m p h t e s for parameters
are enclosed in brackets (like the subscripts o f parameters). F o l l o w i n g a template is a
series o f items. each item consisting o f one set member for each and additk>nalty one
parameter value in the case o f a parameter template. Each item defines an /i-tuple, by
substhuting its set members for the * s in the template: either this tuple is added t o the set
being specified. or the parameter indexed by this tuple & aisigned the value in the item.
A template applies t o ali item& between it and the next template ( o r the end o f the data
statement). Templates having diíTerent numbers o f * s may even be used together in the
SECT GN 0 2 DATA N L S T S 151

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.

Combined Itsts of sets and parameters

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:

param: PROD: r a L c := b a n d s 200 coils 14 0 p l a L c 1G0 :

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.

param r a L e = bands 200 coils 140 plaLc 1G0


param p r o í i t = bands 25 coils 30 plaLc 29
param m a r k e t = b a n d s G000 c o i l s 4 000 p l a L c 3SOO

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:

param: raLc proíit market : =


bands 2 00 "25 GO 00
coils 140 30 4000
piaLe 1 GO 29 3500 ;

Either way, \v\r still have the option o f adding the indexing set's name to the statement,

param: PROD: raLc proíit market : =


bands 2 00 "25 GO 00
coils 140 30 4000
piaLc 1 GO 29 3500 ;

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 :

t o s p e c i f y the membership o f L I N K S and the values o f the parameter c o s t indexed o v e r


it, or

param: LINKS : c o s t limit :


GARY Dirr 14 1000
GARY LAN 11 B00
GARY STL 16 1200
GARY LAF B 1100
CLKV FRA 27 1200
CLKV CLT 9 600
CLKV LAN 12 900
CLKV WIN 9 950
CLKV SI'L 26 1000
CLKV LAF 17 B00
PITT FRA 24 1S00
PITT WIN 13 1400
PITT SI'L 2B 1S00
PITT FRK 99 1200 ;

t o s p e c i f y the values o f c o s t and l i m i t together. T h e same options apply when lem-


plaies are used, making possible further altcrnatives such as

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 :

param: LINKS: cost limit : =


[ O A R Y , * ] D Kl* 14 1000
LAN 11 B00
STL 16 1200
LAF B 1100
[CLKV , * 1 FRA 27 1200
D Kl* 9 600
LAN 12 900
WIN 9 950
STL 26 1000
LAF 17 B00
[ P I T O , * ] FRA 24 1S00
WIN 13 1400
STL 2B 1S00
FRK 99 1200 ;

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:

param n j n i n (MIMRDJ} >= 0 ;


param n nvax (MAXRUQ} >= 0 ;

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 ;

param: nmin n nvax : =


A 700 20000
C 700
Bl 0
B2 0
. S0000
CAL 16000 24000 ;

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

error p r o c c s ssing param n m i n :


i n v a l i d subscripL n minl,?L\'l discardod.

when A M P l . first tries toaccess n _ m i n . usually at the first s o l v e .


When wxr name a set in the first l i n e o f a p a r a m statement. the set must not yet have a
value. If the specification o f parameter daia in Fígure5-1 had been given as
154 3=ECFYNGDATA CHífTÇRO

NUTR: n_min n nvax : =


A 700 2 0000
C 700 .
131 0 .
B2 0 .
NA . 50000
CAL 16000 24000 :

A M P L woukl have gencrated lhe error messagc

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 :=

because lhe declaraiion o f N U T R in the nnxlel.

M L NUTR = M1NR133 u n i o n HAXREQ;

defines il already as the union o f M I N R E Q a n d K A X R E Q .

9.3 Data in tables


T h e table format o f data. with indLcs running along the left and top cdges and values
oorresponding t o pairs o f Índices, can be mi>re concise or casicr t o read than the list for-
mai dcscribed in the previous section. l i e r e w e describe tables first for two-dimensional
parametersand then f o r s l i c e s from higher-dimensional ones. W e alsoslu>w h o w the oor-
responding multidimensional sets can be specified in tables that have entries o f • o r -
rather than parameter value entries.
A M P L also suppons a c o n v e n i e n t extension o f t h e table format, in which more than
t w o Índices may appear along the left and top edge. T h e niles f o r s p e e i f y i n g such tables
are provided near the end o f this section.

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:

param c o s L ( O R I G . DEST} >= 0:

are very naturally specified in a table (Figure 3- Ib):


param c o s L : FRA DKT LAN WIN SVL FRB LAF :=
GARY 39 14 11 14 16 82 8
CLEV 27 9 12 9 26 95 17
P1TT 24 14 17 13 28 99 20
SECT-ON 9 3 D A T A N 1/BLES 1 55

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:

param c o s L : FRA DKT LAN MIN


SVL FRK LAF :=
GARY 39 14 11 14
16 B2 B
CLKV 27 9 12 9
26 95 17
PITT 24 14 17 13
2B 99 20

Or the table may be divided columnwise into several smaller ones:

cosL: FRA DKT LAN MIN


GARY 39 14 11 14
CLKV 27 9 12 9
PITT 24 14 17 13

: SVL FRK LAF j =


GARY 16 B2 B
CLKV 26 95 17
PITT 2B 99 20 j

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:

A s \vc have seen in Section 9 2 , the mcmbership o f L I N K S can be given concisely by a


list o f pairs:

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:

param c o s t : KRA DET LAN WIN 5JTL KRE LAF : =


GARY . 14 11 . 16 . 8
CLEV 27 9 12 9 26 . 17
PITT 24 . . 1 3 28 99 . :

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 :

»Ot LINKS: KRA DET LAN WIN 5JTL KRE LAF :=


GARY
CLEV + + + + + - +
prrr + + + +

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.

Two-dimensional slices of higher-dimensional data

T o provide data f o r parameters o f more than t w o dimensions. w e can s p e c i f y the v a l -


ues in two-dimensional slices that are represented as tables. T h e rules f o r using slices are
much the same a* for lists. A s an example. consider again the üuee-dimensional parame-
ter c o s t defined by

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

(*.».OOÍlcl GARY LAN 11 GARY STL 16 GARY LAK 8


CLEV KRA 23 CLEV DET 8 CLEV LAN 10
CLEV WIN 9 CLEV STL 21 P I T T KRE 81
SECT-ON 9 3 D A T A N 1/BLES 1 57

can instead bc written in table for ma t ai

param c o s L : =

[ * , * , b a i x i c ] : FRA D Kl* LAN WIN STL FRK LAF í


CLKV 27 9 12 26 17
PlTr 24 - • 13 2B 99 •

l * . * . c o i l j = l : FRA DOT LAN WIN STL FRK LAF í


GARY . 11 16 B
CLKV 23 8 10 9 21
PITI* . BI

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 : =

( ' . ' . b a n d s j : FRA DKT LAN WIN SVL FRK LAF :=


CLKV * • « • « • - « • - « •
PlTf « • - - « • • « • -

< * . * . C O Í l s J : FRA DKT LAN WIN SVL FRK LAF :=


GARY + - - •
CLKV •
P1TI* - - - •

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:

param c o s L : FRA QBT LAN WIN STL FRK LAF


: b a n d s b a n d s b a n d s b a n d s b a n d s bands b a n d s : =
CLKV 27 9 12 . 2 6 . 17
PITT 24 . . 13 28 99

l FRA QBT LA M WIN S1'L FRK LAF


: coils coils coils coils coils coils coils :=
GARY . . 1 1 . 1 6 . 8
CLKV 23 8 10 9 21
PITT . . . . . 8 1

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:

param c o s L < LrJ : CLKV CLKV CLKV CLKV CLKV CLKV


: FRA DKT LAN WIN S1'L LAF : =
bands 27 8 12 26 17
coils 23 8 10 9 21

: P I T T P I T T P I T T P I T T GARY GARY GARY


í FRA WIN S1'L FRK LAN 5>FL LAF ! =
bands 24 13 28 99
coils . . 81 11 16 8 ;

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

Thearrangement of slices to represent muhidimensional data ha* no effect on how the


data vahics are used in the mixlel. so you can choose the most convenient format. For the
c o s t parameter above, it may be appealing to slice along the third dimensk>n. so thai the
data values are organi/cd into one shipping-cost table for each product. Aliernativety,
placing ali o f the origin-product pairs at the krft gives a panicularly concise representa-
tion. As another example. consider the r e v e n u e parameter from Figure 6-3:

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

param r c / c n u c ( p i n PROD. A R K A ( p l , 1. .T> > = 0 :

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.

9.4 Other features of data statements


Addhional features of the AMPl. data format are provided tohandle special situations.
We describe here the data statements that speeify defauh values for parameters. that
define the membership o f individual sets within an indexed collection of sets. and that
assign initial values to variables.

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.

or i f y o u faü to give a value for a parameter that doesexist:

error processing o b j e c t i v e Total_Cost:


m value for COfft(vCLEV'M'LAN'a'coils']

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;

param c o s L (ORIG. DEST. PROD} >= 0 :

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 (ORIG} >= 0:


param demand (DEST} >= 0:

but in the data w e g i v e only a default value:

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:

param c o s t (ORlG. DEST. PROD} >= 0 . d e f a u l t 9999:

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:

param h i > g e _ c o s t (PttDD} > 0:


param c o s t (ORlG, DECT. p i n PWDD} >= 0. d e f a u l t h i > g e _ c o s t ( p 1:

A discussion of d e f a u l t ' s rehú>n to the = phrase in p a r a m statements is given in


Section 7.5.

Indexed collections ofsets

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

s e t ARE A ( P R O D } ; i marke t a r e a s í o r each product

The membership of these sets is given in Figure 6-4 by:


s e t PttDD : = bands c o i l s ;
s e t AREAI bands 1 : = e a s t n o r Lh ;
set AREAlcoilsl := e a s t west export :

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:

s e t ARKA (PROD} defaulL (}:

Other wise you w i l l be warncd about any set whose data statement is not provided.

Initial values for variables

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 :

var Trans: FRA DKT LAN WIN SVL FRK LAF : =


GARY 100 100 800 100 100 SOO 200
CLKV 900 100 100 SOO SOO 200 200
Pirr 100 900 100 SOO 100 900 200 :

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: rato profit markeL Make : =


bandr. 2 00 2S GO 00 3000
coils 140 30 4000 2S00
p i a Lo 1 GO 29 3S00 1S00 :

AH o f the previously described features f o r d e f a u l t values a l s o a p p l y *> variables.


Initial vahies o f variables (as w e l l ai the values o f expressions i n v o l v i n g these initial
values) m a y be v i e w e d b e f o r e you type s o l v e . using the d i s p l a y , p r i n t or p r i n t f
commands described in Sections 12.1 through 12.4. Inhial values are also optionally
passed t o the solver, ai explained in Section 14.1 and A.18.1. A f t e r a sohition is
returned. the variables n o k>nger have their inhial values. but even then you can refer t o
the initial vahies by placing an appropriate sulTix after the variable's name. as shown in
Section A . l I .
T h e moca c o m m o n use o f initial vahies is t o give a g o o d staning guess t o a solver f o r
nonlinear optimi/ation. which ii discussed in Chapter 18.
SEC7CN9 5 FEAD N 3 Uf^CFWATTHD DATA. THE *LXD OOWW/*© 163

9.5 Reading unformatted data: the r e a d command


T h e r e a d commaiul provides a paiticularly simple w a y o f getting values into A M P L ,
given thai the values you nced are listed in a regular order in a file. T h e file must be
u n j u n m n i t d in the sense thai it contains nothing except the vahies t o be read — n o set or
parameter names. n o c o l o n s or : = operaiors.
In its simplest f o r m , r e a d specifies a list o f paramcters and a file from which their
values are t o be read. T h e values in the file are assigned t o the cntries in the list in the
order that they appear. K>r example. if you want t o read the number o f wxreks and the
hours available each wxrck for our s i m p l e produetion model (Figure 4-4),

param T > 0:

param a v a i l (1. .T> > = 0:

from a file w e e k _ d a t a . t x t containing

4
40 40 3 2 40

then you can g i v e the command

read T. avail(lj. a v a i l [21. avail[31, a v a i l [4 1 « w e e k data.txt;

Or you can use an indexing exprcssion t o say the same thing more concisely and gener-
ally:

road T. (t in 1..T} avail [tl cweek_daLa.txt:

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

road titnvlitl < fiStrmnvr ;

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:

from a fileorgani/ed by paramctcrs.you could read each parameter separately:

read (p in PWDD} p r o d e o s t [p 1 < c o s t _ d a t a :


read (p in PWDD} i n v c o s t l p l < cost__daLa:
read (p in PWDD, t i n 1 . . T } revenue [ p . t j < cost_data:
164 3=ECFYNGDATA CHífTÇRO

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

param m a r k e t (PROD. 1 . . T } >= 0:

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

param c o s t (ORIG. DliST. PROD} >= 0 . d o f a u l t 9999:

You could set up the r e a d statement as follows:

param ntriplos intoger:


param i c r . > m b o l i c i n ORIG:
param j c r . > m b o l i c i n DESl':
param k c r . > m b o l i c i n PWDD:

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,

road (t in 1..T} revenue l * bands 11;

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

( a ) U « templitesthit looltlàc (CLEV. KRA. * ) -


<b) tfcetemplates that ki<il Klr ( * . * . h a n d s j . wiéi th? Isct f<rmat.
( c ) U s e templUesthil lookHkc (CLEV. with the tible formai
(d) Specify some of éie se*'s members usirçg tcmpla«es with one and some ming templites with

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:

Coullard M259 M233 D341 D237 D239


Qiskin D237 M233 M239 D311 D239 C246 C140
Iti/en C246 D237 M233 M239 C250 C251 D239
lk»pp D237 M233 M239 D241 C251 C250
Iravani D237 C138 C l 18 D211 D239
Linetsky M233 M239 C250 C251 C2A6 D237
Mehrotra D237 D239 M239 M233 D241 C l 18 C251
Nelson D237 M233 M239
Smálowüz M233 M239 D239 D211 C251 C250 D237
Tamhaiv M239 M233 C251 C250 C l 18 C138 D237
While M239 M233 D237 C246

"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

(a) U « templstexllm l o o k l à e l * . c a s t . * ] , empkiyins éic table fcrnut.

<b) U<e (emplaft.-* úui ki<ik Kfce l * . * . 1 1 , c m p b y i i ç lhe table f o r m a l

( c ) U s e ItrmpLUes thit l « i k like l b a n d s . * . 1 1 .

9 - 6 . Gi\en t h : folkiwirç; declaraÉanx,

fl*t OR2C;
fl*t DES?;

var Trjcifl {CRZG, DEST) > - Q;

how coukl you m e a d a t i statement to avugn an ira t a l value af 300 (a ali af t h : T r a n s v a r â b t a ?


Copyright O 2003 by R<*icrt Fourcx, DavidM. Oay and Brian W. Kernighin

10
Database Access

T h e structure o f indexed data in A M P L h ^ much incommon with the structure o f the


relational tables widely used in datahase applications. The A M P L t a b l e declaration leis
you take advantage o f thissimibrity to define explicitconnections between seis. parame-
ters. variables, and expressions in A M P L and relational daiabcae tables maintained by
other software. The r e a d t a b l e and v r i t e t a b l e cx>mmands subsequently use
these connections to impoft data values into AMPL and to export data and solution values
from A M P L .
T h e relational tables read and writtcn by AMPL reside in files whose names and loea-
tions you specify a* pan o f the t a b l e declaration. T o work with these files, A M P L
relies on ktble htindltrs, which are add-ons that can be loadcd ai needed. Ilandlers may
be provided by the vendors o f solvers or datahaie software. A M P L has built-in handlers
for t w o simple rebtk>nal table formais use fui for experimentatk>n, and the A M P L wvrbsite
provides a handler that works with the widely available ODBC interface.
Th& chapter begins by showing how A M P L entities can be put into correspondence
with the columns o f relational tables. and how the same c*>rrespondences can be
described and impkrmented by use o f A M P l / s t a b l e declaration. Subsequent sections
present basic features for reading and writing externai relational tables, additional rules
for handling complicaiions that arise when reading and writing the same table, and mech-
anisms for writing a serie» o f tables or columns and for reading spreadshcet data. The
final section briefly describes some standard and built-in handlers.

10.1 General principies of data correspondence


Consider the following dcclaratk>ns from d i e t . s t o d in Chapter 2, defining the set
FOOD and three parameters indexed over it:

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:

FOOD cost £_min £ max


BKKF 3.19 2 10
CiJX 2.59 2 10
FlSil 2.29 2 10
11AM 2 . 89 2 10
WL'11 1. 89 2 10
Jfl'L 1.99 2 10
SPG 1.99 2 10
TvJR 2.49 2 10

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

| Record: " 1 1f l l 1 \> + \ O* S st

Figure 10-1: Access data entry form.


SECT C N i a i G & £ R A L R R N C P L E S O F DATA O C F F E S F O N C € N C £ 171

Parameters are not the only entities indexed o v e r the set FOOD in this example. There
are also the variables:

var Buy (j in FOOD} >= £_min[j|. <= í nvaxljj:

and a i s o n e d result expressions that m a y be displayed:

ampl: xzodol diot.xaod;


ampl: d a t a diot2a .datj

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

ampl: diaplay Buy, Buy.rc, ( j in FOOD) Buy[j)/f aax[j)j


: Buy Buy.rc Buy[ j j / £ maxl j J :=
BliliF S . 36061 B .BB17B«-16 0.536061
ciix 2 1 .1BBB4 0.2
F1S11 2 1 .14441 0.2
11AM 10 - 0 .3 02651 1
MCU 10 - 0 .551151 1
XV L 10 - 1 . 32B9 1
SP G 9 . 30605 0 0.930605
TUR 2 2 .73162 0.2

A l i o f these can be included in the relational table for vahies indexed o v e r FOOD:

FOOD cost £_min í.max Buy BuyRC BuyFrac


BI£ÜF 3.19 2 10 5.36061 B. B B 1 7 B c - 1 6 0.536061
CilX 2.59 2 10 2 1. 1BBB4 0.2
F1S11 2.29 2 10 2 1.14441 0.2
11>\M 2.B9 2 10 10 -0.302651 1
MCIL 1. B9 2 10 10 -0.551151 1
XV L 1.99 2 10 10 -1.32B9 1
SP G 1.99 2 10 9.30605 0 0.930605
TUR 2.49 2 10 2 2.73162 0.2

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

NÜTR n_min n max NuLrDual


A 700 2 0000 0
131 700 2 0000 0
B2 700 2 0000 0.404S8S
C 700 2 0000 0
CAL 1G000 24000 0
NA 0 SOO 00 -0.0030G90S

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:

KCL PttDD: * producLs


p a r a m T > 0: * numbcr o£ WMkfi

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 :

PROD T1MK markeL revenue Make Sell


bands 1 6000 2S S990 GO 00
bands 2 G000 26 G000 GO 00
bands 3 4000 27 1400 14 00
bands 4 GS00 27 2 000 2000
coils 1 4000 30 1407 307
coils 2 2 SOO 3S 1400 2S00
coils 3 3 SOO 37 3 SOO 3S00
coils 4 4200 39 4200 42 00

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

var Inv (PROD.0..T} >= 0;

T h e table would then have the f o l l o w i n g l a y o u t

PROD TIMK market revenue Make Sell Inv


bands 0 , . , , 10
bands 1 6000 2S S990 GO 00 0
bands 2 6000 26 6000 GO 00 0
bands 3 4000 2? 1400 14 00 0
bands 4 6S00 2? 2 000 2000 0
coils 0 , . , , 0
coils 1 4000 30 1407 307 1100
coils 2 2 SOO 3S 1400 2S00 0
coils 3 3 SOO 37 3 SOO 3S00 0
coils 4 4200 39 4200 42 00 0

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 > :

p a r a m c o s t ( L I N K S } > = 0: * shipnent c o s t s per unit


v a r Trans (LINKS} > = 0 ; * a c t u a l u n i t s t o be shipped

A corresponding relational table has t w o k e y columns corresponding *> the t w o c o m p o -


nents o f the indexing set L I N K S , phis a c o l u m n e a c h for the parameter and variable thai
are indexed over L I N K S :

ORIG DKST cost Trans


GARY D£TT 14 0
GARY LAF 8 G00
GARY LAN 11 0
GARY S Y L 1G 800
CLKV D£TT 9 12 00
CLKV FRA 27 0
CLKV LAF 17 4 00
CLKV LAN 12 G00
CLKV S Y L 2G 0
CLKV WIN 9 4 00
PIRR KRA 24 900
PITT FRK 99 1100
PITT S Y L 26 900
PITT WIN 13 0
1 74 OftT/eASE A C C E S S CHAPTER 10

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.

10.2 Examples of table-handling statements


Totransfcr information between an AMPL model and a relatk>nal table, \v\í begin with
a t a b l e declaration that establishes the correspondente between them. Cenain details
o f this declaration depend on the software being used to cr cate and maintain the table. In
the case o f the four-column table o f diet data defined above. some o f the possibilities are
ai follows:

• For a Microsoft Access table in a datahaic file d i e t . r x i b :

table Foods IN 'ODBC' ' d i e t .rrvdb':

FOOD < - [FOOD], cost. tjxiin. £_max;

• For a Microsoft Excel range from a worktxx>k file d i e t . x i s :

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 :

table Foods IN:


FOOD < - [FOOD], cost. tjxiin. í_aax;

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:

• H>r Microsoft Aceeis. the table is to be read from database file


d i e t . x v d b using A M P l / s ODBC handler. The table's name within the data-
baie file is taken to be Fo<3ds by defauh.

• For Mkrrosoft Excel, the table is to be read from spreadsheet file


d i e t . x i s using A M P L * s O D B C handler. The spreadsheet range containing
the table is taken to be F o < x l s by default.

• 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

I QB Foods : Table HBE3


r FOOD .:usl ( iriin 1 i rníix
I T C E E F ^ M 3.19 2 10
CHK 269 2 IIJ
FISH 2.29 2 10
HAM 2.69 2 10
MCH 1.88 2 .0
MTL 1.S9 2 10
SPG 159 2 10
ruR 2.49 2 10
*
i i i i
cord: H| IP 1 • |M>vj c » 3

Figure 10-2: Access rela!ional table.

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

X Microfüft Cacei - Diel.aU HEI ia


u |r 9 1^5 X

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.

«ampl: modol diot.mod;


a m p l : t a b l o Fooda IN "ODBC" "diot .mdb" t
ampl? rOOD < - [FOOD], coat, f min.
a m p l : road tablo Fooda;
a m p l : diaplay coat, f min, f max;
: c o s t f m i n f max :=
BKKF 3.19 2 10
ciix 2.S9 2 10
K1S11 2.29 2 10
11AM 2.89 2 10
MCT11 1.89 2 10
Jfl'L 1.99 2 10
SPG 1.99 2 10
TUR 2.49 2 10

( T h e d i s p l a y command c o n f i r m s thai lhe datahaie vahies w e r e read ai intrndcd.) If


lhe data values wxrre instead in an Excel worksheet range like Figure 10-3, the values
would be read in the sanie w a y , but using the t a b l e declaration for Excel:

«ampl: modol diot.mod;


a m p l : tablo Fooda IN -ODBC- "diot.xlo"i
«ampl? FOOD <- [FOOD), coat, f min, f max;
«ampl: road tablo Foodaj
SECT C N 102 E X A W f t E S C F T / e t E K f t M X N 3 STATE V S V T S 177

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

the declaration for a lext table would be used:

ampl: codol diot.xaod;


ampl: tablo Foods IN: FOOD <- [FOOD], coat, t min, f max;
ampl: road tablo Foodaj

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:

L a b l o I m p o r t F o o d s 1íj -ODBC- - d i c t . m d b " - F o o d s - :


F00D [F00D1. c o s t . £_min. f max:
t a b l e K x p o r t F o o d s OUT -ODIXT- - d i c t . m d b - -Foods-:
FOOD [F00D1. Buy. B u y . r c BuyRC.
( j i n FOOD} B u y l j l / f m a x l j l ~ B u y F r a c :

or a single table declaratk>n com bi ning the input and output information:

t a b l e P o o d s -0DBL*- - d i o t . m d b - : [VOOD\ I N . c o s t 111.


£ _ m i n 1?J. £ max Buy OlTT. B u y . r c ~ BuyRC <JJV.
( j i n FOOD} B u y l j | / £ m a x l j l ~ B u y F r a c OUV:

These examples show h o w the A M P L table name (such as E x p o r t F o o d s ) m a y be dif-


ferent from the name o f the corresponding table within the externai file ( a s indicated by
the subsequent string ' F o o d s ' ) • A number o f other useftil options are also seen here:
I N and OUT are associated with individual columns o f the table, ralher than with the
whole table: [ F O O D ] I N is used as an abbreviation f o r FOOD < - ( F O O D ] : columns o f
the table are associatcd with the vahies o f variables B u y and expressions B u y . r c and
Buy [ j l / f _ m a x [ j ) ; B u y . r c " B u y R C and { j i n FOOD) Buy [ j 1 / £ _ m a x [ j ] "
B u y F r a c associate an A M P L expression ( t o the left o f the " operator) with a database
column heading ( t o the right).
T o write mea ning fui resuhs back t o the Access database, w e need t o read ali o f the
diet m o d e l ' s data, then solve. and then give a w r i t e t a b l e oommand. l l e r e ' s h o w it
178 OftT/eASE ACCESS CHAPTER 10

ali might loofc using separatc t a b l e declarations t o reaJ and write the Access table
Foods:

ampl: xzodol diot.xaod;


ampl: tablo ixportFoodo IN "ODBC" "diot.xadb" "Food a" i
ampl? FOOD < - [FOOD), cost, f xain, f a s x ;
ampl: t a b l o ÍSUtr» I N "dOBC" " d i o t . x a d b " * M7TR < - [NUTR),
ampl? n xaixi, n u a x ;
ampl: tablo Mata IN "ODBC" "diot .xadb" t [NUTR, FOOD), oxat;
ampl: r o a d tablo ixsportFooda;
ampl: road tablo NUtra;
ampl: road tablo Mata;
ampl: aolvo;
ampl: tablo ExportFooda OUT "ODBC" "diot.xadb" "Fooda "t
ampl? FOOD <- [FOOD),
ampl? Buy, Buy.rc ~ BuyRC,
ampl? ( j in FOOD) Buy[j)/f xaax[j) " BuyFrac;
ampl: i f r i t o tablo ExportFooda;

and here ti an alternative using a single declaraiion to both read and write F o o d s :

ampl: xaodol diot.xaod;


ampl: tablo Fooda "ODBC" "diot.xadb":
ampl? [FOOD) IN, coot IN, f xain IN, f xaax IN,
ampl? Buy OUT, B u y . r c ~ BuyRC OUT,
ampl? ( j in FOOD) Buy[j)/f xaax[j) " Buy Frac OUT;
ampl: tablo NUtra IN "ODBC" "diot.xadb"i
ampl? NUTR <- [NUTR), n xain, n xaax;
ampl: tablo Mata IN "ODBC" "diot .xadb" t [NUTR, FOOD), oxat;
ampl: road tablo Fooda;
ampl: road tablo NUtra;
ampl: road tablo Mata;
ampl: aolvo;
ampl: i f r i t o tablo Fooda;

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

Figure 10-4: Access relational table with output cohimns.

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 a b l e T r a n s L i n k s -ODBC- " t r a n s . x l s " -Links-:


L I N K S < - IOR1G. D K S T l . c o s t I N . T r a n s OUV:

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.

10.3 Reading data from relational tables


T o use an externai rebtk>nal table for reading only, you should employ a t a b l e dcc-
laration thai specifies a readAvrite status o f I N . Thus it shoukl have the general form

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.

Reading parameters only

T o assign values from data columns ii> like-named A M P l . paramcters, it sulTices to


give a brackcted list o f key columns and then a l&t of data cohimns. The simplest caie,
where there isonly one key column, is exemplified by

t a b l e Foods IN: [FOODj . c o s t . £_min. í max:

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

FOOD cost £_min f . max


BBBP 3.19 2 10
CiJX 2.59 2 10
K1S11 2.29 2 10
11AM 2 . 89 2 10
MC 11 1. 89 2 10
XV L 1.99 2 10
SP G 1.99 2 10
TUR 2.49 2 10

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:

table SteelProd IN: [PROD. T I M E ] T markcL, revenue:

the listed daia columns, r a r k e t and r e v e n u e , must corrcipond t o A M P L parameters


r w i r k e t and r e v e n u e thai are indexed o v e r two-dimensional sets.
W h e n r e a d t a b l e S t e e l P r c d is executed. each r o w ' s entries in the key columns
are interpreied ai a pair o f subscripts t o each o f the parameters. Thus if the relational
table contento

PROD T1MK market revenue


bands 1 6000 2S
bands 2 6000 26
bands 3 4000 2?
bands 4 6500 2?
coils 1 4000 30
coils 2 2 SOO 35
coils 3 3 SOO 37
coils 4 4200 39

proccssing the first r o w will aisign 6 0 0 0 t o raarket I ' b a n d s ' . 1 ] and 2 5 to


revenue[ 'bands'«1J; pcoce&sing the second row will aisign 6000 to
r i a r k e t l ' b a n d s ' . 2 ] and 2 6 k> r e v e n u e [ ' b a n d s ' . 2 ] : and s o forth through ali
eight rows. T h e pairs o f subscripts g i v e n by the k e y column entries must be valid f o r
rwirket and r e v e n u e when the vahies o f these parameters are first needed by A M P l . ,
but the parameters need not be declared over sets named PROD and T I M E . < In fact, in the
182 OftT/eASE A C C E S S CHAPTER 10

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.

Reading a set and parameters

It is o f t e n convenient t o read the members o f a set from a table's key column or


oolumns, at the same time that parameters indexed o v e r that set are read from the data
oolumns. T o indicate that a set should be read from a table, the kty-.yiec in the table
declaration iswrkten inthe form

uri -name <- lktycolsptc. kty eolspte. ...1

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:

table Foods IH: FOOD < - [FooâNamol, cost. f_min. f max:

W h e n the c o m m a n d r e a d t a b l e Foods is executed. ali entries in the k e y column


F c c d N a m e o f the relational table are read into A M P L as members o f the set FOOD. and
the entries in the data columns c o s t , tjxiin and £ _ m a x are read into the like-named
A M P L parameters ai previously described. if the key column is named FOOD like the
A M P L set, the appropriate t a b l e declaration becomes

table Foods IH: FOOD < - l FOQDl . cost. f_min. f nvax :

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

table TransLinks IN: LINKS [ORIG. DEST] , cost:

W h e n r e a d t a b l e T r a n s L i n k s is executed, each row o f the table provides a pair o f


entries from key columns O R I G and DEST. Ali such pairs are read into A M P L as mem-
bers o f the two-dimcnsional set L I N K S . RnaDy, the entries in column c o s t are read
into parameter c o s t in the usual w a y .
A s in our pre vious mu bidimensional example. the namcs in brackets need not oorre-
spond lo sets in the A M P L model. The bracketcd nanes serve only to identify the key
columns. The name to the left o f the arrow is the only one that must name a previously
declarcd AMPL set: moreover, this set must have been declared to have the same dimen-
sion. or arity, a* the number o f key columns.
It makes sense to read the set L I N K S from a relational table, because L I N K S is
specifically declared in the nnxlel in a way that leaves the corresponding data to be read
separa lely:

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:

By contrast in the similar nnxlel t r a n s p 2 .r>c<L L I N K S is defined in terms o f t w o


one-dimensional sets:

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:

and in t r a n s p . r > c d , no namcd two-dimcnsional set is defined at ali:

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:

table TransLinks IN: IOR1G. DESV1 , cost:

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

table TransLinks IN: LINKS < - (ORIG. DESTl ;

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

A n A M P L m o d e l ' * set and parameter decbrations d o not nccessarity correspond in ali


respecfc t o the organi/atk>n o f tables in relevant data bates. W h e r e the diflerence is sub-
stantial, h may be necessary t o use the datahaie's query languagc ( o f t e n S Q L ) t o derive
temporary tables that have the strueture required by the nnxlel: an example is g i v e n in the
discussion o f the O D B C handler later in this chapter. A number o f c o m m o n , simple d i f -
ferences can be handled directly, h o w e v e r , through features o f the t a b l e declaraiion.
D i f f e r e n c e s in naming are perhaps the most c o m m o n . A t a b l e declaration can asso-
ciate a data column with a differently named A M P L parameter by use o f a d a t a - . y e c o f
the f o r m param-tuime " diila-eoS-ruttne. Thus, for example. if table F o o d s were instead
defined by

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:

l i is tempting t o l i y t o shorten dcclaratk>ns o f these Icinds by dropping the " liaht-co!-


mune, *> prcxluce, say,

table SteelProd IN:


l p ~ PROD. t ~ TIMIi | . nvarket. revenuelt.pl: * IÍRRQR

This will usually be rejeeted as an error, howxrver. because r e v e n u e I t . p ] is not a


valid name for arelational table column in most database software. Instead it is neces-
sary t o w r i t e

table SteelProd IN:


l p ~ PROD. t TIMK |. nvarket. revenuelt.pl " revenue:

t o i n d i c i e that the A M P L parameters r e v e n u e l t . p ) receive values from the column


r e v e n u e o f the table.
M o r e generally, a " synonym will have t o be used in any situatk>n where the A M P L
expression f o r the recipient o f a c o l u m n ' s data is not itself a valid name f o r a database
column. T h e r u l e s f o r valid cohimn name* tend k> be the same ai the tules for valid c o m -
ponent name* in A M P L models, but they can vary in details de pending on the database
software that is being used t o c r e a t e a n d maintain the tables.

Reading other values

In a t a b l e declaration used f o r input. an nssignoMe A M P L expressk>n may appear


any where that a parameter name would be a l l o w o d . A n expression i* assignable if h can
be assigned a value. such as by placing it on the left side o f : = in a l e t cx>mmand.
Variable name* are assignable expressions. Thus a t a b l e declaration can s p e c i f y
columns o f data t o be read into variables. for purposes o f evahiating a previously storcd
solution or providing a g o o d initial solution for a solver.
Constraint names are a b o assignable expressk>ns. Values " r e a d into a constraint" are
interpreted ai initial dual values for s o m e solvers, such ai Ml NOS.
A n y variable or constraint name qualillcd by an assignable s u f f i x is a l s o a n assignable
expression. Assignable s u f t l x e s include the predefined . s s t a t u s and . r e l a x ai wvll
ai any user-define d suffixes. K>r example. if the diet problem wx^re changed to have inte-
ger variables. the f o l l o w i n g t a b l e declaration coukl help t o provide use fui information
for the C P L K X solver (see Section 143):

t a b l e Poods IH: FOOD I N .


c o s t . £_min. f nvax. Buy. Buy.priority "" prior:

A n execution o f r e a d t a b l e F o o d s would supply members f o r set FOOD and values


for parameters c o s t , £ _ s n i n a n d £ _ r n a x in the usual w a y . and would also assign initial
values and branching prk>rities t o the B u y variables.
1 86 OftT/eASE ACCESS CHAPTER 10

10.4 Writing data to relational tables


T o use an externai relaiional table for writing only, you should employ a t a b l e dec-
laration that specifies its read/write status to be OUT. The general form o f such a declara-
tion is

t a b l e itihle mime OUV ürin%-tia^ :


key spec. d a! a spec. dttía spec t ... ;

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.

Writing rows inferred from the data specifications

1 f the key-spec is simply a bracketed lia o f the names o f key columns,

[key col nome. key-colnome. ... /

the t a b l e declaration works much like the d i s p l a y command. It determines the


externai table rows to be wrhten by taking the union o f the indexing sefc stated or implied
in the data-.spees. The format o f the diiht-spec list is the same ai in d i s p l a y , except
that ali o f the keim listed must have the same dimension.
In the simplest caie, the datasp* cs are the names o f nnxlel ootnponents indexed over
the same set:

t a b l e F o o d s OlTT: (FoodName] . í j n i n , Buy. í nvax:


SECTCN 10.4 V « T N 3 D A T A TO REIATONÍL l & L E S 187

\Vhen w r i t e t a b l e F o o d s is executei, it crcatcs a key column F c c d K a m e and data


columns £ _ m i n . Buy, and f _rnax. Since the AMPI. componente cor respondi ng k> the
daia columns are ali indexed over the AMPI. set FOOD, one row iscreatcd for each mem-
ber o f FOOD. In a representative row, a member o f FOOD is written to the key column
F c c d K a m e , and the values of £ _ m i n , Buy, and £_rnax subscriptcd by that member are
wrhten to the like-namcd data columns. For the daia used in the diet example, the result-
ing relalional table would be:

FoodName £_min Buy í nvax


B&EF 2 S. 36061 10
CiJX 2 2 10
F1S11 2 2 10
J1AM 2 10 10
MCU 2 10 10
XV L 2 10 10
SPG 2 9.30605 10
TUR 2 2 10

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

table S t e e l P r o d Ol/r: [PROD, T l M H j . Make. Sell. Inv:

Because >£ake and S e l l are indexed over { P R O D . 1 . . T ) , while I n v is indexed over


{ P R O D , 0 . . T > , asubsequent w r i t e t a b l e S t e e l P r c d c o m m a n d woukl produce a
table with one row for each member o f the unk>n o f these sets:

PROD TIME Make Sell Inv


bands 0 . . 10
bands 1 S990 6000 0
bands 2 6000 6000 0
bands 3 1400 1400 0
bands 4 2000 2 000 0
coils 0 . . 0
coils 1 1407 307 1100
coils 2 1400 2 SOO 0
coils 3 3 SOO 3 SOO 0
coils 4 4200 4200 0

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 subscquent w r i t e t â b l e N u t r s command is likely t o be rejected, because names


with a " d o t " in the middle are not allowxxl column names by most datahase software:

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:

This says thai the values represented by D i e t . l s l a c k should bc placed in a column


named l b _ s l a c k . the vahies represemed by D i e t . l d u a l should bc placed in a c o l -
umn named l b _ d u a l , and s o forth. With the table defined in this way, a write
t a b l e N u t r s oommand produces the intended rebtk>nal table:

Mutrient lb_slack lb_dual ub_slack ub d u a l


A 12 5 6 . 2 9 0 18043.7 0
Bl 336.2S7 0 18963.7 0
B2 0 0 . 4 04585 19300 0
C 982.515 0 18317.5 0
CAL 3794.62 0 4205.38 0
NA 50000 0 0 -0.00306905

T h e ~ can also bc used w h h unsuíTixed names. if it ti desired t o assign the dahata&c c o l -


umn a name diflerent f r o m the corresponding A M P l . entity.
M o r e general expressions for the values in data columns require the use o f d u m m y
Índices, in the same way that they are used in the data-list o f a d i s p l a y command.
Since indexed A M P l . expressions are rarely valid column names f o r a datah&ie. they
should generally be f o l l o w e d by " ihiia-col-mime t o provide a valid name for the corre-
sponding relational table cohimn thai is t o be wrhten. T o write a column servings
containing the number o f servings o f each food k> be bought and a column percent
g i v i n g the amount bought a percentagc o f the maximum alk>wed. for example. the
t a b l e dcclaration c o u l d be given avcithcr

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:

ta ble P u r c ha s e s Olfl*: [ FoDd>J ame 1 .


(j i n FOOD} <Buy[ j l ~ s e r v i n g s .
1 0 0 * B u y l j l / f max I j l ~ percentJ:

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

FoocfrJame sserv i n g s percenL


B8KF S. 3 6061 53.6061
CiJX 2 20
F1S1J 2 20
HAM 10 100
MCU 10 100
XV L 10 100
SPG 9. 3 0605 93.0605
TUR 2 20

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

L a b l e S L e e l S a l e s CTJV: IPROD. TIMlíl . S e l l .


( p i n PROD. t i n 1 . . T } S c l l l p . t l / m a r k o L l p . L l ~ KracDcmand:

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 .

Writing rows inferred from a key specification

A n ahernative form o f t a b l e dcclaration specifies that one table row is to be written


for each member o f an explicitly specified AMPL set. K>r the dcclaration to work in this
way, the kty-spéc must be written ai

Jrt-spec - > l kty col spec. kry -cal-spre. ...1

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:

Lablc Foods CTJV: FOOD - > lFo=d?iamel . £_min. Buy. f max:

When v r i t e t a b l e F o o d s is executed, a table row is creatcd for each member o f the


AMPL set FOOD. In that row, the set member is written to the key column F c c d K a m e .
and the values of tjxiixu Buy. and £_rnax subscripvrd by the set member are written to
1 205 OftT/eASE ACCESS CHAPTER 10

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

t a b l e F o o d s CTJV: FOOD - > IFODD1. £_min. Buy. f nvax:

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

t a b l e N u t r s CTJV: NUTR - > i 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.
D i e t . u s l a c k ~ ub_ s l a c k . D i e t . u d u a l ~ ub_dual:

and v r i t e t a b l e K u t r s woukl give the same table as previously shown.


More general expressions for the values in data columns requirc the use of dummy
Índices. Since the rows to be written are determined from the kêy-sptc, however. the
dummies are also defined there (rather than in the tiaht-spees a* in the alternative form
above). T o specify a column c\>ntaining the amount o f a f o o d bought as a percentage of
the maximum allowxxl, for example, it isnecessary to write 1 0 0 * B u y [ j ] / £ _ m a x [ j J,
which in turn requires that dummy index j be defined. The definition may appcar either
in a xebspec o f the form { index-ti si i n sti-expr }:

t a b l e P u r c h a s e s Our: ( j i n FOOD} - > l Food?Jame 1.


B u y l j l " s e r v i n g s . 100*Buyl j ] / £ _ maxl j 1 ~ p e r c e n t :

or in a key-cúj-specaf the form index " kiy-Cúl~ntime\

t a b l e P u r c h a s e s OUV: FODD - > l j ~ Foodttame 1.


Buyl j l s e r v i r ç s . 100*Buyl j ] / £ _ maxl j 1 " " p e r c e n t :

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 :

t a b l e S t e e l T o t a i CTJV: ( 1 . . T } ->• l t ~ TlMIíJ .


sum ( p i n PROD} M a k e l p . t l ~ Made.
sum ( p i n PROD} S e l l l p . t l ~ Sold:

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

since 1 . . T is a set-expression. rather lhan lhe name o f a set, it must be includcd in


braces t o be used a* a mS-spee.)
Tables corresponding t o higher-dimensional sets are handled analogously. with the
number o f listed in brackets being equal t o the dimension o f the set-xpec.
T h u s a table containing the results from s t e e l T . m o d could be defined as

table StoelProd Our:


(PROD. 1. .T> - > l PROD. TIMIíl. Make. Scll. Inv:

and a subsequent w r i t e t a b l e S t e e l P r c d would produce a table o f the form

PROD T1MK Make Scll Inv


harxis 1 5990 6000 0
harxis 2 6000 6000 0
harxis 3 1400 1400 0
harxis 4 2000 2 000 0
coils 1 1407 307 1100
coils 2 1400 2 SOO 0
coils 3 3 SOO 3 SOO 0
coils 4 4200 4200 0

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.:

or with d u m m y Índices addcd t o the k e y - c o l - s p t i * :

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.

10.5 Reading and writing the same table


T o read data from a relational table and then write results *> the same table, you can
use a pair o f t a b l e declarations that reference the same file and table names. Y o u may
also b e a b l e k> c o m b i n e these declarations into one that s p e e i f i e » s o m e columns t o be read
192 OftT/eASE A C C E S S CHAPTER 10

and others n> bc written. This sectk>n gives examples and instructions for both o f these
possibilitas.

Reading and writing using two table declarations

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

t a b l e F o o d I n p u t I N "ODBC" " d i o t l . m d b " "Diot":


FOOD l Foo d?1 ame 1. c o s t , £ _ m i n , £ nvax:

T h e corresponding declaration f o r writing the results would have a different A M P L k M e -


n a m t but would refer t o the same Access table and file:

t a b l e F o o d O u t p u t -0DI*T" " d i o t l . m d b " -Diot":


[ F o o d N a m * ] . c o s t I N . £ _ m i n I N . Buy OUT. £. nvax I N :

When r e a d t a b l e Foodlnput is executed. only the three columns listed in the


t a b l e F o o d l n p u t declaration are read: if there r> an existing cohimn named B u y , it is
ignored. Later, when the problem has becn solved and v r i t e t a b l e F o o d O u t p u t is
executed. only the one column that luti read/wrhe status O U T in the t a b l e F o o d O u t -
p u t declaration is written t o the A c c e s s table, while the table's other cohimns are left
tmmodifiúd.
A h h o u g h details may vary with the datahaic software used, the general convention is
that over writing o f an entire existing table or file is intended only when ali data cohimns
in the t a b l e declaration have read/write status O U T . Selective rewrhing or additk>n o f
columns is intended otherwise. Thus if our A M P L table for output had been declared

table FoodOu t p u t - 0 DI*T" " d i o t l . m d b " -Diot":


l FoodNamo | . Buy 0*jr :

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

table FoodOu t p u t " 0 DI*T" " d i o t l . m d b " "Diot":


l FoodNamo | . B u y :
SECTCN 106 N C € X H ? C a i F C T C * * S CF T A B L E S /WD OOLUWttS 193

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 . )

Reading and wr/ting using the same tãble declaration

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

t a b l e 1'oods *0DIX:- - d i e t l .mdb* " D i e t " :


FOOD < - l FcodNamc J. c o s t I N . £_min I N . Buy OUT, £ nvax I N :

A r e a d t a b l e F o o d s would then read only from key column F o c d K a m e and data


columns c o s t , £_snin and £_rnax. A laier w r i t e t a b l e F o o d s would write only to
the column Buy.

10.6 Indexed collections of tables and columns


In some circumstances, it is convcnicnt to declare an indexed coilection of tables. or
to define an indexed coilection of daia columns whhin a table. This section explains how
indexing of these kinds can be specified within the t a b l e declaration.
T o illustrate indexed collectk>ns of tables, w e present a script (Chapter 13) thai auto-
matically solves a series of sccnarios storcd separaiely. T o illustrate indexed oolkctions
of columns. wxr slu>whow a nv\>dimensional spreadsheet table can be read.
Ali o f our examples o f these feaiures make use o f AMPI.'s character-string expres-
sions to generate names for series o f files, tables, or columns. K>r more on string expres-
sions, see Sections 13.7 and A . 4 2 .

Indexed collections of tables

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:

t a b l e itíhle ntmie [ indexing-expr}^ üting-Stí^ : ...


1 94 OAT/EA3E ACCESS CHAPTER 10

im DietScn* : Datnfcasii H 0 E3

SDrtffcç ] fÇçuere* | H Foro* | Rawrte | Pcaes | Mrties |

E SSensBECF!
• ... ... '
••
5w i>PÍ5íi Kl
E SsmHAM

SmMCH

• SensMTl

• ScrwSPC

Figure 10-5: Access databaie with tables o f sensilivily analysis.

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

1 P^xfd: « 1 _LI1 ^ • I.MMCf 3 4 | r

F i g u r e 1(M>: Ahcrnatc Access table for sensitivity analysis.

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 a b l e D i e t S e n s ( j i n FOOD} "0DI*T" - DietSens.mdb":


[ F o o d l . Buy ~ ( " B u y " & j ) :

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

Figure 10-7: Two-dimcnsional AMPL table in Excel.

Indexed collections of data columns

Because there is a natural ocxrespondence between ilata columns o f a relational table


and indexed collections of entities in an AMPL model, each diiht-.yec in a t a b l e decla-
ration normally refers to a diíTerent AMPL parameter. variable,or expiession. Oceasion-
ally the values for one AMPL entity are split among multiple data columns, howvrver.
Such a caie can be handled by defining a collection of data columns, one for each mem-
ber of a specified indexing set.
T h e most common use o f this feature is to read or write two-dimensional tables. For
example, the data for the parameter

param amt (NITTR.FOOD} >= 0:

from d i e t . m c d might be represented in an Excel spreadsheet as a table with nutrients


labeling the rows and foods the columns (Figure 10-7). T o read this table using AMPL's
externai datahaic features, must regard h as having one key column, under the head-
ing NUTR, and data oolumns headed by the namesof individual ftxxls. Thus w e require a
t a b l e declaration whose by-spec is one dimensional and who&e dutu-specs are indexed
over the AMPL set FOOD:

table dietitats IN -ODBC- - D i e t 2 D . x l s - :


l i ~ NUTRI, ( j i n FOOD} < a m t ( i . j l ~ <jj>:

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 > :

or, equivalcntly. using d i s p l a y - s t y l e indexing:

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

(indtxin%-rxpr) < áiitisprc. spec. dasa spte. ... >

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.

10.7 Standard and built-in table handlers


T o work whh externai database files. A M P L relies on table handlers. These are add-
ons. usually in the form o f diaied or dynamk: link libraries, that can be loaded ai needed.
1 98 OAT/EA3E ACCESS CHAPTER 10

=b FJt v j w Inscrt format lote v&úow WE Pct» - I g l x|


A H 0 II E h (i | H
[Product HM1 Maket saiu Imrl Make? 9>?M? i w ? füake3 St
bands 10 5990 t200 Ò 6003 600C 0 1430
coils 0 1407 30? 11 oo 1403 250C 0 35 30

|
H:4 • H\RC»U*»I Á R*gJts2 / M l >jr

Figure 10-8: Another tw\>-dimensional Excel table.

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.

Using the standard ODBC table handler

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

"0DBL*" mctmnecibn»sprC "exkrrnal-iahkr-specm * verbos©*,^


SECT-ON 10.7 S l t t & A F G A N D E U L T N TAfitE K f t M X E R S 199

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

" S QL= query "

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:

t a b l e c h e a p F o o d s 1ÍJ "OüQC" -dict.mdb*


-S0L=SKLKCT * FROM Foods WHHRK c o s t < = 2.49-:
FOOD < - [FOODl. c o s t . £_min. f m a x :

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:

o p L i o n s o l o c t A m t s "SKLBCT N17TR. A m t s . FOOD. amL -


"FROM A m t s . Foods "
-WHERE ítaits .FOOD = F o o d s . FOOD arxi c o s t <= 2 . 4 9 - ;

L a b l c choapAmts I N "ODBC" "dict.mdb- < " S 0 L = " U $sclccLAmLsJ :


INITTR. FOODl . amL :

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

T o set up a relational table correspondence for reading or writing Microsoft Aceeis


files, specify the exi in the second string of the string-list ai r»db:

"0Di*T" -fJenamr.mdb- -trxirrnaUahlrxptc-^

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 :

-0DB1*- *füma»lí-.xls" -exkrrnaUahltsptc

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.

Built-in table handlers for text and binary files

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 -

the file is taken t o be an ASCII text f i l e : if h ha* the f o r m

-fútnt\n\r. b i t **

it is taken t o be a binary file. if n o string-Üsi is g i v e n . a text file kibltniunt. t a b is


aisumed.
For reading, the indicated file m u s t e x i s t H>r writing, if the file does not exist, it is
created. If the file exists but ali o f the t a b l e declaration's daUt-sptc* have readÀvrite
status OUT, h is overwrkten. Otherwise, writing causes the existing file t o be nuxlified:
each column written either replaces an existing cohimn o f the same name. or becomes a
new cohimn added t o the table.
T h e format for the text files can be examined by writing one and viewing the rcsults
in a text editor. For example, the f o l l o w i n g A M P l . session,

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;

produces a file D i e t O p t . t a b with the f o l l o w i n g content:

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

A M P l . providos a variety o f c o m m a n d s like rr>cdei, s o l v e . and d i s p l a y thai tcll


the A M P l . m o d e l i n g system what t o d o whh models and data. Although these oommands
may use A M P l . expressions, they are not pari o f the modeling languagc hself. They are
intended t o be used in an environment where you g i v e a cx>mmand. wait f o r the system t o
d i s p b y a response. then decide what command to g i v e next. Commands might be typed
directly. or given implicitly by menus in a graphical user interface like the ones availabkr
on the A M P l . w e b site. Commands a b o appear in scripts. the subject o f Chapvrr 13.
This chapter begins by describing the general principies o f the command environ-
ment. Section 11.2 then presents the c o m m a n d s that you are likcly t o use most for setting
up and solving optimi/ation problems.
A f t e r solving a problem and looking at the rcsults, the next step is o f t e n ii> make a
changc and s o l v e again. T h e remainder o f this chapter explains the variety o f changes
that can be made without restarting the A M P l . session from the beginning. Section 11.3
describes commands for re-reading data and m o d i f y m g speeific data values. Section 11.4
describes facilhies for oomptetely delcting or redefining nxxlcl componcnts. and for lem-
porarily dropping constraints, fixing variables, or r c b x i n g integrality o f variables. <Con-
venient commands for examining nuxlel information can be found in Chapter 12, espe-
cially in Section 12.6.)

11.1 General principies of commands and options


T o b e g i n an inwrractivc A M P l . session, you must start the A M P l . program. for e x a m p l e
by typing the command a m p l in response t o a prompt o r by selecting it from a menu or
clicking on an icon. T h e stanup prix.cdure necessarily varies somewhat from one operat-
ing system toanother: for detaik. you should refer t o the system-speeific instructk>ns that
c o m e with your A M P L software.

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:

ampl: diaplay {i in ORIG, j in DEST)


ampl? sun {p in PROD) Trana [ i , j, p) ;

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 : o p t i on praxsptl, dl a play xrldth;


o p L i o n promptl 'ampl: •;
o p t i o n d i s p l a y _ w i d L h 7 9:
ampl:

A * in an option name is a 4 *wild card'' lhai matches any sequcnce o f characters:

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:

a m p l : option prarsptl "A> dlaplay uldth 60;


A> option dlaplay irldth;
o p L i o n d i s p l a y _ w i d t h GO:
A>

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:

a m p l : option cplox options;


option cplox options ' ' ; #not doíinod

T o return ali options to theirdefauh values, use the command r e s e t options.


A M P L maintains no maiter list o f valid options, but rather accepts any new option that
you define. Thus if you mis-type an option name. you will nuxst likely define a n e w
option by mistake. ai the following example demonstrates:

a m p l : option dlaplay xrdlth 60;


a m p l : option dlaplay xra;
o p t i o n d i s p l a y wdith 60:
option display_widLh 7 9:

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

11.2 Setting u p a n d solving models and data


T o apply a sol ver to an instance o f a nnxlel. lhe examples in this book use m o d e l ,
d a t a , and s o l v e commands:

a m p l : modol diot.modj data dlot.dat; aolvo;


M1NQS S . S : o p t i n v a l s o l u t i o n í o u n d .
6 i t o r a t i o n s , o b j o c t i v © BB. 2

The m c d e l command name* a file thatcontains nnxlel decbrations (Chapters 5 through


8X and the d a t a command names a file that containsdata values for nxxlel components
(Chapter 9). The s o l v e command causes a description o f the optimizaiion problem to
be sent to a sol ver, and the re*ults to be retrieved for examinaiion. This sectk>n takes a
closer look at the main A M P L features for setting up and solving models. Kratures for
subsequently changing and re-solving models are covered in Section 11.4.

Entering models and data

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

T h e s o l v e command sets in motion a seriei of activities. First, it causes AMPL to


gcneraie a specific optimi/ation problem from the nnxlel and data that you have supplied.
If you have neglected to provide some needed data, an error messagc is printed: you will
also get error messages if your data values violate any restrictions imposed by qualifica-
tion phrases in v a r or pararr»declarations or by c h e c k statements. AMPL waitsto ver-
ify data restrictions until you type s o l v e , because a restriction may depend in a compli-
cated way on many different data values. Arithmetic e r r a s like dividing by zero are also
caught at this stage.
After the optimi/ation problem is generated, AMPL enters a 4 'presolve" phase that
tries to make the problem easier for the solver. Sometimes presolve so greatly reduces
the si/e o f a problem that h become substantially easier to solve. Normally the work o f
presolve gtxs on bchind the scenes, however, and you need not be conccrned about it. In
rare cases, presolve can substantially aflect the optimal values o f the variables — when
there is more than one optimal solution — or can interfere with other preprocessing rou-
tines that are built into your solver software. A b o presolve sometimes detects that no
feasible solution is possible, and so dcxs not bother sending your program to the solver.
For example. if you drastieally reduce the availability of one resource in s t e e l * .mcd,
then AMPL produces an error messagc:

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:

a m p l : rsodol atoolT.aod; data stoalT.dat;


ampl: aolvo;
MINOS 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 S1S033
208 MOC€LN3 COUVA!*y$ CHOTERI1

ampl: raaot;

ampl: codol ataolT.xsod;

ampl: data ataolT.dat;

ampl: option aolvor cplax;

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: izodal ataolT.xsod;

ampl: data ataolT.dat;

ampl: option aolvor anopt;

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

11.3 Modifying data


M a n y nnxleling projects i n v o l v e solving a series o f problem instances, each defined
by somcwhat dilTerent daia. W e describe hcre A M P L ' s facilhies f o r resetting parameter
values while leaving the nxxlcl as is. They include cx>mmands for resetting data nxxle
input and for reiampling random parameters, as wxrll ai the l e t command f o r direetly
assigning n e w values.

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:

roixit data M l D J . MAXRHQ. amt, njnin. n max:

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

update data M12JRUQ. MAXRKQ. amt. n_min. n max:

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

T h e r e s e t d a t a c o m m a n d also acts t o resample the randomly computed parameters


described in Section 7.6. Continuing with the variant o f s t e e l 4 . r > c d intnxluced in
that section. if the definhion o f parameter a v a i l & changed s o that its value is given by
a random funetion:

param a v a i l mean ( S r A G l í } >= 0:


param a v a i l _ v a r i a n c e ( S r A G l í } > = 0:

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 ) ;

with corresponding data:

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 : xsodal atool 4r. xood;


a m p l : data atool4r.dat/
ampl: aolvo;
M1NQS S . S : o p L 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 1B7632.24B9

a m p l : diaplay avail/
rchcaL 3 2 . 3 504
rol1 43.03B ;

a m p l : raaot data avail/


ampl: aolvo;
M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
4 i L c r a t i o n s . o b j o c t i v c 1SBBB2.901

a m p l : diaplay avail/
rchcaL 32.0306
rol1 32.6BSS ;

Only r e s e t d a t a hasthiseftect: i f y o u issue a r e s e t comirand then AMPL*srandom


number generalor is reset, and the values of a v a i l repeat from the beginning. (Section
7.6 cxplains how to reset the generator's " s e e d " to get a diíTerent sequencc of random
number s.)

The let command

T h e l e t command a b o pcrmits you to change particular data values while leaving


the nnxlel the same. but it is more convenient for small or easy-to-describe changes than
r e s e t d a t a or u p d a t e d a t a . You can use it, for example. to solve the diet nnxlel of
Figure 5-1. trying out a series of upper bounds £_rnax [ •OOC* ] on the purchases of
food CHK:

ampl: xzodol diotu.xood/


ampl: data diotu. 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 .
S i t c r a t i o n s . o b j o c t i v c 74.273B2022

ampl: l o t f xsaxl-CHK") i» 11/


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 c r a t i o n s . o b j o c t i v c 73.43B1B1B2

ampl: l o t f xsaxl-CHK") i» 12;


ampl: aolvo;
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
0 i t c r a t i o n s . o b j o c t i v c 73.43B1B1B2

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

A n indexing expression may be given after the k e y w o r d l e t , in which case a change


is ma de f o r each member o f the specified indexing set. Y o u could use this feature t o
change ali upper bounds t o 8 :

let (j in FOOD} f nvaxljl := 8:

or t o incr cave ali upper bounds by 10 percent:

let (j in FOOD} f nvaxljl := 1.1 * f maxljl;

In general this c o m m a n d consisti o f the k e y w o r d l e t , an indexing expressk>n if needed.


and an assignmeni A n y set or parameter whose declaration does not d e f i n e it using an =
phrase may be specified t o the left o f the assignment's : = operator. whikr ti> the right
may appear any appropr iate expression that cancurrently be evahiated.
A h h o u g h AM PI. does not impose any restrictions on what you can change using let,
you should take c a r e in changing any set or parameter that alYects the indexing o f other
data.
For example, after solving the multiperiod produetion problem o f Figures 4 - 4 and 4-5,
it might be tempting t o change the number o f weeks T from 4 < as given in the original
data) t o 3:

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 :

Use 1 . . T d a t a for indexing in the p a r a m declarations. whikr retaining 1 . . T for the


variables. objeetive and constraints: then you can use l e t t o change T as you like.
Y o u can also use the l e t c\>mmand k> change the current values o f variables. This is
somei imes a convenient feature for exploring an alternative solution. For example. here
212 M0C€LN3 OOWVANDS CHOTERI1

coil (x) arilingof.Y (ncxt hçhrr infcrgcr)


£ l o o r <ATJ fki<rof.v (ncxf lowcrinlcgcr)
p r o c i s i a n <*, n ) .t nninJcd «ci n signific-int digits
r o u n d < * . n} .t nninJcd «ci n digito p t d ú\c dccmul jxiint
round<,x) x rciurxlcd «ci th: ncarcat intcgcr
L runc (x* n} * trurvatcd ki n digito panl #ic dccmul jxiint
Lrunc(*J x trurvatcd k» an mtrgcr ((raclxiiul jurt drcippcd)

T a b l e 11-1: Rouiuling funetions.

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:

a m p l : c o d o l diotu.xood; data diotu.dat; aolvo;


M1NQS S . S : o p t i m a l s o l u t i o n í o u n d .
S i t o r a t i o n s . o b j o c t i v e 74.27382022

a m p l : lat ( j in FOOD) Buy[j) t* floor(Buy[j))j


a m p l : diaplay Total Coot, n ssin, Diot Min. alack;;
ToLal_Co=L = 70. B

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.

11.4 Modifying models


Several commands are provklcd t o h e l p you make limited changes t o the current
nnxlel, wkhout nnxlifying the nnxlel file or issuinga full r e s e t . This section describes
o o m m j n d s that completely remove or redefine nnxlel components, and thai temporarily
drop constraints. fix variables, orrelax imegrality restrictions on variables.
S E C T . O N 11 4 W C D F Y N 3 WCC€LS 213

Removing or redefining model components

T h e d e l e t e command removes a prevk>usly d c v b r e i l nnxlel component, provido d


that no other components use it in their decbrations. T h e form o f the command is simply
d e l e t e foltowed by aoomma-scparated list o f n a m e s o f nnxlel components:

ampl: modol diotobj. ao d;


ampl: data diotobj.datj
ampl: doloto Total Nuxsbor, Diot Kin;

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:

T h e command p u r g e £ _ m i n deletes parameter £_snin and the components w h o s e dec-


larations refer tt> t j x i i i u including parameter £_rnax and variable B u y . It also deletes
objective T o t a l _ C o s t , which depends indirectly on í j m i n through hs reference t o
Buy.
I f y o u ' r e not sure which components depend on s o m e g i v e n component, you can use
the x r e £ command t o f i n d out:

a m p l : xrof f min;
i 4 ontitics d e p e r x i on £_min:
£_max
Buy
Total_Cost
Diot

L i k e d e l e t e and p u r g e , the x r e £ c o m m a n d can be applied t o any list o f mixlel c o m -


ponents.
Once acomponcnt been removed by d e l e t e or p u r g e , any previously hidden
meaning o f the c o m p o n e n t e name becomes visible again. A f t e r a conslraint named
p r c d isdeleted, f o r instance, A M P L again recognizes p r c d ai an iterated muhiplication
operator (Tabkr 7 - 1 ) .
I f there is n o prevk>usly hidden meaning, the name o f a component removed by
d e l e t e or p u r g e b e c o m e s again unused, and may subsequently be declared as the
name o f any new component o f any type. If you only want t o make some relatively l i m -
ited modifications t o a declaration, h o w e v e r , then you will probably find r e d e c l a r e t o
be more convenient. Y o u can change any c o m p o n e n t ' s declaration by wrhing the k e y -
214 MOC€LN3 COUVA!*y$ CHOTERI1

w o r d r e d e c l a r e f o D o w e d by the complete revised declaration that you woukl like t o


substhutc. L o o k i n g again at d i e t . rr»cd. for example.

ampl: rodoclaro parais f min (FOOD) > 0 into&or/

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 .

Changing the model: f i x , unfix; drop, reatore

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;

A d r o p c o m m a n d can s p e c i f y a particular one o f these constraints t o ignore:

drop Diot MaxfCAL-1 :

or it may specify ali constraints or objectives indexed by some set:

drop (i in MAXNOT} D i e t MaxUl;

where MÀXNOT has previously been d e f i n e d ai s o m e subset o f XAXREO- T h e entire c o l -


lection o f constraints can be ignored by

drop (i in MAXRl*)} D i e t Max [ i j ;

or more simply:

drop Diet Max:

In general, this c o m m a n d c o n s i s t s o f the key w o r d d r o p , anoptional indexing expressk>n,


and a constraint name that may be subscripted. Successive d r o p commands have a
cumulative e f t e c i
T h e r e s t o r e command reverses the elYect o f d r o p . It has the same syntax, except
for the key w o r d r e s t o r e .
SECT.ON 11 4 W C D F Y N 3 WCC€LS 215

T h e i i x command f i x e » specificd variables ai their current values, as if there w e i e a


constraint that the variables must equal these vahies: the u n ü i x command reverses the
e f f e e t . T h e s e commands have the same syntax ai d r o p and r e s t o r e . except that they
name variables rather than constraints For example, here inituli/e ali variables o f
our diet problem t o their lowxrr bounds. fix ali variables representing foods that have m o r e
than 1200 m g o f sodium per package. and optimize o v e r the remaining variables:

a m p l : lat ( j in FOOD) Buy [ j ) : * f min[j);


a m p l : f i x ( j in FOOD: amt ["NA", jJ > 1200) Buylj);
ampl: aolvo;
MINOS S . S : o p t i m a l s o l u t i o n f o u n d .
7 i t e r a t i o n s , o b j e c t i v e 8 6 . 92
O b j e c t i v e = T o t a l C o s L l 'A&P ' 1

a m p l : diaplay ( j in FOOD) (Buy l j ) .lb, Buy [ j ] , axst [mNAm,jJ );


: Buylj1.1b Buylj1 amt[ 'NA*. j ] :
BKEF 2 2 938
ciix 2 2 2180
F1S11 2 10 94S
J1AM 2 2 278
MC1I 2 9 . 42857 1182
XV L 2 10 896
SPG 2 2 1329
TUR 2 2 13 97

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:

ampl: f i x (j in FOOD: asst [" KA", j ) > 1200) Buylj) *« fsainlj);

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

Changing optk>n r e l a x _ i n t e 9 r a l i t y from its default o f O to any n o m e i o value:

option reiax_integrality 1;

tells A M P L to ignore ali restrictions o f variables to integer values. Variables dcclarcd


inte^er get whatever bounds you specified for them, w h i l e variables dcclarcd
b i n a r y are g i v e n a l o w e r bound o f zero and an upper bound o f one. T o restore the inte-
grality restrictions. set the r e l a x _ i n t e g r a l i t y optk>n h a c k t o O .
A v a r i a b l e s name followxrd by the s u f f i x . r e l a x indicates its current integrality
relaxation status: 0 if integrality is enforced. noa/cr o otherwise. Y o u can make use o f
this suftlx to relax integrality on selected variables only. For example.

let Buy [ ' C M C ' 1 . r e l a x = 1

relaxes integrality only on the variable B u y [ ' C H K ' 1, w h i l e


216 M O C € L N 3 COUVA!*y$ CHOTERI1

leL (j in FOOD: £_minlj] > allcw_£rac} Buyljl.rclax := 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 :

var Buy (j in FOOD} inLogcr >= £_minlj|, <= s c a l o * £_jnax(j) :

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 : option ralax intovrality;


o p L i o n r c l a x _ i n L o g r a l i t y 0:

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 : option cplox option a 'ralax' j


ampl: aolvo;
CPLUX B . 0 . 0 : rolax
I g n o r i n g i n L o g r a l i L y o£ B v a r i a b l e ; : .
CPLttX B . 0 . 0 : q p L i m a i s o l u L i o n ; o b j o c L i v e 120.24210S7
2 d u a i s i m p l o x i L o r a L i o n s <0 i n pha.^o IJ

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

If insfóad option r e l a x _ i n t e < j r a l i t y is set t o I, presolve leaves the upper iimits at


9.5 and sends those t o the solver. with the result being a less constrained problem and
henee a lower objeetive value:

a m p l : option ralax intovrality 1;


ampl: aolvo;
CPLKX 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 119.1S07545
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

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.

12.1 Browsirtg through results: the d i s p l a y command


T h e easiest way to examine data and result values is to type d i s p l a y and a descrip-
tion o f what you want to kx>k at. T h e d i s p l a y command automatically formato the val-
ues in an intuhive and familiar arrangement: as much as possible, it uses the same list and
table formais as the data statements described in Chapter 9. Our examples use parameters
and variables from m o d c k defined in other chapters.

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:

a m p l : diaplay ORlG, DE ST, LIKKS;


M L O R l G : = GARY CLHV P I T T :
s e t DKST : = FRA DKY LAN WIN SYL FRK L A F :
s e t L I N K S : =

(OARY.DKT) (GARY.LAF) <CLKV. LANJ (CLKV. LAF) (PITT.OTL)


(OARY.LAN) (CLKV, FRA) (CLKV.W1NJ (P1TT.FRAJ (PITT.FRK)
(GARY. S T L ) (CLKV.DKD ( C L K V . SYL} (PITT. WIN);

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 ) :

a m p l : diaplay PROD, AREAj


KCL PttDD : = b a n d s c o i l s :
SOL A R K A ( b a n d s ] : = o a s L n o r L h ;
SOL A R K A [ c o i l s ] := oasL wcst export:

Particular members o f an indexed collcction can be v i e w c d by subscripting. as in


d i a p l a y AREAJ •b a n d s •
T h e argument o f d i s p l a y need not be a declarcd set: it can be any o f the expres-
sions described in Chapter 5 or 6 that evaluate t o sets. For example, you can show the
union o f ali the sets Á R E A [ p l :

ampl: diaplay union {p in PROD) AREAl p);

SOL union (p in PttDD} ARKAlpl := oasL nart-h w c s t export:

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.

Displaying parameters and variables

T h e d i s p l a y command can show the value o f a scalar nuxlel component:


SECTCN 12.1 BROVtfS N3 T>TOUGH RESULTS THE OISPIAT OCWW/ND 221

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):

a m p l : diaplay a v a i l [ "rahaat "J, avail[ "roll "Jj


avail [ ' r e h e a f l = 3S
avail ['rolIa 1 = 4 0

or an arbitrary expression:

a m p l : diaplay a in (1) ~2 • coa(l)"2j


s i n < l ) " 2 «• c o s ( 1 J " 2 = 1

T h e major use o f d i s p l a y , h o w e v e r , fc t o show w h o l e indexed c o i l e c t i o n s o f data. F o r


" o n e - d i m e n s i o n a r ' data — parameters or variables indexed over a simple set — AMPL
uses a column format (Figure 4 - 6 b ) :

a m p l : diaplay avail/
a v a i l 1*1 : =
reheaL 3S
rol1 40

For ' t w o - d i m e n s i o n a l " parameters or variables — indexed over a set o f pairs or t w o


simple sets — A M P L forms a list for small amounts o f data ( F j g u r e 4-1):

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

or a table for larger amounts:

ampl: diaplay dcazand;

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):

ampl: diaplay coat;


cost :=
CLKV DKT 9
CLKV FRA 27
CLKV LAF 17
CLKV LAN 12
CLKV SVL 26
CLKV W1?J 9
GARY DKT 14
GARY LAF 8
GARY LAN 11
GARY SVL 16
PITT FRA 24
PITT FRK 99
PITT SVL 28
PITT WIN 13

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):

a m p l : diaplay invO, prodeoat, inveoat/


: invO p r o d c o s L i n v c o s L :=
bands 10 10 2.S
coils 0 11 3

or two-dimcnsional (Figure 4-6):

ampl: diaplay rato, xoako cost, KaXo;


: r a L e makc c o s L Makc
CLKV harxis 190 190 0
CLKV coils 130 170 19S0
CLKV plaLe 160 IBS 0
GARY ha reis 200 180 112 S
GARY coils 140 170 17S0
GARY plaLe 160 180 300
PITT ha reis 230 190 77 S
PITT coils 160 180 SOO
PITT plaLe 17 0 18S SOO

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

ampl: diaplay avail;


avail l*I :=
27 s e p 40
04ocL 40
llocL 32
lBocL 40

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.

Display ing indexed expressions

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 :

ampl: diaplay s u e (p in PROD,t in 1.. T) rovonuo lp, t) éSoll lp, t) ,


ampl? SUE {p in PROD,t in 1.. T) prodeoatlp) 'Jtoko[p, t),
ampl? SUE {p in PROD,t in 1..T) inveoat [p) êInvlp, t);
surníp in PROD. t i n 1 . . T> r e v e n u e l p . t l * S e l l l p . t l = 7 8 7 8 1 0
sumCp in PROD. t i n 1 . . T> p r o d c o s t l p p M a k e l p . t l = 2 6 9 4 7 7
sum(p in PROD. t i n 1 . . T> i n v c o s t l p 1 * I n v l p . t l = 3 3 0 0

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 : diaplay rovonuo • Soll;


syntax error
context: d i s p l a y revenue » > * < « Sell:

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:

a m p l : diaplay (p in PROD, t in 1..T) rovonuolp, t) • Soll lp, t);


r e v e n u e lp. t p S e l l lp. t l l * . * l <trj
• bands coils
1 1S0000 9210
2 156000 87500
3 37 800 12 9 5 0 0
4 54 000 163800

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

A n indexing expression f o l b w e d by an expression or parenthesi/ed list o f expressk>ns is


ireaied ai a single display item. which specifies some indexed collection o f values. A
d i s p l a y command may oontain one o f these i t e m s a s above, or a comma-separated list
o f them.
T h e presentation o f the values for indexed expressions f o l l o w s the same mies as f o r
individual parameters and variables. In f a c t you can regard a command like

display revenue, Sell

ai shonhand for

ampl: diaplay {p in PROD, t in 1..T) (rovonuo [p, t) , Soll [p, t) ) ;


i revenue lp,t| S e l l l p . t l : =
bands 1 25 6000
bands 2 26 6000
bands 3 27 1400
bands 4 27 2000
coils 1 30 307
coils 2 35 2500
coils 3 37 3500
coils 4 39 4200

If you rearrange the indexing expression s o that t i n 1 . . T c o m e s first, h o w e v e r . the


r o w s o f the list are instead sorteei first on the members o f 1 . . T :

a m p l : diaplay {t in 1. .T, p in PROD) (rovonuo [p, t) , Soll [p, t) ) ;


i revenue lp,t| S e l l l p . t l : =
1 bands 25 6000
1 coils 30 307
2 bands 26 6000
2 coils 35 2500
3 bands 27 1400
3 coils 37 3500
4 bands 27 2000
4 coils 39 4200

T h i s c h a n g e in the default presentatk>n can only be achieved by placing an explicit index-


ing expression after d i s p l a y .
226 D3=LAYCOVVAfC<S C H í f T E R 12

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

Transli . j. •coils' 1 l * . M <trj


: CLKV GARY P1TT :=
DKT 7 S0 0 0
FRA 0 0 SOO
FRK 0 BS0 0
LAF SOO 0 0
LAN 4 00 0 0
STL S0 900 0
WIN 2 S0 0 0

T r a n s l i . j . •plaLc ' 1 l * . * l <tr)


: CLKV GARY PITT : =
DKT 0 0 100
FRA 0 0 100
FRK 0 100 0
LAF 0 0 2S0
LAN 0 0 0
STL 0 2 00 0
WIN 0 0 SO

A s this example shows, i f a d i s p l a y command s p e c i f i e s a n indexing expression right at


the beginning, followxxl by a colon. the indexing set applics to the whole c\>mmand. F o r
S E C T C N 12.2 F O W A T T N 3 OPTONS FOR DXSP2AY 227

di.cplay_lcol nuLximum clcmcntx for A «atile l o be dupl-iwd in Iwl í t m m (20)


d i .cp l a y _ L r a nOTOÍXS (rjLmpc)sc tablm if xxrws- colunim < d i s p l a y _ _ t r a n s p o s e <0>
d i .cp l a y _w i d L h nuixinium line width <79)
guttcr_widt_h scpirjukin b e t w x n ttbk columns <3)
ccniL_2«ro_colss if not d omit JLU zero columns frcizn duplays (0)
il not ( l <niit ali-zero rows fromdttpliys (0)

T a b l e 12-1: Formatting options f o r d i s p l a y ( w i t h default values).

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.

12.2 Formattirtg options for d i s p l a y


T h e d i s p l a y c o m m a n d uses a f e w simple rules for choosing a gcxxl arrangement o f
data. By changing several options, you can cx>ntrol overall arrangement, handling o f zero
values. and line width. These options are summari/ed in T a b l e 12-1, with default values
shown in parentheses.

Arrangement of lists and tables

T h e display o f a one-dimensional parameter or variable can prcxluce a v e r y long list,


av in this example from the scheduling nnxlel o f Figure 16-5:

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 option d i s p l a y _ l c o l can be used k> request a more compact formai:

a m p l : option diaplay lcol 0;


a m p l : diaplay roquirodj
r c q u i r c d 1*1 : =
F r i l 100 M o n l 100 S a L l 100 Thu2 7B Tuo2 76 Wed2 7B
Fr i 2 7B Mon2 7B SaL2 7B Thu3 52 Tua? 52 Wod3 52
Fr i 3 52 Man3 52 T h u l 100 Tucl 100 W«âl 100

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:

ampl: option diaplay lcol 0;


ampl: diaplay coat;

cosL l*.*J < LrJ


: CLKV GARY P I T T :=
DKT 9 14
FRA 27 . 24
FRK . . 99
LAF 17 B
LAN 12 11
SVL 26 16 2B
WIN 9 . 13

A dot ( . ) entry indicates a nonexistentcombinatk>n in the index set. Thus in the G A R Y


column o f the table, there t% a dot in the F R A r o w because the pair { G A R Y . F R A } is not a
member o f L I N K S : n o c o s t [ • G A R Y ' . • F R A ' 1 is dcfined for this problem. On the
other hand. L I N K S does contain the pair { G A R Y . L A F ) . and c o s t [ • G A R Y ' . • L A F ' J
is shown ai 8 in the table.
In choosing an orienta ti on for tablcs. the d i s p l a y c\>mmand by default favors rows
over columns: that is. if the number o f columns would exceed the number o f r o w s , the
table is transposed. Thus the table f o r d e r w i n d in the previous section has rows labeled
by the first coordinaic and columns by the second, because it is indexed o v e r D E S T with
SECT-ON 12.2 F O W A T T N 3 OPTQNS FOR D i s n - x r 229

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:

a m p l : option diaplay tranapoao 3/


a m p l : diaplay d ar: and j
denvand l * . * l (trj
: DKT FRA FRK LAF LAN STL WIN
bands 300 3 00 22 5 2 50 100 650 75
coils 750 500 850 500 400 950 2 50
plaLe 100 100 100 2 50 0 200 50

while negative values tend tosupprcss i t

a m p l : option diaplay tranapoao -3;


a m p l : diaplay coatj
cost [*,*J
: D Kl* FRA FRK LAF LAN STL
CLKV 9 27 17 12 26
GARY 14 , 8 11 16
PITT 24 99 28

T h e m i e is ai folk»ws: a table is transposed only when the number o f r o w s minus the


number o f columns would be less than d i s p l a y ^ t r a n s p o a e . A t its default value o f
zero, d i s p l à y _ t r à n s p o s e gives the prevk>usly described default behavior.

Control of Une width

T h e optk>n d i s p l a y _ v i d t h gives the maximum number o f characters on a line


gcncratcd by d i s p l a y ( a s seen in the m o d e l o f Figure 16-4):

ampl: option diaplay ifidth 30, diaplay lcol 0;


ampl: diaplay roquirodj

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

W h e n a table would be wider than d i s p l a y — w i d t h , it is cut vertically inn> t w o or


more tables. T h e r o w names in each table are the same, but the columns are dilTerent:
230 D3=LAYCOVVAfC<S C H í f T E R 12

a m p l : option diaplay ifidth 50/ diaplay coat/


cost l*.*|
• C l 1B C l 38 C l 40 C 2 4 6 C2S0 C 2 S 1 D2 37 D2 39
Co u l l a r d 6 9 8 7 11 10 4 S
lia s k i n 11 e 7 6 9 10 1 S
11a z e n 9 10 11 1 S 6 2 7
Itopp 11 9 8 10 6 S 1 7
Iravani 3 2 8 9 10 11 1 S
LineLsky 11 9 10 S 3 4 6 7
MehroLra 11 10 9 8 7 1 2
Ne l s o n 11 S 4 6 7 8 1 9
ânilowitz 11 9 10 8 6 S 7 3
Tamhane 6 9 8 4 3 7 10
WhiLe 11 9 8 4 6 S 3 10

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 ) :

a m p l : option diaplay ifidth 40/


a m p l : diaplay {p in PROD, t in 1..T) (rovonuo [p, t) êSoll [p, t) ,
ampl? prodcoat [p) •Jiako [p, t) , invcoat[p) *Inv[p,t)) /
* $1 = r e v e n u e [ p . t ) * S e l l [ p . t l
4 $2 = p r o d c o s L [p\ « M a k e l p . t J
it $3 = i n v c o s t l p l * l n v l p . t l
: $1 $2 $3
bands 1 1S0000 59900 0
bands 2 156000 6 0 0 00 0
bands 3 37800 14000 0
bands 4 54000 2 0000 0
coils 1 9210 154 77 3300
coils 2 87S00 154 00 0
coils 3 12 9 5 0 0 3 8500 0
coils 4 163800 4 62 00 0

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:

ampl: diaplay Trana;

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:

ampl: option arzit zaro rows 1;

ampl: diaplay Trana;

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

A corresponding option o m i t _ z e r o _ c o l s suppresses ali-zero columns when set t o I,


and would eliminate t w o columns f r o m T r a n s [ C L E V . * . * 1.

12.3 Numeric options for d i s p l a y


T h e numbers in a table or list produced by d i s p l a y are the result o f a transforma-
tion from the compuier's internai numeric representation t o a string o f digits and s y m -
bols. A M P L ' s options for adjusting this trans for m i tion are shown in Table I2-2. In this
section we first consider options that affect only the appearance o f numbers. and then
options that aftect underlying solution vahies as weD.

d i sp l a y _ c p s sxiLillir<t magnitude cfcspliyed chfferently from /cto(0>


digifc of prcci-aon to which dispUvcd numbers m* rounck-d: íull prv
d i sp l a y _p r c c i s i o n ctsx»nif 0 ( 6 )
digifc left or <if nrgotiw) right of decimal pljtcv Io whichdKpl.i>vd
d i sp l a y _ r o u n d
numhrrs j r e rounded. o w m d i n g d i s p l a y _ p r c c i s i o n < * ">
digifc of prcci si an Co which solution values wtc rounJcd: íull prcci
s o l u t i o n prcci sion âanif0<0»
digita lcfc o r ( i f n:gA«i\r) right of dccinul plaa: Io whichsolutkin
s o l u t i o n _ r o u nd values AIC raunded.awrriding s o l u t i o n p r © e i s i o n < - " )

T a b l e 12-2: Numeric options for d i s p l a y < with default values).


S E C T C N 12.3 N U W S í C OPTONS FOR DXSPIAY 233

Appearance of numeric values

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:

a m p l : diaplay {p in PROD, t in 1..T) Kako[p,t)/rato[p) j


Make[p,tj/ratclpl l*.M <tr)
: bands coils :=
1 29.95 10.05
2 30 10
3 20 12
4 32.1429 7.85714

a m p l : diaplay (p in PROD, t in 1..T) prodcoat [p) êMako[p, t)j


p r o d c o s t . [p 1 * M a k o [ p , t 1 l*. 1 <trj
bands coils
1 59900 15477
2 6 0 0 00 154 00
3 4 0000 184 80
4 64285.7 12100

(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 m p l : option dlaplay prociaion 3;


a m p l : diaplay KaXo[' banda 4) / rato [ 'banda' ) ,
ampl? prodcoat ['banda'J • Mmkm('banda ' , 4)j
Makcl'bands'.41/rate[*bands'1 = 32.1
p r o d c o s L l ' b a r x i s ' 1 "Make l ' b a n d s ' . 4 1 = 6 4 3 0 0

a m p l : option dlaplay prociaion 9;


a m p l : diaplay KaXo[' banda 4) / rato['banda') ,
ampl? prodcoat ['banda') • Mmkm('banda 4)j
H a k o [ ' b a n d s ' . 4 1 / r a t e i ' b a n d s ' 1 = 32.1428571
p r o d c o s t [ ' b a n d s ' 1 * M a t a i [ ' b a n d s * .41 = 6 4 2 8 5 . 7 1 4 3

a m p l : option diaplay prociaion 0;


a m p l : diaplay Kako[' banda4) / rato['banda') ,
ampl? prodcoat ['banda') • Kako[ 'banda ' ê 4) j
M a k e l ' b a n d s ' . 4 1 / r a t e i ' h a n d s ' 1 = 32.14285714285713
p r o d c o s t [ ' b a n d s ' 1 * M a t a i [ ' b a n d s * .41 = 6 4 2 8 5 . 7 1 4 2 8 5 7 1 4 2 7

In the lait example. a d i s p l a y _ p r e c i s i o n o f 0 is interpreted specially: it tells


d i s p l a y t o represem numbers as exactly ai possiblc. using h o w e v e r many digits are
neeessary. ( T o be precise, the d&playcd number is the shortest decimal representation
that, when correctly rounded k> the computcr's representation. gives the vahie exactly as
stored in the computer.)
234 D3=LAYCOVVAfC<S C H í f T E R 12

Displays t o a g i v e n precision provide lhe same degree o f useful information about


each number. bui they can kx>k ragged due t o the varying numbers o f digits after the dec-
imal point. T o s p e e i f y rounding t o a fixed number o f decimal places. regardless o f the
resuhing precision. you m a y set the option d i s p l a y _ r o u n d . A nonnegative value
specifies the number o f dighs appear after the decimal point:

a m p l : option diaplay round 2j


a m p l : diaplay {p in PROD, t in 1..T) Kako[p,t)/rato[p);
Makclp. t l / r a t o l p l l*.M <trj
• bands coils
1 2 9 . 95 10.05
2 30.00 10.00
3 20.00 12.00
4 3 2 . 14 7 . BG

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:

a m p l : option diaplay round -2j


a m p l : diaplay {p in PROD, t in 1..T) prodeoat [p) *Kakolp,t)j
p r o d c o s t l p l "Makclp. t l l*.*l <trj
• bands coils
1 59900 15500
2 G0000 154 00
3 4 0000 1B500
4 G4300 12100

Any integer value o f d i s p l a y _ . r o u n d overrides the eíTect o f d i s p l a y _ p r e c i s i o n .


T o turn o f T d i s p l a y _ r o u n d . set it t o s o m e non-integer such as the empty string ''.
Depending on the solver you e m p l o y , you may flnd that some o f the solution values
that ought t o be zero d o not ahvays quite c o m e out that way. R>r example. here is one
s o l v e r ' s report o f the objective funetion terms c o s t [ i . j J • T r a n s [ i . j ] for the
assignmcnt problem o f Section 3 3 :

a m p l : option arzit zoro roxra 1;


a m p l : diaplay ( i in ORIG, j in DEST) coat[i,j) • Trana[i, j)/
costli.jl"Transli.jl : =
Coullard C11B G
Coullard D241 2.05994c-1?
Daskin D2 3? 1
llazcn C2 4G 1
Itopp D2 3? G.BGG47c-lB
Itopp D2 41 4
... 9 Snes onútttd
Whitc C2 4G 2.74G59c-l?
Whitc C2S1 -3.43323c-1?
Whitc M2 39 1
S E C T C N 12.3 N U W S í C OPTONS FOR DXSPIAY 235

Minusculc values like 6 . 8 6 6 4 7 e - 1 8 and - 3 . - l 3 3 2 3 e - l 7 have n o signifícance in lhe cx>ntexi


o f t h i s problem; they woukl be zeros in an exact solution. but c o m e out slightly non/ero
ai an artifkrt o f the w a y thai the solver's algorithm interacts with the computer's repre-
senta ti on o f numbers.
T o a v o i d v i e w i n g these numbers in meaningless precisk>n. you can pick a rcaionablc
setting for d i s p l a y _ r o u n d — in this case 0, since there are n o digits o f interest after
the decimal point

a m p l : option diaplay round 0/


a m p l : diaplay ( i in ORIG, j in DEST) co*t[i,j) • Trana[i, j)/
costli.jl"Transli.jl :=
Coullard C l 1B G
Coullard D2 41 0
lia s k i n D2 37 1
11a z e n C24G 1
Itopp D2 37 0
Itopp D2 41 4
Iravani C l 1B 0
Iravani C13B 2
Linotsky C2S0 3
Mehrotra D2 39 2
lson C13B 0
.Nelson C140 4
â n i l o w i t z M233 1
Tamhano C l 1B -0
Tamhano C2S1 3
Whitc C24G 0
White C2S1 -0
Whitc M2 39 1

T h e small numbers are n o w represented only ai 0 if positive or - 0 if negative. I f you


want t o suppress their appearance entirely, h o w e v e r , you must set a separate option,
display_eps:

a m p l : option diaplay opa lo-10;


a m p l : diaplay ( i in ORIG, j in DEST) co*t[i,j) • Trana[i, j)/
costli.j|"Transli.jl :=
Co u l l a r d C l 1B G
lia s k i n D2 37 1
11a z c n C24G 1
Itopp D 2 41 4
Iravani C13B 2
Linotsky C2 50 3
Mehrotra D2 39 2
.Nelson C140 4
â n i l o w i t z M233 1
Tamhano C2S1 3
Whitc M239 1
236 D3=LAYCOVVAfC<S C H í f T E R 12

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 .

Roundingof solution values

T h e options d i s p l a y _ p r e c i s i o n . d i s p l a y _ r o u n d and d i s p l a y _ e p s alYect


only the appcarance o f numbers. not their actual vahies. Y o u can see this if you try t o
display the set o f ali pairs o f i in O R I G and j in D E S T that have a positive vahie in the
preceding table. by compor ing c o s t [ i . j ] * T r a n s [ i . j ] t o 0:

a m p l : diaplay ( i in ORIG, j in DEST: coat [ i , j J • Trana / i , j ) > 0) ;


s e t ( i i n ORIG. j i n DEST: c o s t l i . j 1 * Trans [ i . j J > 0} : =
( C o u l l a r d . C l 1BJ < I r a v a n i . C l 1BJ <SmilowitZ.M233j
( C o u l l a r d . D2 41J ( I r a v a n i .C13BJ ( T a m h a n e . C251J
( D a s k i n . D2 3 7 ) ( L i noL s k y . C 25 0J ( W h i L o . C2 4 G J
( l l a z c n . C24 Gj ( M e h r o L r a . D 2 3 9j ( W h i L o . M2 39j
<Uqpp.D237) (Welson.C13Bj
( l l o p p . D241J ( N e l s o n . C14 0J ;

Even though a value like 2J05994C-!7 is treatcd as a zero for purposes o f d i s p l a y . it


tests greater than z e r o . Y o u could fix this problem by changing > 0 above *>. say. > 0.1.
A s an ahernative. you can set the option s o l u t i o n _ r o u n d s o that A M P L rounds the
solution values k> a reau>nable precision when they a r e r e c e i v e d from the solver:

a m p l : option aolution round 10;


ampl: aolvo;
M1NQS S . S : o p L i m a l s o l u L i o n found.
40 i t o r a L i o n s . o b j o c L i v e 2B

a m p l : diaplay ( i in ORIG, j in DEST: coet [ i , j)'Trana [i, j) > 0) ;


SOL ( i i n ORIG. j i n DEST: c o s t l i . j 1 * Trans [ i . j J > 0 } : =
( C o u l l a r d . C l 1BJ ( I r a v a n i . C l 3B J (SmilowitZ.M233j
( D a s k i n . D2 37 ) (LineLsky.C2S0j ( T a m h a n o . C251J
( l l a z e n . C24 Gj ( M o h r o L r a . D 2 3 9j ( W h i L o . M2 39j
(llopp.D241J ( W e l s o n . C 1 4 0j ;

T h e options s o l u t i o n _ p r e c i s i o n and s o l u t i o n _ r o u n d woric in the same w a y


ai d i s p l a y _ p r e c i s i o n and d i s p l a y _ r o u n d . except that they are applied only t o
solution values upon return from a solver, and they permanently change the retumod v a l -
ues rather than only their appearance.
Rounded values can make a difference even when they are not near zero. A s an
example, w e first use several d i s p l a y options n> g e t a compact listing o f the fractional
solution *> the scheduling ntxlcl o f Figure 16-4:

ampl: izodal achod.xaod;


ampl: data ochod.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 .
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

ampl: option diaplay *fidth 60;


ampl: option diaplay lcol 5;

ampl: option diaplay opa lo-10;


a m p l : option arzit zoro roxra 1;
a m p l : diaplay Work;
Work l * | : =
10 2 8 . 8 30 14.4 71 35.G 10G 2 3 . 2 123 35.G
18 7. G 3S G. 8 73 28 109 14.4
24 G. 8 GG 3S.G 87 14.4 113 14.4

Each value W o r k ( j ) represents the number o f workers assigned to schcdulc j . W e can


get a quick practical schcdulc by roundmg the fractional values up to the next highest
integer: using the c e i i funetion k> perform the rounding, we see that the total number of
wofkers needed should be:

a m p l : diaplay SUE ( j in SCHEDS) coil(Work[ jj)/


sumCj i n SCiJKDS} c o i 1 ( W a r k [ j 1J = 273

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:

ampl: option diaplay opa 0;


ampl: option diaplay praciaion 0;

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 :

a m p l : option aolution round 10;


ampl: aolvo;
M1NQS 5 . 5 : o p t i m a l s o l u t i o n í o u n d .
19 i t c r a t i o n c . o b j o c t i v e 2G5.G

ampl: diaplay SUE ( j in SCHEDS) coil(Work[ jj)/


s u m j j i n SCillíDS} © o i l < W o r k ( j l J =271
238 D3=LAYCOVVAfC<S C H í f T E R 12

We pickcd a value o f IO for s o l u t i o n _ r o u n d because VÍC observed that lhe slight


inaccuracies in lhe solver*s values occurred well pau the lOth decimal place.
T h e e f f e e t o f s o l u t i o n _ r o u n d or s o l u t i o n _ p r e c i s i o n applies to ali values
returned by the solver. T o modify only cenain values. use the assignment ( l e t ) c o m -
mand described in Section 11.3 together whh the rounding functions in Table I I I .

12.4 Other output c o m m a n d s : print and print f


T w o additional AMPL commands have much the same syntax as d i s p l a y , but do
not automatLally formai their output. The p r i n t command does no formatting at a l i
while the p r i n t £ command requires an cxplicit dcscription of the desircd formatting.

The print command

A p r i n t command products a single line of output:

a m p l : print SUE (p in PROD, t in 1. .T) rovtmuo[p, t) 'Soll[p, t),


ampl? sun (p in PROD, t in 1. . T > prodcoat [p] 'Kako [p, t) ,
ampl? sun {p in PROD, t in 1. .T) invcoat [p) • Inv[p, t J/
787810 269477 3300

ampl: print {t in 1. .T, p in PROD) Kako[p,t)j


S990 1407 6000 1400 1400 3S00 2000 4200

or. if follovrcd by an indexing expression and a colon. a line of output for each member of
the indexset:

ampl: print {t in l..T)i {p in PROD) K*kolptt)j


S990 14 07
6000 14 00
1400 3500
2000 42 00

Prinied entries are normally separatcd by aspace. but option p r i n t _ s e p a r a t o r can


be used to change this. For instanevr. you might set p r i n t _ s e p a r a t o r to a tab for
data lo be imported by a spreadshect: to do this. type o p t i o n print_separator
• ' , where stands for the result o f pressing the tab key.
T h e keyword p r i n t <whh optional indexing expression and c o l o n ) is followad by a
print item or comma-separatcd list of print items. A print item can be a value, or an
indexing expression followvd by a value or parcnthcsi/ed list of values. Thus a print item
is much like a display item, except that only individual values may appear: although you
can say d i s p l a y r a t e . you mustexplkntly specify p r i n t { p i n PROD) ratetp].
Also a set may not be an argument to p r i n t , ahhough hs members may be:
SECT ON 12 4 O T H E R O U T P U T C O W V . A f C < S w.zzt? fttD p » zzrrr 239

a m p l : print PROD/
syntax error
context: print » > PttDD: « <

a m p l : print (p in PROD) (p, rato lp))j


b a n d s 2 00 c o i l s 140

Unlike d i s p l a y . howxrver. p r i n t alk>ws imlexing to be nested within an indexed item:

ampl: print {p in PROD) (p, rato lp) , {t in 1. .T) Makolp, t ))j


bands 2 00 5 9 9 0 6 0 0 0 14 00 2 0 0 0 c o i l s 140 14 07 14 00 3 5 0 0 42 00

The representation of numbers in the output of print is governed by the


print_precision and print_round options. which work exactly like the
display_precision and d i s p l a y _ r o u n d options for the d i s p l a y command.
Initially p r i n t _ p r e c i s i o n a 0 and p r i n t _ r o u n d is an empty string. s o that by
default p r i n t uses as many digits as necessary t o represent each value as precisely as
possibkr. For the above examples, p r i n t _ r o u n d has been set t o 0, s o that the numbers
are rounded t o integers.
NVorking inieractively, you may find p r i n t useful f o r viewing a f e w vahies on your
scrccn in a more compact format than d i s p l a y produccs. W h h output redirected t o a
file, p r i n t is useful f o r writing unformaned results in a form convenient for spread-
sheets and other data analysis tools. A s with d i s p l a y . just add >filenume t o the end o f
the p r i n t command.

The prin t £ comman d

T h e syntax o f p r i n t £ is exactly the same as that o f p r i n t , except that the first


print item is a character string that provklcs formatting instmetions for the remaining
items:

a m p l : printf »Total rovíinuo ia $\6.2£.\n",


ampl? aun {p in PROD, t in 1 . . T j ravanuolp,t)*Solllp,t)j
T o t a l revenue i s $787810.00.

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

a m p l : príntf (t in l..T)i "\3i\12.2 f\12. 2f \n" , t ,


ampl? SUE: (p in PROD) rovanua [p, t) 'Soll [p, t) ,
ampl? busz (p in PROD) prodcoat [p) êKako[p, t) j
1 159210.00 7 5377.00
2 243500.00 75400.00
3 1673 0 0 . 0 0 52500.00
4 217800.00 662 0 0 . 0 0

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.

12.5 Related solution values


Seis. parameters and variables are the must obvk>us things ti> look at in interpreting
the solution o f a linear program. but A M P l . also provides w a y s o f examining objectives,
bounds. slacks, dual prices and reduced costs associated with the optimal solutk>n.
A s w e have shown in numerous examples already. A M P l . distingu&hcs the various
values associated whh a nnxlel component by use o f " q u a l i f i e d " names that c o n s i s t o f a
variable or constraint klcntifier, a dot ( . X and a predefined " s u f T i x " string. For instance,
the upper bounds f o r the variable >Cake are called > C a k e . u b , and the upper bound f o r
> C a k e [ ' c o i l s ' . 2 ] is written J í a k e t ' c o i l s 1 , 2 ) . u b . ( N o t e that the sulYix c o m e s
after the s u b s c r i p t ) A qualified name can be used like an unqualified one, s o that
display > C a k e . u b prinfc a table o f upper bounds on the J í a k e variables, while
d i s p l a y >Cake, >Ca k e . u b printv a ü s t o f the optimal values and upper bounds.

Objective funetions

T h e name o f the objective ftmction ( f r o m a m i n i m i z e or m a x i m i z e declaration)


refers t o the objective*s vahie computed from the current values o f the variables. This
name can be used t o represem the optimal objective value in d i s p l a y , p r i n t , or
printf:

a m p l : print 100 • Total Profit /


ampl? SUE {p in PROD, t in 1. .T) ravonua[p,t) • Soll(p,t)j
6 5 . 3 7 52 80841827 35

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

Bounds and slacks

T h e suffixes . l b and . u b on a variable denote its l o w e r and upper bounds. while


. s l a c k denotes the d i f f e r e n c e o f a variable's value from its nearer bound. I l e r e ' s an
example from Figure 5-1:

a m p l : diaplay Buy .lb, Buy, Buy.ub, Buy.alackj


i Buy.lb Buy Buy.ub B u y . s l a c k :=
BHKF 2 2 10 0
ciix 2 10 10 0
F1SJ1 2 2 10 0
HAM 2 2 10 0
2 2 10 0
»rL 2 6.23596 10 3
SP G 2 5.25843 10 3
TUR 2 2 10 0

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:

ampl: diaplay {p in PROD) (Inv[p, 0) .lb, invOlp), Inv[p, 0) .ub);


i I n v l p . 01.1b invOlpl I n v l p . 0 1 . ub :=
bands 10 10 10
coils 0 0 0

In the production-and-transportaiion nnxlel o f Figure 4-6, the constraint

sum ( i in ORIG} T r a n s i i . j ,p 1 = dccvindlj.pl

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

fcHW bound ^ Av*/v ^ upper bound

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:

and the f o l l o w i n g constraint bounds:

a m p l : diaplay Diot Min.lb, Diat Min.body, Diot Min.ub;


i D i e L _ M i n . l b DieL_Min. body DieL_Min.ub :=
A 700 1 0 1 3 . 9B Inf i n i L y
Bl 0 G05 InfiniLy
B2 0 4 9 2 . 41G InfiniLy
C 700 7 00 InfiniLy
CAL 1G000 1 GO 00 InfiniLy

a m p l : diaplay Diot Max.lb, Diat Mox.body, Diat Siax.ub;


i D i e L Max . l b D i e L . M a x . i » d y D i e L M a x . u b :=
A -inf iniLy 1013.9B 20000
CAL - Inf i n i L y 1G000 24000
NA -Inf iniLy 43BSS.9 S0000

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:

ampl: diaplay Diat Min .alackj


Diet_ Min. s l a c k l* 1 : =
A 313.97B
Bl G0S
B2 492.41G
C 0
CAL 0

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

Dual values and reduced costs

Associated whh each constraint in a linear program is a quantity vark>usly known ai


the dual variable. marginal value or shadow price. In the A M P I . command e n v i r o n m e n i
these dual values are denotcd by the names o f the constraints. without any qualifying suf-
fix. Thus for e x a m p l e in Figure 4 - 6 there & a coilection o f constraints named D e m a n d :

s u b j o c t t o Dcmarxi ( j i n DEST. p i n PROD} :


sum ( i i n O R I G } T r a n s l i . j . p l = d c m a n d l j . p l :

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

F i g u r e 12-1: Piecewise-linear p l o t o f o b j e e t i v e funetion.

I lere it is rc vealing t o loofc at the dual values together with the slacks:

ampl: diaplay Tiizo, Tixoo.alack;


: Time Time. slack :=
CLKV -1522.BG 0
GARY -3040 0
PITT 0 10.SG43

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

a m p l : diaplay Buy.lb, Buy, S u y . u b , fluy.rc;


.: B UuYy..Xl U
O b IBuy Buy.ub Buy.rc
BKKF 2 2 10 1.73GG3
CiJX 2 10 10 -0.853371
K1S11 2 2 10 0.255281
li>\M 2 2 10 0.G987G4
Wl'11 2 2 10 0.24G573
rnL 2 G.2359G 10 0
SPG 2 5.25843 10 0
TUR 2 2 10 0.343483

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 . )

12.6 Other display features for m o d e l s and instances


W e gather in \ht% scction various utility c\>mmands and other features f o r displaying
information about nnxlcts or about problem instances generated from models.
T w o c o m m a n d s let you r e v i e w an A M PI. model f r o m the command-line: s h o w lists
the names o f nnxlel components and displays the definitions o f individual componcnts.
while x r e £ lists ali componcnts that d e p e n d o n a given component. T h e e x p a n d c o m -
mand displays selecfted objectives and constraints that A M PI. h^i generated from a nnxlel
and data.or analogous infouration for variables. A M P l . ' s " g e n e r i e " names f o r variables.
246 D3=LAYCOVVAfC<S CHífTER 12

constraint. or o b j e c t i v e * permit listings or teus that apply t o ali variables. constraint*. or


objeetives.

Displaying model components: the ohow command:

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.

This display may be restricted t o components o f one or m o r e types:

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

T h e s h o w command can also display the dccbrations o f individual componcnts. saving


you the trouble o f looking them up in the nnxlel f i l e :

a m p l : a how Total Cost;


m i n i m i z e T o L a l _ C o s L : s u m { i i n ORIG, j i n DEST. p i n PROO}
v c o s L l i . j . p l » T r a n s [ i . j . p l «- s u m ( i i n ORIG. j i n D E S r }
ícosLli.j1*Use[i.j|:
a m p l : shcxr vcoet, fcost, Trans;
p a r a m v c o s L ( O R l G . D E S r . PROD} >= 0:
p a r a m £ c o s L ( O R l G . DEST} >= 0:
v a r T r a n s ( O R l G . DEST. PROD} > = 0:

If an item f o l l o w i n g 3 h o w t% the name o f a component in the current n n x l e l the dcclara-


tion o f that component fc displaycd. Otherwise. the item is interpretcd as a component
type aceording to its first letter or t w o : see Section A . 19.1. (Displaycd declaration* may
diíTer in inessential ways from their appearancv? in your nnxlel file. duc t o transformaiions
that A M P L performs when the nnxlel is parsed and transbted.)
Since the c h e c k statements in a nnxlel d o not have namcs. A M P L numbers them in
the order that they appear. Thus t o see the third chcck statement you would type

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:

By itself. s h o v c h e c k s indicates the number o f c h e c k statements in the nnxlel.


SECTCN 126 OTHER D S R - A Y FE ATURES FOR WCC€LS AND ttSTANCCS 247

Displaying model dependencies: the x r e f command

T h e x r e £ command lists ali nuxlel componente lhat depend on a specified c o m p o -


nent. eilher dircetly (by referring t o it) o r indircctly (by referring t o its dependente). If
more than one component is given. the dependente are listed scparately f o r each. I Icre is
an example from m u l t m i p 3 . m o d :

a m p l : xrof daxsand, Tranaj


4 2 e n t i t i e s d e p e n d on d e m a n d :
check 1
Demand
i S e n t i t i e s d e p e n d on T r a n s :
Tot_al_Cost
Supply
Demand
Multi
Mi n _ S h i p

In general, the command is simply the k e y w o r d x r e í f o l l o w e d by a comma-scparatcd


list o f a n y combination o f set, parameter, variable, objective and constraint names.

Displaying model instances: the exp&nd command

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;

subject to Supply [ ' P I T T ' 1 :


T r a n s l • PI T f * . ' FRA' 1 + T r a n s l ' P I T T ' . ' D Kl*' 1 +
T r a n s i ' PI Tf* . ' LAN' 1 + T r a n s l ' P I T T ' . 'WIN ' 1 +
T r a n s i ' P I V Y ' . ' SYL1\ + Transl'PITT'.'FRK'1 +
Trans('PITT','LAF'j = 2900;

(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 : oxpand Total Cost;


minimize ToLal_CosL:
3 9 * T r a n s l ' G A R Y ' , ' F R A * 1 / ( 1 - T r a n s i ' G A R Y • . • F R A ' J / 5 0 0 ) + 14*
T r a n s [ ' G A R Y ' , • IHfT ' 1 / ( 1 - T r a n s ( ' GARY* a ' DSSV ' ] / I O 0 0 ) + 1 1 *
T r a n s [ ' G A R Y * , • L A N ' j / ( 1 - T r a n s ( ' G A R Y ' a ' L A N ' J / 1 0 0 0 ) + 14*
T r a n s [ ' G A R Y ' » ' W I N ' 1 / ( 1 - T r a n s ( ' G A R Y ' , ' W I N ' ] / 1 0 0 0 ) + 16*
... 15 Hntx on\iiòt<i
T r a n s [ ' P I T T * M ' FRK ' 1 / ( 1 - T r a n s ( • P I T T ' , • FRB • J / 5 0 0 ) + 2 0 *
T r a n s [ ' P I T T * a ' LAF ' 1 / ( 1 - T r a n s [ ' P I T T ' L A F ' 1 / 9 0 0 ) ;

W h e n e x p a n d fc applied t o a variable. h lists ali o f lhe nonzero c o e f f i c i e n t s o f thai


variable in the linear t e m i s o f objectivcsandconsirainLs:

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

C o o í í i c i c n L s o£ T r a n s i 'GARY ' « • D K T ' J :


Supplyl'GARY'1 1
Domandl •DKT' J 1
ToLal_CosL 0 + nonlinear

C o e i í i c i c n L s o£ T r a n s i 'GARY ' , ' L A N ' 1 :


Supplyl'GARY'1 1
Domandl'LAN'J 1
ToLal_CosL 0 + nonlinear

C o e i í i c i c n L s o£ T r a n s i 'GARY ' , ' WIN* 1 :


Supplyl'GARY'1 1
Dcmandl ' W I N ' 1 1
ToLal_CosL 0 + nonlinear
... 17 iennxomittrd

W h e n a variable a b o appears in nonlinear expressions within an objective or a constraint.


the teim • n o n l i n e a r K appendeJ t o represent those expressions.
T h e command e x p a n d alone produces an expansion o f ali variables, objectives and
oonstraints in a nnxlel. Since a single e x p a n d command can produce a very long listing.
you may want toredirect its oulpul a file by placing >/iUmimei at the end ai e x p b i n e d
in Section 12.7 below.
T h e formatting o f numbers in the expanded oulpul is governed by the options
expand_precision and expand_round, which work like the display
c o m m a n d ' s d i s p l a y _ p r e c i s i o n and d i a p l a y _ r c u n d d e s c r i b e d ín Section 12.3.
T h e output o f e x p a n d refiects the ' 'nnxleler's v i e w " o f the problem: it is baied on
the nnxlel and data ai they w e r e inhially read and translated. But A M P L ' s presolve phase
(Section 14.1) m a y m a k e significam simplifications *> the problem befoce it s sent t o the
solver. T o see the expansion o f the " s o l v e r ' s v i e w " o f the problem f o l b w i n g presolve,
use the k e y w o r d s o l e x p a n d in p b c e o f e x p a n d .
SECTCN 126 OTHER D S R - A Y FE ATURES F O R W C C € L S A N D ttSTANCCS 249

Ceneric synonyms for variables, constraints and objectives

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:

_nvar s number o f variables in lhe current problem


_ncons number o f constraint* in the cummt problem
_nobj s number o f abjcclivcs in lhe current problem

Correspondingly indexed parameters cx>ntain the A M P l . n a m e s o f ali the components:

_varnamc (1 . . j i v a r ) rumes af variables in the current problem


_connamc(l. . _ncans} rumes af canxtrainfe m th? curient pfabkm
_ o b j n a m c ( 1 . . _r>obj s> rumes af abjcclrves in the current problevn

Finally. the f o l l o w i n g synonyms f o r the components are ma de available:

_var (1. ._nvars} xynanymc f<r variables in the current problem


_ c o n ( 1. . j i c o n s } synonyms fer canxtrainfe in the current problem
_ o b j ( 1 . ._nob j s } synonyms f<r abjcclivcs in the current problem

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

ampl: diaplay ( j in 1.. nvara)


ampl? ( varnaxzn [ j ) , v a r [ j ) , var[j).ub, var[j).rc);

l _varname l jl _var l j1 _ v a r l j 1 . ub _var[j 1 .rc


1 -PD_Shipr?JI£' 1- 2 SO 2S0 -o.s
2 • P D _ S b i p [ ' 5 H' 1- 2 00 2S0 - 1 . 11022c-1G
3 " DW_Sbip [ ' N B * .•BOS•1" 90 90 0
4 " DW_Sbip [ ' N B * . ' BWR ' 1 " 100 100 -1. 1
S " DW_Sbip [ ' N B * . ' B M X ' 1" GO 100 0
G ,•DW__Ship^SK, . ' BWR • l - 20 100 2.22 04Sc-lG
7 ',DW_JShip[,SB, . ' B M X ' 1" GO 100 2.22 04Sc-lG
8 ',DW_JShip[,SB, .•ATL'1" 70 70 0
9 -a«í_Shipl,SK' . 'MOO ' 1 " SO SO 0
250 D3=LAYCOVVAfC<S CHífTER 12

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-

T h e same commcnts apply t o constraints and objectives. M o r e precise formatting o f this


information can be obtained w i l h p r i n t f (12.4, A . 1 6 ) instcad o f d i s p l a y .
A s in the case o f the e x p a n d o o m m t n d , these parameters and generic synonyms
refleei lhe m o d e l e r ' s v i e w o f the problem: their values are dctcrmincd from lhe nnxlel
and data ai they were inilially read and translated. A M P I / s presolve phase may make sig-
nificam simplificaiions t o the problem before it is sent t o the solver. T o work wilh
parameters and generic synonyms that refkrct lhe s o l v e r ' s v i e w o f the problem f o l l o w i n g
presolve, r e p b c e _ by in the names given a b o v e ; f o r example in the case o f variables.
use _ s n v a r s , _ s v a r n a m e and _ s v a r .
Addhional predefined sets and parameters represent lhe names and dimensions <ari-
ties) o f the nnxlel components. T h e y are summarized in A.19.4.

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:

ampl: izodal ataolT.aod;


ampl: data ataalT.dat;
ampl: option ahow atata 1;
ampl: aolvo;

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.

12.7 General facilities for manipulating output


W e describehere how some or ali o f AMPl.'s output can be directed toa file, and how
the volume o f warning and error messages can be regulatcd.

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:

ampl: diaplay ORIG, CE ST, PROD >xoilti .out;


ampl: diaplay aupply >rrulti.outj

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:

ampl: cloao xulti .out/

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 i c g ^ í i l e option instruets AMPI. to save subscquent c\>mmands and responses


toa file. The option's value is a string that is interpreted as a filename:

ampl: option log filo 'xai lt i . trp '/


252 D3=LAYCOVVAfC<S C H í f T E R 12

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:

ampl: option log f i l o " ;

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

B y specifying o p t i o n e e x i t /i, where n t* s o m e inieger, you determine h o w A M P I .


handles error messages. lf n ti not zero, any A M P I . statement is krrminated afier h hai
pnxluced a b s {/t > error messages: a n e g a i i v e value causes only the one statement t o be
terminaied, while a positive value results in terminatk>n o f t h e entire A M P L session. T h e
e f f e c t o f this option is mixst often seen in the use o f m c d e l and d a t a statements where
somcthing h a s g o n e badly awry, like using the wrong file:

a m p l : option ooxit -3;


a m p l : xzodol diot.xaod;
a m p l : data diot.xaod;
dieL.rn.od. l i n e 4 < o í í s e t 3 2 ) :
e x p e c t e d : < l : o r symbol
context: param c o s t » > ( « < FOOD} > 0:

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:

diet.mod. line 6 (oííseL BI):


e x p e c t e d ; < l : o r symbol
context: param í max » > ( < « j in FOOD} > = í_minljl:

iiailing out aíter 3 warnings.

T h e default value f o r e e x i t is - 1 0 . Seuing it t o 0 causes ali error messages t o be dis-


played.
T h e e e x i t setiing also applies k> infeaiibility warnings produccd by A M P l . ' s pre-
s o l v e plfcfce after you type s o l v e . T h e number o f these warnings ti simultancously l i m -
SECT ON 12.7 GBVJERAL F A C L T ES FOR W / N P U L A T N 3 OUTPUT 253

itcd by lhe vahie o f option p r e s o l v e _ v a r n í n g s , which is typically sei to a smaller


value: lhe default i s 5 .
A n A M P L d a t a statement may specify values ihai correspond u» illcgal combinalions
o f Índices, due to any number o f mistakes such as incorrect index seis in the m o d e l
indices in the wrong order, misuse o f ( t r l , and typing error s. Similar errors may be
ca used by l e t statements that change the membership o f index sets. A M P L catches these
errors after s o l v e istyped. The number o f invalid combinalions displaycd is limitcd to
lhe value o f the option b a d _ s u b s c r i p t s , whose defauh value is 3.
Copyright O 3 K B by Robcrt Fourcx, David XLGayand B r i » W . Kernighin

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.

13.1 Running scripts: include and commands


A M P I . p r o v i d e s several c o m m a n d s that cause input lo be taken from a file. T h e c o m -
mand

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

T h e r > c d e l and d a t a c\>mmands lhai appear in m o f l o f our examples are special


cases o f i n c l u d e thai put the command interpreter into nxxlcl or data mode before
rcading the s p e c i f i e d file. B y contrast. i n c l u d e leaves the nnxle unchangcd. T o keep
things simple. the examples in \ht% lxx>k always assume that r » c d e l reads a file o f nnxlel
dcclarations. and thai d a t a reads a file o f data values. Y o u may use any o f atodel,
d a t a and i n c l u d e to read any file. h o w e v e r : the only difference is the nnxle that is set
when rcading starfc. W o r k i n g whh a small nnxlel, f o r example, you might find it c o n v e -
nient t o store in one file ali the nnxlel dcclarations. a d a t a command, and ali the data
statements: either a r > c d e l or an i n c l u d e command could read this file t o set up both
nnxlel and data in one operation.
A s a n illustration, if the file d i e t u . r u n c\>ntains

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:

a m p l : includo d ia tu. run/


M1MDS S . S : o p L i m a l s o l u L i o n í o u n d .
6 i t c r a t i o n s . o b j e c L i v e 74.27382022

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

W h e n an included file itself contains an i n c l u d e , r r » c d e l or d a t a c\>mmand. rcading


o f the first file issuspended while the contente o f the c\>ntaincd file are included. In this
example. the command i n c l u d e d i e t u . r u n causes the subsequent inclusion o f the
files dietu.rr>cdanddietu.dat.
O n e panicularly useful kind o f i n c l u d e file contains a list o f o p t i o n commands
thai you want to run before any other commands. to nnxlify the default options. Y o u can
arrange to include such a file automaiically ai stanup: you can even have A M P L write
such a file automaiically ai the end o f a session. s o that your option settings will be
restored the next time around. IXtails o f \ht% arrangement depend on your opcraiing sys-
tem:seeSectk>ns A . 14.1 and A 2 3 .
T h e statement

c o n m a n d s fútntin* •

is v e r y similar t o i n c l u d e , but is a tnie statement that necds a terminating semicolon


and can only appear in a context where a statement is legal.
T o i l l u s t r a i e corrrr-winds. considcr h o w \V>Í might p e r f o r m a simple sensitivity analy-
sis on the multi-perkxl produetion problem o f Section 4.2. O n l y 32 hours o f prtxluction
SECT CN i a i FJUWN3SCRPTS JU=ujiolAÍ4L}CC—í»£OS 257

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: codol ataolT.xsod;


ampl: data ataolT.dat;

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 ;

a m p l : l o t avail [3J i - avail [3) • 3;


ampl: aolvo;
MINOS 5 . 5 : 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 532 033
a m p l : diaplay Total Profit >atoalT. 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 ;

a m p l : l o t avail [3J i* avail [3) • 3;


ampl: aolvo;
MINOS 5 . 5 : 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 549033
ampl:

T o continue trying values o f a v a i l [ 3 ] in steps o f 5 up t o say 62. w e must c o m p l e t e


another fotwr s o l v e cycles in the same w a y . W e can avoid having t o type the same c o m -
mands over and over by creating a new file containing the commands t o be repeaied:

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

If call ihiü file s t e e l T . s a l , we ean execute ali thccommands in it by typing the


singkc line c o r e t e i n d s s t e e l T . s a l :

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.

13.2 Iterating over a set: the f o r statement


T h e examples above still require that some command be typed repeatcdly. AMPL pro-
vides looping c\>mmands that can do this work au*>matically, with various options to
determine how long the looping should continue.
W e begin with the £ o r statement. which executes a statement or collcctk>n of statc-
mcnts once for each member o f some set. T o execute our multi-period produetion prob-
lem sensitivity analysis script four times, for example. w e can use a single f o r statement
followxrd by the command that we want k> repeat:

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

T h e expression between f o r and lhe command can be any A M P I . indexing expression.


A s an ahernaiive k> taking lhe cx>mmands from a separaie file, w e can w r i t e them ai
lhe body o f a f o r statement. cnckxscd in braees:

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

ampl: ccazands ataal T. aa2

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}:

T h e set A V A I L 3 w i l l e o n t a i n ali the different values f o r a v a i l [ 3 ) that \V>Í w a n t t o try;


for each such vahie a , a v a i l 3 _ o b j [ a ] and a v a i l 3 _ d u a l [ a ] w i l l be the associ-
ated objective and dual values. O n c e these are set up, w e assign the set vahie to
AVAIL3:

let AVA1L3 : = a v a i l 131 .. availUl • 15 b y S:

and then use a f o r kx>p t o iterate over this set:

í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;

F i g u r e 13-1: fttf « í e t e r s e nsiti vi ty script ( s t e e l T . s a 3 ) .

plete, lhe dcsircd table fc pcoduced by d&playing a v a i l 3 _ o b j and a v a i l 3 _ d u a l , as


shown at the end o f the script in Figure 13-1. If this script is stored in steelT.sa3,
then the dcsircd results are produccd wilh a single command:

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%

T h e script *> write this table can be as short as t w o p r i n t í commands:

printf • \n%s%14 s% 17s \n • . " S A L E S " , " b a r x i s " . "coils":


pr i n t £ ( t in 1 . . T } : " w o c k %d%9d%7.1£%%%9d%7.1£%%\n". t.
Soll [ "bands" . t j, 1 0 0 » S c l 11" baixis " . t | / m a r k o t l " h a r x i s " . t | .
Soll l"coils".t|. 100»Scl11"coils".t|/markotl"coils".t| :

This approach is undesirably restrictive, h o w e v e r , because it assumes that there w i l l


always be t w o produetsand that they will always be named c o i l y and b a n d s . In fact
the p r i n t f statement cannot write a table in which both the number o f r o w s and the
number o f columns depend on the data. because the number o f entries in hs formai string
is always f i x e d .
A more general script for generating the table is shown in Figure 13-2. Each pass
through the " o u t e r " l o o p o v e r { 1 . . T > generates one r o w o f the table. Within each
pass, an " i n n e r " kx>p over PROD gcncrates the r o w ' s product entries. There are more
printf statements than in the previous example, but they are shorter and simpler. We
use several statements t o write the contents o f each line: p r i n t f does not begin a n e w
l i n e e x c e p t where a newline < \ n ) appears in its formal string.
L o o p s c a n be nested t o any depth. and may be iterated o v e r any set that can be repre-
sented by an A M P l . set expression. There is one pass through the l o o p for every member
o f the set, and if the set is ordered — any set o f numbers like 1 . . T . or a set declared
o r d e r e d or c i r c u l a r — the order o f the passes is determined by the ordering o f the
set. I f the set is unordered (like P R O D ) then A M P L chooses the order o f the passes, but

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":

F i g u r e 13-2: Generatinga forimtted sales table with nested loops< s t e e l T . tabi).


262 CQHVX4DS C R PTS C H í f T E R 13

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.

13.3 Iterating subject t o a condition: the r e p e a t statement


A second kind o f looping constnict. the r e p e a t statement. continues iterating ai
long as s o m e k>gical condition ii satisfied.
Returning t o the sensitivhy analysis example. w e wish t o take advantage o f a property
o f the ilual value on the constraint T i m e [ 3 J: the addhional profit that can be reali/ed
from each extra hour added k> a v a i l [ 3 1 is at most T i m e [ 3 1 . d u a l . When
a v a i l ( 3 1 is m a d e suHlcienUy large, s o t h a t there is more thirdwxrek capacity than can
be used. the associatcd dual value falls lo z e r o and further increases in a v a i l [ 3 ] have
n o e f f e c t on the optimal solution.
W e can s p e c i f y that looping should stop once the dual vahie falls t o zero, by writing a
r e p e a t statement that ha* one o f the f o l l o w i n g forms:

rcpoaL while T i m e 131 . d u a l > 0 ( .. .}:


repeat until T i m e 131 . d u a l = 0 ( .. .}:
repeat (...} w h i l e T i m e 131 . d u a l > 0:
repeat (...} u n t i l Time 131.dual = 0:

T h e l o o p body, here indicated by { . . . } , must be enclo&ed in braces. Paises through the


l o o p continue ai long ai lhe w h i l e condition is t m e , or as k>ng as the u n t i l condition
is false. A condition that appears before the l o o p body is tested before every pass: if a
w h i l e condition is f a b e or an u n t i l condition is tme before the first pass, then the
l o o p body is never executed. A condition that appears afier the kx>p body is tested after
e v e r y pass, s o that the l o o p body is executed at least o n c e in this case. If there is n o
w h i l e or u n t i l condition, the l o o p repeats indefinitely and must be terminated by
other means, like the b r e a k statement described below.
A complete script using r e p e a t b shown in Figure 13-3. For thb particular applica-
tion \V>Í dux>se the u n t i l phrase that b placed afier the l o o p body, ai \V>Í d o not want
T i m e [ 3 1 - d u a l t o be fcrsied until afier a s o l v e hai been executed in the first pass.
T w o other fe atures o f this script are worth noting, as they are relevant t o m a n y scripts o f
this kind.
A t the beginning o f the script w e d o n ' t k n o w h o w many passes the r e p e a t state-
ment will make through the l o o p . Thus w e cannot determine À V À I L 3 in advance as w e
did in Figure 13-1. Instead. \v\? declare it initially t o be the empty s e t

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}:

and add each n e w value o f a v a i l 1 3 ] t o it after s o l v i n g :


SECT CN 133 T E R A T N G SUBJECT TO A O O N D T O M TVt s r r r x ? S T A T W E M T 263

rodei z toe lT . n»d;


data stoelT.dat:

opLion solution procision 10:


option s o l v o r ..cnsg 0:

.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:

display avail3_obj. avail3_dual:

F i g u r e 13-3: Script for reeording sensitivhy ( s t e e l T . s â 4 ) .

lot AVA1L3 ! = A V A I L 3 u n i o n (avail(3]};


lot avail3_objlavail1311 := T o t a l . P r o f i t :
lot a v a i l 3 _ d u a l l a v a i 11311 : = T i m o l 3 1 . d u a l :

By aJding a new m e m b e r t o A V A I L 3 , \V>Í also creaie n e w componcnts o f the parameters


a v a i l 3 _ o b j and ã v a i l 3 _ d u a i that are indexed over A V A I L 3 , and s o w e c a i t pro-
ceed t o assign the appropriaie values t o these componcnts. A n y change t o a set is propa-
gated *> ali declarations that use the set, in the same way that any change t o a parameter
is propagated.
Because numbers in the computer are represented w h h a limited number o f bits o f
precision, a solver may return values that dilTer very slightly from the solution that would
be computed using e x a c t arithmetic. Ordinarily you d o n ' t see this, because the dis-
p l a y command rounds values t o six significam digits by defauh. H>r example:

a m p l : i s o d o l atoolT.aod; data otoolT.dat; solvo;


a m p l : diaplay Kakoj
Make ( * . * 1 < LrJ
: bands coils : =
1 S990 1407
2 6000 1400
3 1400 3 SOO
4 2000 4200

Compare what is s h o w n when rounding is dropped. by setting display_precision


toO:
264 CQHVX4DS C R PTS C H í f T E R 13

a m p l : option diaplay praciaion O;


a m p l : diaplay Jíoko;
Makc [ * . * l <Lr)
: harxis coils
1 S989.999999999999 14 0 7 . 0 0 0 0 0 0 0 0 0 0 0 0 2
2 6000 1199.9999999999991
3 1399.999999999999S 3S00
4 1999.9999999999993 4200

These seemingly tiny dilTcrcnces can have undcsirable e f l e c t s whencver a script m a k c s a


comparison that uses vahies returned hy the solver. T h e roundcd table would lcad you t o
believe that > C a k e [ • c o i l s ' . 2 J > = 1 4 0 0 is t m e . for example, whereas f r o m the sec-
ond table you can see that really it is false.
Y o u can avoid th ti k i n d o f surprise by writing arithmetic tests more carcfully: instcad
of u n t i l T i : n e [ 3 ) . d u a l = 0 , f o r instance. you mjght say u n t i l T i s > e [ 3 ] .dual
<= 0 . 0 0 0 0 0 0 1 . Alternatively. you can round ali solution vahies that are returned by
the solver, s o that numbers that are supposed t o be equal really d o c o m e out e^ual. T h e
statement

opLion solution_precision 10:

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

13.4 T e s t i n g a condition: the if-then-else statement


lnSectk>n 7.3 described the cx>nditional ( i f - t h e n - e l s e ) expression. which pro-
duces an arithmetic or set value that can be used in any expression c o n t c x i The if-
then-else tíuit/netti uses the same syntactic f o r m t o conditionally control the execu-
tion o f statements or groups o f statements.
In the simplest case. the i £ statement cvahiatc* a conditk>n and takes a specified
actk>n if the condition is true:

i£ Makc [ - c o i l s - . 2 1 < 1S00 t h e n o r i n L Í -urxicr lS00\n-;

T h e action m a y also be a series o f c\>mmands grouped by braces as in the f o r and


repeat commands:

if Makc [ - c o i l s - . 2 1 < 1S00 t h e n (


p r i n t í " F e w o r Lhan 1S00 c o i l s i n w e e k 2 . \ n - ;
l e L m a r k e t [ - c o i l s - . 21 : = m a r k e L l - c o i l s - . 2 1 * 1.1:
>
SECT ON ia4 T E S T N 3 A O C N D T C M THE i r tkxsi ZLSZ STATEVENT 265

A n optional e l s e specifies an altcrnaiivcaction lha! also m a y be a single command:

i£ Make [ - c o i l s - . 2 ] < 1500 t h e n (


p r i n t í " F e w c r t h a n 1500 c o i l s i n w o o k 2 . \ n - :
l o L m a r k e t l - c o i l s ". 2\ : = m a r k e t l - c o i l s - . 2 ] * 1.1:
>
else

printí -At least 1500 c o i l s i n woek 2.\n":

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í -

or equivalently. but pcrhaps more clearly.

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:

repeat while previous_dual > 0 (


solve:
i £ T i m e 1 3 ) . d u a l < p r e v i o u s _ d u a l Lhen (
l e t AVAIL3 := AVAIL3 union (availl31>:
l e t a v a i l 3 _ o b j l a v a i 11311 : = T o t a l _ P r o £ i t :
l e t a v a i l 3 _ d u a 11 a v a i l [31 1 : = T i m e l 31 . d u a l :
l e t p r e v i o u s _ d u a l : = T i m e [ 31 . d u a l :
>
let a v a i l 131 : = a v a i l 131 «- avail3_step:
}
display avail3_obj. a v a i l 3_dual:

F i g u r e 13-4: Testing condi tk>ns within a l o o p < s t e e l T . s a 5 ) .

In ali caies, an e l s e fc paircd with the ctosest prcceding available i £ .

13.5 Terminatirtg a loop: break and continue


T w o other statements work with kx>ping statementv t o make s o m e scripts casier t o
write. T h e c o n t i n u e statement terminates the current pass througha £ o r or r e p e a t
l o o p ; ali further statements in the current pass are skipped. and execution continues with
the test that oontiols the start o f the next pais ( i f a n y ) . T h e b r e a k statement completely
terminates a f o r or r e p e a t loop, sendingcontrol im media te ly k> the statement f o l l o w -
ing the end o f the l o o p .
A s a n example o f both these commands. Figure I3-5 exhibhs another w a y o f wrhing
the l o o p from Figure 13-4, s o that a table entry is made only when there & a change in the
dual vahie aisociatcd with a v a i l [ 3 1 . A f t e r s o l v i n g . w e test t o see if the new dual
value is equal t o the previous one:

i£ T i m e 131 . d u a l = previous_dual Lhen continue:

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

model s Lee l T . owd;


data sLeelT.daL:

opLion soluLion precision 10:


opLion s o l v e r msg 0:
s e L AVA1L3 d e f a u l L ( } :
param a v a i l 3 _ o b j (AVAIL3I;
param a v a i l 3 _ d u a l (AVAIL3};

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:

leL AVAIL3 : = AVAIL3 union (availl31>:


leL a v a i l 3 _ o b j l a v a i 1(3JJ : = T o t A 1 _ P r o í i L :
leL a v a i l 3 _ d u a l [ a v a i l l 31 J : = T i m e l 31 . d u a l ;
i£ T i m e (31 . d u a l = 0 Lhen break:

leL previous_dual : = Time[31. dual:


}
display avail3_obj. avail3_dual:

F i g u r e 13-5: Using b r e a k and c o n t i n u e in a kx>p ( s t e e l T . s a 7 ) .

if Time(31.dual = 0 then break:

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.

if T i m e (31 . d u a l = 0 then break:

\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:

T h e l o o p name appears right after r e p e a t or f o r , and after b r e a k or c o n t i n u e .

13.6 Stepping through a script


l f y o u think that a script might not be doing what you want it to, you can tell A M P I . t o
step through it one command at a time. This facilhy can be used t o provide an elemen-
tary f o r m o f " s y m b o l i c d e b u g g e r " for scripts.
T o step through a script that does not execute any other scripts, reset the option
s i n g l e _ s t e p *> I from its default value o f 0. K>r example, here is h o w you might
begin stepping through the script in Figure 13-5:

a m p l : option ainglo atap lj


a m p l : ccazands otoolT.ca?j
steelT.sa7 :2(16) data . . .
<2 >ampl :

T h e expression s t e e l T . s a 7 : 2 { 1 8 > gives the filename. line number and character


number where AMPI. s*>pped in its processing o f the script lt is f o l l o w e d by the
beginning o f the next command < d a t a ) *> be executed. On the next line you are returned
t o the a m p l : prompt. T h e < 2 > in front indicates the levei o f input nesting: " 2 " means
that executk>n is within the scope o f a c o m n a n d s statement that w » in turn issucd in the
original input stream.
A t this point you may use the s t e p command t o execute individual c\>mmands o f the
ser ipt. T y p e s t e p by itse lf t o exeeute one command.

<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

If s t e p is f o l l o w x l by a number, thai number o f o o m m j n d s w i l l be executcd. Every


command i% counted except those having k> d o with nnxlel dcclarations. sueh as rr>cdel
and p a r a m in ihis example.
Each s t e p returns you t o an A M P l . prompt. Y o u m a y continue stcpping until the
script ends, but at s o m e point you w i l l want t o d&play some values t o see if the script is
w o r k m g . This sequence captures one p b c e where the dual value changes:

< 2 > a m p l : diaplay avail [3] , Tiiso[3) . dual, proviouo dual;


avail13| = 2 2
T i mel 3J . d u a l = 3 6 2 0
p r e v i o u s _ d u a l = 3G20

<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 :

A n y series o f A M P l . commands may be typed while single-stepping. A f t e r each c o m -


mand. the < 2 > a m p l prompt returns t o remind you that you are still in this nnxle and may
use s t e p t o continue executing the script.
T o h e l p you step through lengthy compound commands ( f o r , r e p e a t , or i£)
A M P L provides several ahernatives t o s t e p . T h e n e x t command steps pait a c o m -
pound command rather than into i t If w e had staned at the beginning. each n e x t would
cause the next statement t o b e executed: in the case o f the r e p e a t , the entire cx>mmand
would be executed. stopping again only at the d i s p l a y command on line 28:

a m p l : option ainglo atop lj


a m p l : coxazanda atoolT.aa7j
steelT.sa7:2<18J data . . .
<2>ampl: noxt
steelT.sa7:4<36) option ...
<2>ampl: n o x t
steelT.sa7:5<66) option ...
<2>ampl: n o x t
steelT.sa7:ll<167j let ...
<2>ampl: n o x t
S t e e l T . s a 7 : 1 4 <225) repeat ...
<2>ampl: n o x t
steelT.sa7:2B<S39) display ...
<2 >ampl :
270 CQHVX4D S C R PTS C H í f T E R 13

Typc n e x t n tostcp pavt n cx>mmands in this way.


T h e commands s k i p and s k i p n work like s t e p and s t e p / i , except that they skip
the next I or n commands in the ser ipt rather than executing them

13.7 Manipulating character strings


T h e ability *> work with arbitrary sets o f character strings is one o f the key aJvan-
tagesof AMPI. scripting. We describe here the string concatcnation operator and several
functk>ns for building up string-valued expressions that can be used anywhere that set
members can appear in AMPI. staiemcnts. Further detaik are provided in Scction A.-I2.
and Table A--1 summari/es ali o f the string funetions.
W e also show how string expressions may be used to specify character strings that
serve purposes other than being set members. This feature allows an AMPI. script to, for
example. write a differem file or set diíTerent option vahies in each pass through a kx>p,
according to informatk>n derived from the contento of the loop indexing sets.

String funetions and operators

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

Numbers that appear as arguments t o & are automahcally convcned to strings. A s a n


example. for a multi-wxrek nnxlel you can create a set o f generically-nameJ perkxls
WEEK1, WEEK2, and so forih. by declaring:

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;

s o t WBBXS o r d e r e d = setoí ( t in 1..T} "WBBX" U 0 . 1 * t ;

But the autuai set comes out differently:


ampl: l o t T i* 4;
a m p l : diaplay WEEKSj
s e L WBBXS : =
WBBXO . 1 WBBXD. 30000000000000004
WBBXO.2 WBBX0.4:

Because 0.1 cannot be stored exactly in a binary representation. the value o f 0 . 1 * 3 is


sljghtly different from 0.3 in " f u l l " precision. There is no eaiy way to predict this
behavior, but it can be prevented by specifying an explicit conversion using aprintf.
The s p r i n t £ funetion does format conversions in the same way as p r i n t í (Section
A . 16), except that the resulting formaled string is not sent to an output stream. but
instead becx>mes the function's return value. For our example. "WEEK• & 0 . l * t could
be re placed by s p r i n t £ { 'WEEK%3. l £ ' . 0 . l * t ) .
T h e l e n g t h string funetion takes a string a* argument and returns the number o f
characters in it The m a t c h funetion takes two string arguments. and returns the first
position where the second appears a* a substring in the first, or zero if the second never
appears as a substring in the first. For example:

a m p l : diaplay ( j in FOOD) (langth(j), aatch(j,"H"));


i l e n g t h ( j ) match<j. • ir ) :=
BBBF 4 0
C1JX 3 2
F1S11 4 4
11AM 3 1
MCH 3 3
mu 3 o
SPG 3 0
TUR 3 0

The s u b s t r funetion takes a string and one or t w o integers as arguments. It returns a


substring o f the first argument that begins at the position given by the second argument: it
272 CQHVX4D SCR P T S C H í f T E R 13

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:

param amL (NITTR.FOOD} >= 0:

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:

param iNITTR symbolic;


param jFOOD symbolic;
param upos > 0:
l e L NITTR : = (}:
l e L FOOD : = (}:
íor (ij i n NtTTR_FOOD} (
IoL upos := m a L c h ( i j .
leL itJUTR : = s u b s L r ( i j . 1. u p o s - l j ;
leL jFOOD : = s u b s L r ( i j , u p o s + 1 J ;
Io L NITTR := NUTR union ( ÍWUTR} ;
leL FOOD := FOOD union ( j F O O D } ;
leL amL [ i í f J T R . jlADODl : = amL_nuLr ( i j 1 ;
}
Under either alternative, errors such as a missing in a member of KUTR_FOOD are
eventually signalcd by error messages.
SECT-ON 137 WANRJLATP»3CHí«/C7mSTRM3S 273

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.

String expressions in AMPL commands

wString-vahied expressk>ns may appear in place of literal strings in several contexts: in


filenames that are pari o f cx>mmands, including s t c d e l , d a t a , and corerKinds, and in
filenames following > or > > to specify redircctk>n of output: in values assigncdto AMPI.
options by an o p t i o n command: and in the string-list and the databaic row and column
names specified in a t a b l e statement. In ali such caies, the string expressk>n must be
identified by enclosing it in parentheses.
Ilere ti an example involving filenames. This script uses a string expression to spec-
ify files for a d a t a statement and for the redirection o f output from a d i s p l a y state-
ment:

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 " ) í
}

The result is to solve d i e t . m o d with a series o f dilTerent data files dietl.dat,


diet2.dat, and d i e t 3 . d a t , and k> save the solution to filei dietl.out,
d i e t 2 . o u t . and d i e t 3 . o u t . The vahie o f t h e index j ii converted automalically
from a number toa string as previously explained.
T h e following script uses a string expression to specify the value o f the option
c p l e x _ o p t i o n s , which contains directions for the CPLEX solver:

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:

a m p l : xzodol atoolT.aod; data ataolT.dat;


a m p l : option ohow st ata 1;
ampl: aolvo;
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 v a r i a b l e s .
Adjusted problem:
24 v a r i a b l e s , a l i l i n e a r
12 c o n s L r a i n L s , a l i l i n e a r : 3& 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 .
M1NQS 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 S1S033

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

Y o u can determine which variables and constraints presolve eliminatcd by testing. ai


cxplaincd in Section 14.2, *> see which have a s t a t u s o f p r e :

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

Y o u can then use s h o w and d i s p l a y t o examine the eliminatcd components.


In this section w e introduce the operatk>ns o f the presolve pha*e and the options f o r
controlling it from A M P I . . W e then e x p b i n what presolve does when it dctects that n o
f e a ú b l e solution is possible. W e will not try k> e x p b i n the whole presolve algorithm.
however: one o f t h e references at the end o f t h i s c h a p t e r contains a complete descriptk>n.

Activities of the presolve phase

T o g e n e r a t e a problem insiancvr. AMPI. llrst assignseach variable whatever bounds are


specified in its v a r declaratk>n. or the special bounds - I n f i n i t y and Infinity
when n o l o w e r or upper bounds are given. T h e presolve pha*e then tries k> use these
bounds togcther with the linear constraints t o deduce tighter bounds that are still sat&ficd
by ali o f the problemas feasible sohitions. Concurrently. presolve tries t o use the tighter
bounds t o detect variables that can be fixed and constraints that can bedropped.
Presolve inhially looks for constraints that have only one variable. Equalitics o f this
kind fix a variable, which may then be dropped from the problem. Incqualitie» s p e c i f y a
bound f o r a variable, which may be f o l d c d into the existing bounds. In the e x a m p l e o f
s t e e l T . r > c d (Figure -1-4) shown above. presolve eliminates the t w o constraints gener-
ated f r o m the declaration

subject to Initial (p in PROD}: Xnvlp.OJ = invOlpl;

along with the t w o variables fixed by these constraints.


Presolve continues b y sceking constraints that can be proved redundam by the current
bounds. T h e constraints eliminatcd from d i e t u . r>cd (Figure 5 - 1 ) provide an example:

ampl: isodol diotu.xood; data diotu.dat;


ampl: option shou- atata 1;
ampl: aolvo;

Presolve eliminates 3 constraints.


Adjusted problem:
8 variables. a l i linear
S c o n s t r a i n t s . a l i l i n e a r ; 39 n o n z e r o s
1 linear o b j e e t i v e ; 8 nonzeros.

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

On further investigation, lhe constraint D i e t _ M i n [ ' B l ' ] is seen t o bc redundam


because it is generated from

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 :

ampl: diaplay SUE ( j in FOOD) amt['A',J] • f xaax[j);


sum( j i n FOOD} a m L [ ' A v . j j * f m a x l j l = 2860

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):

ampl: isodol xoilti .xoodj


ampl: data xaulti.dat;
ampl: option ohow otato 1;
ampl: aolvo;

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: print ( j in 1. . nvara:


ampl? var .ata tua [ j ) * "pro ") i varnaao [j) j
Trans l ' GARY' . 'LAN ' , ' p l a L e ' |
Trans l ' CLKV' . • LAN ' . ' p l a L e 1 1
Trans l' PITT' . • LAN ' . ' p l a L e 1 1
278 N T E F V C T CNS V / T H S O L \ € R S C H í f T E R 14

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.

Controlüng the effects of presolve

For more c o m p l e x problems. p r e s o l v e ' s e l i m i n a t i o n s o f variables and constraints may


not be s o e a * y t o explain, but they can represem a substantial fractk>n o f the p r o b l e m
T h e time and m e m o r y needed t o s o l v e a problem instance may be reduced considerably
av a resuh. In rare caües, presolve can also substantially a f f e c t the optimal values o f the
variables — when there is more than one optimal solution — or interfere whh other pre-
processing routines that are built into your solver software. T o turn oíT presolve entirety,
set option p r e s o l v e t o 0: t o turn oíT the second pan only, set it t o I . A higher value f o r
this option indicates the maximum number o f passes m a d e in part t w o o f presolve: the
default is 10.
SECT0N14 1 FRESCLVE 279

F o l l o w i n g presolve, A M P L saves t w o seis o f l o w e r and upper bounds on lhe variables:


ones that relleet the tightening o f the bounds implied by constraints that presolve e l i m i -
nated. and ones that relleet further tightening dedueed from oonstraints that presolve
could not eliminate. T h e problem has the same solutkxn with either set o f bounds, but the
overall sokition time may be lowxrr with one or the other, depending on the optimi/ation
method in use and the speeifies o f the p r o b l e m
For continuous variables. normally A M P L passes t o solvers the first set o f bounds, but
you can instruct it t o pass the second set by changing option v a r _ b o u n d s t o 2 from hs
default vahie o f I . W h e n active-set methods < like the simplex method) are applied, the
second set tends t o g i v e rise t o more degenerate variables, and hence more degeneraie
iterations that may impede progress toward a solution.
For integer variables, A M P L rounds any fractional lower bounds up t o the next higher
integer and any fractional upper bounds down t o the next lower integer. Due t o inacvura-
c i e s o f finite-precision computation, h o w e v e r , a bound may be calculaied to have a value
that is just sljghtly diíTerent from an integer. A l o w e r bound that should be 7, f o r e x a m -
ple, might be caLulated ai 7.00000000001, in which case you w o u l d not want the bound
t o be rounded up t o 8 ! T o deal with this possibilhy, A M P L subtracfc the value o f option
presolve_inteps from each l o w e r bound, and adds it t o each upper bound, before
rounding. If increasing this setting t o the value o f option presolve_intepsrkix
would make a diflerence t o the rounded bounds o f any o f the variables, A M P L issues a
warning. T h e defauh values o f p r e s o l v e _ i n t e p s and p r e s o l v e _ i n t e p s r r K i x are
l . 0 e - 6 a n d l . 0 e - 5 . respectively.
Y o u can examine the first set o f presolve bounds by using the suffixes . I b l and
. u b l , and the second set by . I b 2 and . u b 2 . T h e original bounds, which are sent to the
solver only if presolve is turned ofT, are given ai . l b O and . ubO. T h e suffixes . l b and
. u b g i v e the bound values currently ii> be pavsed t o the solver, ha*xl on the current v a l -
ues o f options p r e s o l v e and v a r ^ b o u n d s .

Detecting infeasibility in presolve

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

This is a simple c a i e , because the upper bound on variable S í a k e [ • b a n d s • 3 hai clearly


been reduced b e l o w the l o w e r bound. Presolve's more sophisticated lesti can a b o find
280 NTEFVCT CNS V/TH S O L \ € R S CHífTER 14

infeaiibilities that are not due k> any one variable. A s an example, consider the constraint
inthis model:

subjoct to Time: sum ( p i n PttDD} 1 / r a t o [ p l "Make [pJ <= avail:

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 narkot[ "banda") i» 3000;


a m p l : l o t a v a i l i* 13;
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 <= 13 c a n n o t b e > = 1 3 . 2 5 6 9 : d i f f c r e r x r e = -0.2SB929

T h e " b o d y " o f constraint T i m e is s u m < p i n P R O D } l / r a t e [ p ] • J í a k e l p ] , the


part that contains the variables (see Section 12.5). Thus, given the value o f a v a i l that
we have s e t the constraint placcs an upper bound o f 13 on the value o f t h e body expres-
sion. On the other hand. if we set each variable in the body expression equal t o ifc l o w e r
bound, g e t a lower bound on the value o f the body in any f c a i i b l c solution:

ampl: diaplay aUE {p in PROD) l/rato[p) 'Kakalp) .lb2;


sum(p i n PROD} 1 / r a t e l p p ( M a k e l p l . l b 2 j = 13.2SB9

T h e statement from presolve that b e d y < = 1 3 c a n n o t b e > = 1 3 . 2 5 8 9 isthus report-


ing that the upper bound on the body fc i n c o n t l i c t whh the k>wer bound. implying that n o
solution cansatisfy ali o f t h e problem's bounds and constraint».
Presolve reports the dilTerence between hs t w o bounds for constraint T i m e ai
- 0 . 2 3 8 9 2 9 ( t o six djgits). Thus in this case we can guess that 13.258929 is. approxi-
mately, the smallest value o f a v a i l that a l i ow s for a f e a i i b l e solution, which \V>Í can
v e r i f y by experiment:

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

ampl: option diaplay prociaion 10;

ampl: diaplay C C E E Í C , KAkm;


: cccxnit Make :=
bands 1000 999.999B8S7
coils SOO SOO
plate 7 SO 7S0

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: option aolvor cplox;


ampl: option aand atatuaoa 0;

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

Settin? $p r e s o l v e . e p s >= G. BGe-07 m i g h t help.

in the e x a m p l e above. The default value o f option p r e s o l v e _ e p s is zaro and


p r e s o l v e _ e p s r « i x fc lJ0e-5.
A rclated situa tion occurs when imprecision in the computatk>ns causes the implkrd
l o w e r bound on s o m e variable or constraint Ixxly t o c o m e out slightly k>wer than the
implied upper bound. l l e r e n o infeasibility is detected. but the presence o f bounds that
are nearly equal may make the s o l v e r ' s work much harder than necessary. Thus when-
282 N T E F V C T CNS V / T H S O L \ € R S C H í f T E R 14

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.

14.2 Retrieving results from solvers

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: xzodol diot.xaod;


ampl: data diot2.datj

a m p l : diaplay aolvo roault nua, aolvo roault;


solve_rci:ulL_num = -1
solve_rci:ult = ' ? '

ampl: aolvo;
Ml NOS S . S : i n í e a n i b l c problcm.
9 iLeraLions

a m p l : diaplay aolvo roault nua, aolvo roault;


s o l v o _ r c i : u l L _ n u m = 2 00
solvo_rc;:ult = iníoasi blo
SECT ON 14 2 RETREVNQ RESULTS FTOW SCLVERS 283

a m p l : option aolva rasult tabloj


option solve. result_table '\
0 solvod\
100 solvcd?\
200 infeasible\
300 untourxiodX
400 l i m i t\
SOO f a i l ure\

At the beginning of an AMPI. session. solve_result_nu:n is -1 and


s o l v e _ r e s u l t is ' ? ' . Each s o l v e c\>mmand resets these parameters. howxrver, so
thai they describe the solver's status at the end of ife run. s o l v e _ r e s u l t _ n u n by a
number and s o l v e _ r e s u l t by a character string. The solve_result_table
option lists the possible combinations. which may be interpretei! ai follows:

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:

a m p l : cassando diat. run;


<1 >ampl ? NA
c l v a m p l ? 60000
< l > a m p l ? 3000
i n í e a s i b l e a t 48000

. 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:

Flfture 14-1: Sensitivity analysis with infeasibility test ( d i e t . r u n ) .

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:

solve_result_num mcwagL- JA tcrminatum


0 aptnLilsolutkin
1 primai hxs untxiundi-d optmLil ÍJCV
2 apfcnLilintcgi-r sohitoon
3 apfcnLilintcgi-r sohitian w i t h i n m i p g a p o r a b s m i p g a p

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:

a m p l : diaplay aolvo coaaaffo;


j M l v c j n c s ü a g c = • M1ÍJOS S. 5 : i n f c a s i b l e p r o b l e m . \
9 iterations •

Because s o l v e _ m e s s a g e is a symbolic parameter. its value is a eharacter string. It is


most use fui in scripts. where you can use eharacter-string funetions (Section 13.7) to test
the messagc for indica tions o f optimal ity and other outeomes.
A s a n example. the test in d i e t . r u n could a b o have been written

if match(solve. m o s s a , •infcasiblc") > 0 then (

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.

Solver statuses of objectives and problems

vSometimes it isconvenient t o be able t o refer t o the s o l v e result obtained when a par-


ticular objective was most recently optimizcd. For this purpose, A M P l . associates with
each buih-in solve result parameter a " s t a t u s " suíTix:

buill in juramctcr suffix

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

Appended t o an objective name. this s u f f i x indicates the value o f the correspondi ng


built-in parameter at the motU recent s o l v e in which the objective was current.
A s a n example, w e consider again the muhipie objectives defined for the assignment
nnxlel in S e c t i o n S . 3 :

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:

a m p l : xsodol tranap4. xoodj data aaaiçjn. dat j aolvo;


CPLEX 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 2 6
24 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 I J
Objective = Total_Cost
S E C T O N 14 2 R E T R E V N Q RESULTS FTOW S C L V E R S 287

a m p l : objactivo Prof o£['Coullard'J j


ampl: aolvo/
CPLlüC B . 0 . 0 : o p t i m a l solution; objective 1
3 simplex i t e r a t i o n s <0 i n p h a s e IJ
a m p l : objactivo Prof of['Hazan ') j
ampl: aolvo;
CPLlüC B . 0 . 0 : o p t i m a l solution: objective 1
S simplex i t e r a t i o n s <0 i n p h a s e 1J

a m p l : diaplay Total Coat.rooult, Prof of.raaultj


Total_Cost.result = solved

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.

Solver statuses of variables

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:

a m p l : isodol atoolT3. xood;


a m p l : data atoolT3.dat;
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 p h a s e I J
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 537104
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
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
0 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
a m p l : l o t (t in 1..T) avail [ t ) i - 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
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
SECT ON 14 2 R E T R E V N Q RESULTS FTOW SCLVERS 289

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: modol diot.xaod;


ampl: data diot2a.datj

a m p l : diaplay Buy. aa tatua/


Buy.«tatus l* l : =
BKKF none
ClIK none
F1S11 none
1JAM none
MCil none
MTL none
SB3 none
TUR none

A f t e r an invocation o f a simplex method solver, the same d i s p l a y lists the statuses o f


the variables at the optimal haiic sohition:

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

a m p l : option BBtatus tabloj


option sstatus_t_able " \
0 none no s t a t u s assignod\
1 has basic\
2 sup superbasic\
3 low n o n b a s i c <= ( n o r m a l l y =J l < y * e r b o u n d \
4 upp n o n b a s i c >= ( n o r m a l l y =J u p p e r b o u n d \
5 03 u n o n b a s i c a t 0:3uai l o w e r a n d u p p e r b o u n d s \
6 btw n o n b a s i c between bounds\

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

p a r a m nPAT i n t e g e r > = 0: i number o £ p a t t e r n s


s e t PATTKRNS = 1 . . n P A T : ft s e t o£ p a t t e r n s
v a r C u t ( P A T T K R N S } i n t e g e r >= 0 ; * r o l l s c u t u s i n g each pattern

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:

• A f t e r the problem and statuses have been nuxlified, the statuses c o n v e y e d


t o t h e solver at the next s o l v e may not properly define a basic solutk>n.

• A f t e r the problem has been modifíod, A M P L ' s presolve phase m a y send a


diíTerent subset o f variables and constraints t o the s o l v e r ( u n l e s s option p r e -
s o l v e is set t o z e r o ) . A s a resuh, the statuses c o n v e y e d t o the solver may
S E C T O N 14 2 R E T R E V N Q R E S U L T S FTOW S C L V E R S 291

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: diaplay { j in 1. . nvara: var [ j ) .aot atua * mbaa-)

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

A n anak>gous listing o f ali the variables would be pcoduced by the command

display _varname. _var:

Solver statuses of constraints

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: xsodol atoolP.xsod;


ampl: data ataalP.dat;

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:

subject to Diet ( i in NUTR} :


rx m i n l i l <= sum ( j i n FOOD} amt[i.jl * Buyljl <= n m a x [ i l :

the k>gical variables are slacks that have the same variety o f statuses as the structural vari-
ables:

ampl: xsodol dlot.xsod;


ampl: data diot2a .dat;

a m p l : option show atata 1;


ampl: aolvo;
8 variables. a l i linear
G c o n s t r a i n t s . a l i l i n e a r : 47 i » n z e r o s
1 l i n e a r o b j e c t i v e : 8 rx>nzeros.
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. aa tatua ;


Buy.sstatus 1*1 : =
BKKF bas
CHK lcm
F1S11 low
JJAM upp
MCil upp
MTL upp
SKI bas
TUR 1 c/ti
S E C T O N 14 2 R E T R E V N Q R E S U L T S FTOW S C L V E R S 2 9 3

ampl: diaplay Diot.aotatuo;


dieL. ssLaLus l*J :=
A bas
Bl bas
B2 low
C bas
CAL bas
NA upp

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

ampl: diaplay connaxao, con.alack, con.a ata tu a;


: _conname _con.slack _con.
1 -Supply ['GARY' 1 - -4.S47 47e-l3 equ
2 -Supply ['CLEV 1- 0 equ
3 •Supply 1 ' P I T T ' 1 - -4.S47 47e-l3 equ
4 "Dcmand l • F R A ' 1 " -G.B2121C-13 bas
S -Dcmand[,Dlfr,l- 0 equ
G *Dcmand[aLANv 1 " 0 equ
7 -Dcmand[,WlM,l- 0 equ
8 *D«nar>d l • STL " 1 " 0 equ
9 *D«nar>d l • FRK ' J • 0 equ
10 -Dcmand[,LAF,l- 0 equ

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 : option as tatus tablo;


option astatus_table ' \
0 in normal s t a t e < in problcmJ\
1 drop r e m o v e d b y d r o p ccmmarxi\
2 pre e l i m i n a t e d by p r e s o l v e \
3 íix í i x e d b y í i x ccmmand\
4 sub defined variable. substitutod out\
S unusod n o t usod in c u r r e n t p r o b l e m \

I iere' s an example o f the most c o m m o n cases, using one o f our diet m o d c k :

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 m p l : diaplay Diot Nin.aotatuo;


Diet_Min.astatus l*l : =
A in
Bl pre
B2 pre
C in
CAL drop

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:

• Variables B u y [ ' C H K ' l and B u y f S F G ' ) have A M P I . status -fix'


because the í i x c o m m a n d was used t o s p e c i f y their values in the solution.
SECT O N 14 3 E X C K V X ã N G N F C F W A T C N V/TH S O L \ € R S V A S U F F X E S 295

• Constraint D i e t _ M i n t ' C A L ' J has A M P l . status ' d r o p ' because it w a s


removei! by the d r o p c o m m a n d .

• Constraints D i e t _ M i n [ ' B I ' ) and D i e t _ M i n [ ' B 2 ' ] have A M P l . sta-


tus ' p r e ' because they w e r e removed from the problem by simplifications
performed in A M P L ' & p r e s o l v e phase.

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:

a m p l : diaplay Buy.atatua, Buy.aatatua, Buy.aatatua;


: Buy. s t a t u s Buy. a s t a t u s Buy. s s L a L u s : =
HBKF Ia* in low
CiJX fix fix I>D n e
F1S11 lOM in low
HAM lOM in low
MCH bas in bas
XV L lOM in low
SP G fix fix 1X5 n e
TUR lo* in low

ampl: diaplay Diot Hin.atatua, Diot Hin.aatatua,


ampl? Diot Hin.aatatuaj
: D ic t_M in,.status D i o t M i n . a s t a t u s D i c t _ M i n .s s t a t u s
A bas in bas
Bl prc prc nane
B2 prc prc nane
C low in 1 OW
CAL drop drop nane

In general, mune. status is equal k> mune. s s t a t u s if mune. a s t a t u s is "in"


and isequal t o mune. a s t a t u s othenvise.

14.3 E x c h a n g i n g information with solvers via suffixes


W e have seen that t o represem values associatcd with a mixlel componcnt. A M P l .
employs various qualifiers or suffixes appended t o componcnt names. A suffix consists
o f a period or " d o t " ( . ) followvrd by a (usual ly short) identifier. s o that for example the
reduced cost associated with a variable B u y [ j ] is written B u y [ j 1 . r c , and the reduced
296 N T E F V C T CNS V / T H S O L \ € R S C H í f T E R 14

costs o f a l l such variables can be v i e w e d by g i v i n g lhe command d i s p l a y Buy.rc.


There are numerous buili-in sufTixes o f this kind. summari/ed in the tables in A . 11.
A M P L cannot anticipate ali o f the values that a solver might associate with nnxlel
components. howxrver. T h e values recognizcd ai input or computcd as output depend on
the design o f each solver and its algorithms. T o provide for open-ended representation o f
such values, n e w suffixes may be defined for the duration o f an A M P L session, ehher by
the user for sending values t o a solver. or by a solver for returning values.
This section introduces both user-defined and solver-defined sufTixes. ilhistrated by
features o f the C P L E X solver. W e show h o w user-definod suffixes can pass preferences
for variable seleetion and branch direction k> an integer programming solver. Sensitiv ity
analystü provides an example o f solver-defined suffixes that have numeric values. while
infeasibflity diagnosis s h o w s h o w a s y m b o l i c (string-valued) suíTix works. Reporting a
direction o f unboundedness gives an example o f a solver-defined sulTix in an A M P I .
script, where it must be declared before it can be used.

User-defined suffixes: integer programming directives

M o s t solvers recognize a variety o f algorithmic c h o i c e s o r settings, each governed by


a single value that applies t o the entire problem being solved. Thus you can alier selected
settings by setting u p a single string o f directives, ai in this example applying the CPLEX
solver t o a n integer program:

ampl: modol mui tmip3 .modj


ampl: data multmip3. dat;

ampl: option aolvor cplaxj


ampl: option cplox option a 'nodoaol 3 varaol 1 backtrack 0.1't

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:

ampl: a u f f i x priority IN, intagor, >» 0, <• 9999j


ampl: a u f f i x diroction IN, intoQar, >» -1, <• 1/
S E C T ON 14 3 EXCKVXã NG N F C F W A T C N V / T H S O L \ € R S V A S U F F X E S 297

T h e e f f e e i o f these statements is t o d e f i n e expression* o f the form m i m e . p r i o r i t y and


mimt . d i r e c t i o n . where mime denotes any variable, objective o r constraint o f the cur-
rent nnxlel. T h e argument I K specifies that vahies corresponding to these suffixes are t o
be read in by the solver, and the subsequcnt phrascs place restrictions on the vahies that
will be accepted ( much as in a p a r a r » dcclaration).
T h e newly defined suffixes may be assigncd values by the l e t c\>mmand (Section
11.3) or by later dcclarations ai described in Sections A . 8 . A . 9 , A.IO, and A . 18.8. For
our current e x a m p l e want t o use these sulTixes to assign CPl.IIX priority and dircction
values corresponding t o the binary variables U s e [ i . j ] . Normally such values are c h o -
scn bavedon knowlcdge o f the p r o b l e m a n d paitexpcrience with similar problems. Ilere
is one possibiiity:

ampl: lot ( i in ORIG, j in DEST)


ampl? Usa [ i , j ) .priority t* sua {p in PROD) daaand [ j , p) ;
ampl: lot Uaol" GARY", " FRE") .diroction t» -1/

Variables not assigned a . p r i o r i t y or . d i r e c t i o n value g e t a default value o f zero


(as d o ali constraint» and objcctives in this example), as you can check:

ampl: diaplay Usa .diraction;

Use.direction l*.*l (trj


: CLKV GARY P I T T :=
DKT 0 0 0
FRA 0 0 0
FRI£ 0 -1 0
LAF 0 0 0
LAN 0 0 0
SVL 0 0 0
WIN 0 0 0

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: option rosat initial guossos 1;

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

( W e have set option r e s e t _ i n i t i a l _ g u e s s e s t o I s o t h a t the optimal sohition from


the first CFl.ILX run \v\>n't be sent hack to the second.)
Funher information about the sulTixes recognized by CPl.IIX and h o w t o determine
the corresponding settings can be found in the C P L E X driver documentaiion. Other
solver interfaces may recognize dilTerent suffixes for dilTerent purposes: you'11 nced t o
check separately for each solver you want t o use.
298 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14

Solver-defined suffixes: sensitivity anatysis

When thckeyword s e n s i t i v i t y is included i n C P L E X ' s list o f directives. cbssical


sensitiv hy ranges are computcd and are returncd in three new sufTixcs. . up, . d o w n . and
.current:

ampl: isodoi atoolT.xsod; data otoolT.dat;


ampl: option oolvor cplox;
ampl: option cplox options ' oonaitivity';

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:

ampl: diaplay Soll.doxfn, Soll. curront, Soll.up;


i Sell.down Sell.current Sell.up :=
bands 1 23.3 25 le+2 0
bands 2 25.4 2G l o 4-2 0
bands 3 24.9 27 27.5
bands 4 10 27 29.1
coils 1 29.2857 30 30.8571
coils 2 33 35 le+2 0
coils 3 35.2857 37 le*2 0
coils 4 35.2857 39 l e 4-20

For constraints. the interpretation fc similar except that it applics to a constraint's constam
term (the so-calkrd rjght-hand-side value):

a m p l : diaplay Tiiso.do%fn, Tixso. curront, Tiizo.up;


: T i m e . down T i m e . c u r r e n t T i m e . up :=
1 37.8071 40 GG.37 8G
2 37.8071 40 47.8571
3 25 32 45
4 30 40 G2.5
S E C T CN 14 3 EXOtf**3 P*3 N F C F W A T C N V/TH S O L \ € R S V A S U F F X E S 299

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.)

Solver-defined suffixes: infeasibility diagnosis

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':

a m p l : xzodol diot.xaod; data diot2 .dat; option aolvor cplax;


ampl: aolvo;
CPLKX 8 . 0 . 0 : i n í e a s i b l e p r o b l e m .
4 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
c o n s t r a i n t .dunbcfci r o L u r n e d
s u í í i x dunbdd Ot/r:

a m p l : option cplax option a 'iiatind 1';


ampl: aolvo;
CPLKX 8 . 0 . 0 : i i s í i n d 1
CPLKX 8 . 0 . 0 : i n í e a s i b l c p r o b l e m .
0 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
R e t u r n i n g i i s o í 7 v a r i a b l e s and 2 c o n s t r a i n t s .
c o n s t r a i n t .dunbdd r o L u r n e d

suííix iis s y m b o l i c OUT;

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

a m p l : diaplay vamaxsa. var.iia, corna na, con.iiaj


: _varrvamc _var.iis . conrvamc _con. i i c
1 - B u y f B B K K ' 1" upp " D i c L l ' A ' 1" í»n
2 "Buyl 'CH*' 1 " low "DicLl'Bl'1" í»n
3 • B u y l ' F 1 S H * 1" low •DicLl'B2'1" low
4 • B u y l " HAM* 1 " upp •DicLl,C,1" í»n
S " B u y l ' HCir 1 - i»n • D i c L l 'NA* 1 " upp
G " B u y l ' HTL' 1 - upp • D i c L l 'CAL' 1 - ran
7 "Buyl'SPG*1" low
8 " B u y l " TUR* 1 " low

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 . )

Solver-defined suffixes: direction of unboundedness

For an unboundcd linear program — one that ha* in e f l e c t a minimum of


- I n £ i n i t y o r a maximum o f - * - I n £ i n i t y — a solver can return a r a y o f feasible solu-
tions o f the f o r m -V + a d. where a 2 0. On return from CPLEX, the f e a i i b l e solution ,Y
is given by the values o f the variables. while the direction o f unboundedness </is given by
an aJditional vahie associatcd with each variable through the solver-defined suffix
. unlxld.
An application o f the directk>n of unboundedness can be found in a nnxlel
t r n l o c l d . r > c d and script t r n l o c l d . r u n f o r Benders dccomposhion applied t o a
combination o f a warchouác-locatk>n and transponation problem: the nnxlel. data and
script are available from the A M P I . w e b site. W e w o n ' t try t o describe the whole d e c o m -
position scheme here. but rather concentra tc on the subproblem obtained by fixing the
zero-one variables B u i l d [ i ] , w h i c h indicate the warehouses that are t o be built. t o trial
values b u i l d [ i ] . In its dual form, this subproblem is:
S E C T CN 14 3 E X O t f * * 3 P*3 N F C F W A T C N V / T H S O L \ € R S V A S U F F X E S 301

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:

a m p l : xsodol trnlocld .mod;


a m p l : data trnlocl.dat;
a m p l : problozs Subi Supply Prico, Doaand Prico,
ampl? Dual Ship Cost, ZXial Ship/
a m p l : l o t { i in ORIG) build[i) i* 0;
a m p l : option aolvor cplax, cplax optiona 'proaolvo 0';
ampl: aolvo;
CPLlüí 8 . 0 . 0 : p r e s o l v e 0
CPLlüí 8 . 0 . 0 : u n t o u n d e d p r o b l e m .
2S d u a l s i m p l e x i L e r a L i o n s <2S i n p h a s e IJ
variable.unbdd reLurned

G exLra simplex iLeraLions for ray <1 i n p h a s e IJ

suffix unbdd OUT;

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:

a m p l : diaplay Supply Prico. unbdd;


S u p p l y _ P r i c e .unbdd 1*1 : =
1 -1 4 -1 7 -1 10 - 1 13 - 1 1G - 1 19 - 1 22 -1 2S -1
2 -1 S -1 8 -1 11 - 1 14 - 1 17 - 1 20 - 1 23 -1
3 -1 G -1 9 -1 12 - 1 IS - 1 18 - 1 21 - 1 24 -1

a m p l : diaplay Daxsand Prico. unbdd;


Dcmand P r i c e . unbdd 1*1 : =
A3 1
AG 1
A8 1
A9 1
B2 1
B4 1

Our script for Benders deoompositkxn ( t r n l o c l d . r u n ) solves the subproblem repeat-


edly, with differing b u i l d l i l values generated from the master problem. After each
302 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14

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

suí í i x unbdd OUT;

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.

Defining and using suffixes

A n e w AMPL suffix is defined by a statement consistingof the keyword s u f f i x fol-


lowxxl by a suffix -mime and then one or more optional quaüfiers that indicaie what values
may be associatcd with the sutTix and how it may be used. For example. w e have seen
the definition

suííix priority IN. intoger, > = 0. <= 9999:

for the sutil x p r i o r i t y with in-ouu type, and toicrtt/qtttlifieis.


S E C T C N 14 3 E X O t f * * 3 P*3 N F C F W A T C N V/TH S O L \ € R S V A S U F F X E S 303

T h e s u f f i x statement causes AMPl. fc> recognize suffixeil exprewiotts o f the form


componeni-mime. suffix-mune, where eomponens-mime refers to any currently dcclarcd
variable. constraint. or objective (or problem, as defined in the next section). The defini-
tion of a suffix remains in eftect until the next r e s e t command or the end o f the current
AMPL session. The suffix-name is subject to the same rules as other names in AMPl..
Suftlxe* have a se par ate name space. however, so a suffix may have the same name asa
parameter, variable, or other model componcnt. The optional qualifiers of the s u f f i x
statement may appear in any order: their forms and effects are described below.
T h e optional fype qualifier ina s u f f i x statement indicates what values may be asso-
ciated with the suíTixed expressions. with ali numeric values being the defauh:

suíflx type values alkiwvd


mne .yveeifled Any numeric value
integer integer numeric values
binary 0<r 1
symbolic dimctcv strirçgx bstcdin optiem x»iffix-name_tábl*

Ali numeric-valuedsuffixed expressions have an inhial value of 0. Their permissible val-


ues may be fufther limited by one or t w o bound qualifiers o f the form

>= ariih *xpr


<= ariih *xpr

where arúh-expr isany arithmetic expression not involving variables.


For each s y m b o l i c suffix. A M P l . automatically defines an associated numeric suf-
fix, suffix -mune _num. An A M P l . option suffix-mim e^tàble must then be created to
define a rebtk>n between the . suffix -mime and . suffix-mime_xi\jm values, as in the fol-
lowing example:

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

in*auJ hJLIKIhng ofsufru values

IÍJ writfcn by A M P L bcforc invaling úic xoKer, then rein by inKer


OüT writfcn oi4 h> soInvt. (hcn read by A.VIH. after «hc soAvet rs fínrshxl
INOlTT both read and written. as kw 1N jnd OUT above
LOCAL nejthcr read rnr written

I K O U T is lhe defauh if n o fo-our k e y w o c d is specified.


W e have seen thai sulTixed expressions can be assigned or reassigned values by a l e t
statement

let Use ["GARY-. "FRITl . d i r e c t i o n := -1;

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 :

In general, one or more o f the phrascs in a v a r declaration may consist o f the k e y w o r d


s u Ü Ü i x f o l l o w e d by a previously-defincd suffix-namt and an expressk>n for evaluating
the associated sulTix expressions.

14.4 Alternating between models


Chapter 13 described h o w 4 'scripts' * o f A M P L o o m m j n d s can be set up t o run as pro-
grams that perform repetitive actions. In several examples, a script solves a series o f
relatcd model instances, by including a s o l v e statement inside a l o o p . T h e result is a
simple kind o f sensitivity analysis algorithm, programmed in A M P L * s command lan-
guage.
M u c h more p o w e r f u l algorhhmic procedures can be constnictcd by using t w o models.
A n optimal solution for one nnxlel yields n e w data for the other. and the t w o are solvcd
in alternation in such a way that s o m e termination condition must eventual ly be reached.
C h s s i c methods o f column and cut generation, dccomposhion, and Lagrangian relaxation
are h a t c d o n schemes o f this kind, which are described in detail in r e f e r e n c e s c h e d at the
end o f this chapter.
T o use t w o nxxlcls in this manner, a script must have s o m e way o f switching betwzen
them. Switching can be done with previously d e f i n e d A M P L features, or more clearly and
efficiently b y d e f i n i n g scparately-namcd problemsandenvironments.
S E C T C N 14 4 A L T E F M 4 T P*3 B t T V i E E N W C C € L S 305

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 o derive a more manageable m o d e l the so-called Gilmore-Gomory procedure


defines a cutting punern to be any one feasible way in which a raw roll can be cut up. A
paliem thus consisti o f a ceriain number o f rolls o f each desired width. such that their
total width does not exceed the raw width. If (as in Exercise 2 - 6 ) the raw width ii I I 0 \
and there are demands for widths o f 20% A5\ 50\ 5 5 ' and 7 5 ' . then t\v\> rolls o f 45* and
one o f 20* make an acceptable pattern. as do one o f 50* and one o f 55* < with 5 # o f
waste). Given this v i e w . the t w o simple linear programs in Figure 14-2 can be made to
work together to find an efficient cutting plan.

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

param r o l l _ w i d L h > 0: * w i d L h o £ raw rolls

SOL WIDTHS; »• SOL o f w i d t h s Lo b o c u L


param o r d e r s (WIDTHS} > 0: 4 number o f e a c h w i d L h Lo bo c u L

param nPAT i n L o g e r > = 0 : * number o f p a L L e r n s


SOL PATTKRNS = 1 . . nPAT: A seL of paLLerns

param n b r (WIDTHS. PATTKFNS} i n L e g e r >= 0:


check ( j i n PATTKRNS}!
sum ( i i n WIDTHS} i * n b r l i . j l < = r o l l _ w i d L h :
4 d e f n o f p a L L e r n s : n b r l i . j l = number
* o f r o l l s of widLh i i n paLLern j

v a r CuL (PATTKRNS} inLeger >=0: i rolls cuL u s i n g each paLLern

m i n i m i z e Number: * minimize L o L a l raw r o l l s cuL


sum ( j i n PATTBKNS} CuLlj|;

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

F f e u r e 14-2a: Paitern-hascd model for cutting optimi/ation problem ( c u t .r>cd).

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:

Figure 14-2b: Knapsack model for p a t e m gcneration problem ( c u t . wtod. continucd).

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:

pick initial patterns sufficient *> meet demand


repeat
solve the <fracik>nal) cutting optimi/ation problem
let p r i c e ( i l e^ual F i l l ( i ] . d u a l for each pane rn i
solve the patterngeneratk>n problem
if the optimal vahie is < 0 then
add a new pattern that cuts U s e ( i ] rolls o f each width 1
else
find a final integer solution and stop
SECT ON 14 4 A L T E F M 4 T P*3 B t T V i E E N W C C € L S 307

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:

uníix Use; r e s t o r e Width_Limit: objective Reduced_Cost:


í i x Cut: drop F i l l ;
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:

problem P a t t e r n . Gen: Use. 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:

The first statement defines a problem named C u t t i n g _ O p t that consists o f the C u t


variables, the F i l l constraints. and the objective Kurnber. This statement also makes
308 MTEFVCT Cf*S Y / T H 3 0 L \ € R S C H í f T E R 14

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:

p r o b l e m C u t L i n g _ O p L : CuL. Number. Fill;


o p L i o n r o l a x _ i n L o g r a l i L y 1:

problem PaLLorn Gen: Use. Roduced_CosL. Width_Limit:


o p L i o n r o l a x _ i n L o g r a l i L y 0:

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:

Figure 14-3: Gilmore-Gomory pcoccdurc forcutting-stockproblem<cuL . r u n ) .

C u t t i n g _ O p t the current problem: uses o f the v a r , m i n i m i z e , m a x i m i z e , sub-


ject t o , and o p t i o n statements now apply to this problem only. Thus by setting
option r e l a x _ i n t e < j r a l i t y to I above, for example. w e assurc that the integrality
condition on the C u t variables will be relaxed whenever C u t t i n g _ O p t is current. In a
similar way, w e define a problem ? a t t e m _ G e n that consists o f the U s e variables. the
W i d t h _ L i m i t constraint and the objective R e d u c e d _ C o s t ; this in turn beeomes the
current problem, and this time wxr set r e l a x _ i n t e 9 r a l i t y k> 0 because only integer
solutions ti> this problem are meaningful.
T h e i o r loop in Figure 14-3 createsthe initial cutting patterns, after which the main
repeat kx>p carries out the Gilmore-Gomory procedure as described previously. The
statement

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 :

Figure 14-4: Daia for cuiting-stock model ( c u t . d a t )

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

let (i i n WIDTHS} price[il : = Vi 11 [ í\ . d u a l :

transfers the optimal dual prices from C u t t i n g _ O p t to the parameters p r i c e [ i ] that


will be used by P a t t e r n _ G e n . Ali sets and parameters are global in A M P L so they can
be referenced or changed whatever the currcnt problem.
T h e second half o f the main loop makes problem P a t t e r n _ G e n and its environ-
ment current, and sends the associated integer program to the solver. lf the resuhing
objective ti sufficiently negative, the pattern returned by the U s e d ) variables is added
tothe data that will be used by C u t t i n g _ O p t in the next pass through the loop. Other-
wise no furthar progressean be made. and the kx>p is terminated.
T h e script concludes with the following statements. to solve for the best integer solu-
tion using ali paiterns generated:

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 :

The expression C u t t i n g _ O p t . r e l a x _ i n t e g r a l i t y stands for the value o f the


relax_integrality option in the C u t t i n g _ O p t environment. W e discuss these
kinds o f names and their uses at greater length in the next section.
A s a n example o f how this works, Figure 14-4 shows daia for cutting 110* raw rolls,
to meet demands o f 48,35, 24, 10 and 8 for finishod rolls o f widths 2 0 , 4 5 , 5 0 , 5 5 and 75,
respectively. Figure 14-5 s h o w s the output thai occurs when Figure 14-3's script is run
with the nnxlel and data ai shown in Figures 14-2 and 14-4. The best fractional solution
cuts 4 6 2 5 raw rolls in f i v e different paiterns, using 48 rolls if the fractional values are
rounded up to the next integer. The final s o l v e using integer variables shows how a
coilection o f six o f t h e paiterns can beapplied k> meet demand using only 47 raw rolls.

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

ampl: ccxzsaandB cut. run;

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

CPLliX B . 0 . 0 : o p t i m a l i n t e g e r solution: objective 47


5 M1P s i m p l e x i t e r a t i o n s
0 branch-and-bound nades

Cut l*| : =
1 0 2 0 3 B 4 5 5 0 G1B 7 B B B

F i g u r e 14-5: Output from execution o f Figure 14-3 cutting-stock script.

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.

Defíning named problems

A t any point during an A M P l . session. there is a eurrens problem consisting o f a list o f


variables, objcctives and constraints. The current problem is named I n i t i a l by
default. and comprises ali variables, objcctives and constraints defined so far. You can
define other " n a m e d " problems consisting o f subsets o f these oomponents, however, and
can makcthcm current. When a named problem tv made current ali o f the nuxlel c o m p o -
nente in the problem's subset are made active, while ali other variables, objcctives and
constraint* are made inactivc. More precisely, variables in the problem's subset are
unfixedand the remainder are f i x e d a t their current values. Objcctives and constraints in
the problem's subset are restored and the remainder are dropped. (Fixing and dropping
are dtscussed in Section 11.4.)
Y o u can define a problem most straightforwardly through a p r o b i e r » dcclaration
that g i v e s the problem's name and its Itvt o f componente. Thus in Figure 14-3 we have:

problem C u t t i n g _ O p t : Cut. Number. Fill;

A n e w problem named C u t t i n g _ O p t is defined. and & specified to conta in ali o f the


C u t variables. the objective N u m b e r , and ali o f the F i l l constraints from the model in
Figure 14-2. A t the same time. C u t t i n g _ O p t beeomes the current problem. Any fixed
C u t variables are unfixed, while ali other dcclarcd variables are fíxed at theircuncnt val-
ues. The objective N u m b e r t% restored if it had been previousty dropped, while ali other
dcclarcd objcctives are dropped: and simflarly any dropped Fill constraints are
restored, while ali other dcclarcd constraints are dropped.
For more complex nxxlels. the list o f a problem's componente typically include* sev-
eral collectkxns o f variables and constraints, as in this example from s t o c h l . r un (one
o f the examples from the A M P l . web site):

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

A problem dcclaration's form and intcrprctation naturally resemble those o f other


A M P L statements that specify listi o f model components. T h e declaration begins with the
k e y w o r d p r o b l e n , a problem name not previously used f o r any other model c o m p o -
nent. an optional indexing expression ( t o d e fine an indexed collection o f problems), and a
colon. Folk>wing the colon is the c o m ma-separatcd Itvt o f variables. objcctives and con-
straints t o be included in the problem. This list may oontain henti o f any o f the f o l l o w i n g
for ms, where " c o m p o n e n t * * refers t o any variable, objective or constraint:

• A component name, such as C u t or F i l l , which refers t o ali components


having that name.

• A subscriptcd component name. such ai R e d u c e d _ C o s t [ p ] , which


refers t o that component alone.

• A n indexing expression f o l l o w r d by a subscripted component name. such


ai { i in ORIG) S u p p l y t i . p l . w h i c h refers to one component for each
member o f the indexing set.

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} Supplylli.pl. ( i i n ORIG} Supply2li.pl.


(i i n ORIG. j i n DEST} T r a n s l i . j . p l .
(i i n ORIG. j i n DEST} U s o l i . j . p l

(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 :

Figure 14-6: Ahcrnatc definhion o f named cutting-stock problem* ( c u t 2 .r>cd).

command adds variables. As an example. r n u l t i l . r u n uses the f o l b w h g problesi


statemenfc:

problem M a s t e r l : A r t i f i c i a l . Weight. Excess. M u l t i . Convex:


p r o b l e m S u b i : A r t i f _ R e d u c e d _ C o s t . T r a n s . S u p p l y , Demand:

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: A r t i f i c i a l , Weight. Excess. Multi. Convex:


problem Sub: A r t i £ _ R o d u c e d _ C o s t . T r a n s . S u p p l y . Demand:

to de fine the problems initially, and then

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

Ahernatively, a r e d e c l a r e p r o b l e s i statement can give a new dcfinition for a


problem. T h e d r o p , r e s t o r e , and £ i x c\>mmands above could be repbced, for
insta nce. by

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.

reset problem Cutting_Opt:

resets the dcfinition of C u t t i n g _ O p t to the list o f components in the p r o b l e m state-


ment that moca recently defined it.

Using named problems

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

A p r o b l e m statement may also refer k> an indexed collection o f problem*, as in lhe


m u i t i 2 . r u n example cited previously:

problem Subll (p in PROD} : R©di>c«d_Cost ( p i . ...

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 .

Displaying named problems

T h e c o m m a n d conststing o f p r o b l e m alone tells which problem is current:

a m p l : c o d o l c u t .mod;
ampl: data cut.datj
ampl: problomj
problem Initial;

a m p l : probloxn Cutting Opt i Cut, Maibor, Fill;


a m p l : probloiz Pattorn Gani Uso, Roducod Coat, Width Limitj
ampl: problaaj
p r o b l e m P a t t o r n . Gcn:

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:

a m p l : ahoif Cuttinçj Opt, Pattorn Gan;


p r o b l e m C u t t i n g _ O p t : F i l l . Number. C u t :
problem P a t t o r n . Gon: W i d t h _ L i m i t . R e d u c o d C o s L . Uso:

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

a m p l : axpand Pat tom Gonj


m i n i m i z e Rcxiuced_Cos t :
-O . 166667 *Use[201 - 0. 416667*Use 1451 - 0.5niso[501
- 0.5*Usel551 - 0.e33333*Use[751 * 1;

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:

See Section 12.6 for funher discussion of s h o w and e x p a n d .

Defining and using named environments

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:

problem Mas t e r I I environ Mas L e r : ...

T h e named environment is then automatically made current whenever the associatcd


problem becomes current. T h e usual crcaiion o f an environment having the same name
ai the problem i s o v e r r k l d e n in this c a i e .
A n indexed collection o f environments may be declared in an e n v i r o n statement by
placing an A M P I . indexing expressk>n after the environment name. T h e name is then
"subscriptcd' * in the usual way t o r e f e r t o individual environments.
N a m e d environments handle changes in the same way ai named problems. I f an
o p t i o n ' * value ii changed while some particular environment is current the new value is
recordcd and is the value that will be rcinstated whenever that environment is made cur-
rent again.

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

M i x l c l s o f nctworks have appeared in several chapter s. notably in the transponation


p f o b l c m s in Chapter 3. W e n o w return t o the f o r m u h t i o n o f these models, and A M P L ' s
features for handling them.
Figure 15-1 shows the son o f diagram e o m m o n l y used to describe a network problem.
A cirele representa a /t/Ale o f the network, and an arrow denotes an are running from one
node t o another. A flow o f some kind travek from node t o node along the ares. in the
directions o f the arrows.
A n e n d l e s s variety o f models involve optimi/ation over such nctworks. Many cannot
be expressed in any straightfonvard algebraic w a y or are very diflicult t o solve. Our dis-
cussion starts with a particular class o f network optimi/ation nuxlels in which the d e c i -
sion variables represent the amounts o f f l o w on the ares. and the constraints are limited t o
t w o kinds: simple bounds on the flows. and conservation o f flow at the nodes. Models
restricted in thts w a y g i v e rise t o the problems known as network linear programs. T h e y
are especially easy t o describe and solve, yet are widely applicable. S o m e o f their bene-
flts exiend t o certain generali/ations o f the network flow form, which w e a b o touch upon.
W e begin with minimum-cost transshipment nuxlels, which are the brgest and most
intuhive source o f network linear programs, and then proceod to other wvll-known cases:
maximum flow, shortest path, transponation and assignment models. Examples are ini-
tially given in terms o f standard A M P L variables and oonstraints, defined in v a r and
s u b j e c t t o decbrations. In later sections, w e intnxluce n e d e and a r e decbrations
that per mi t models t o bedescribed m o r e d i r e c t l y in terms o f their network structure. T h e
lavt section discusscs formubting network n u x l c k s o that the resuhing linear programs
can be solved m o â efl iciently.

15.1 Minimum-cost transshipment m o d e l s


A s a concrete example, imagine that the n o d e s a n d ares in Figure 15-1 represent cities
and intercity transponation links. A manufacturing plant at the city marked PITT will

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.

A general transshipment model

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

Corresponding t o each city lhere is potcntially a supply o f packagcs and a demand f o r


packagcs:

param s u p p l y (C1T1KS} >= 0:


param dcmarxi (C1T1KS} >= 0:

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:

var Ship (<i.j) in LINKS} >= 0. <= c a p a c i t y l i . j 1 :

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:

Because the expression

sum ( < i j k ) in LINKS} Shipli.kl

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 ) :

param s u p p l y {ClTIKS} >=0; i amounts a v a i l a b l e a L c i t i e s


p a r a m demand (ClTIKS} >=0; i a m o u n t s r e q u i r o d aL c i t i e s

check: sum (i in ClTIKS} supply[i] = sum (j in ClTIKS} dcmandljj :

p a r a m c o s L ( L I N K S } >= 0 : 4 shipmcnL cosLs/1000 p a c k a ç e s


param c a p a c i L y ( L I N K S } >= 0: i max p a c k a g e s LhaL c a n b e s h i p p e d

var Ship (<i.j) in LINKS} >= 0. <= c a p a c i L y l i . j | :


4 p a c k a ç e s Lo b e s h i p p e d

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;

F i g u r e 15-2a: General transshipment nuxlel ( n e t l . r > c d ) .

set ClTIKS : = PITT ?JK SK BDS EWR BWI A T L MCO :

scL LINKS := ( P I T T , NE) < P I T T . S K )


( N K . B D S ) (NK.KWR) (NK.BWl)
(SK.BWR) (SK.BMX) (SK, A T L ) <SK.ML*0J:

param s u p p l y deíaulL 0 := PITT 4S0 :

p a r a m demand deíaulL 0 :=
BDS 90. BMR 1 2 0 . BWI 1 2 0 . ATL 70. M20 S0:

param: cosL capaciLy : =


P I T T NK 2 .S 2 S0
P I T T SK 3.S 2 S0

NK BOS 1.7 100


NK KWR 0.7 100
NK BWI 1.3 100

SK K WR 1.3 100
SK BWI o.e 100
SK ATL 0.2 100
SK MCO 2.1 100

F i g u r e 15-2b: Daia for general transshipment nuxlel ( n e t l . d a t ) .

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

Specialized transshipment models

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 ;

With the dcclaratk>ns organi/cd in this w a y , it is impossible t o s p e e i f y inappropriatc


kinds o f links, such a* ones betwxren t w o warehouses or from a warehouse back t o the
plant.
O n e parameter represents the supply at the plant, and a collection o f dcmand parame-
ters is indexed o v e r the warehouses:

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:

SOL C l T l I i S = ( p _ c i L y } union D_CITY union W_CITY;


soL LIWXS = < ( p _ c i L y > c r o s s D_ClTYJ u n i o n DW_LINKS;

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 ) ;

p a r a m p _ s u p p l y > = 0: * amount a v a i l a b l e a t plant


p a r a m w demand ( W _ C l T Y } >=0: 4 amounts r e q u i r e d a t warehouses

check: p_supply = sum ( k in W_ClTY} w demand [ k l ;

set ClTlIíS = ( p _ c i t y } union D_CITY union W_CITY;


set LINKS = < ( p _ c i t y } cross D_CITYJ u n i o n DW_LINXS;

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;

i ii Remainder same a s g e n e r a l transshipnent model iii

param c o s L ( L I N K S } > = 0 ; 4 shiomenL costs/1000 p a c k a g e s


p a r a m c a p a c i t y ( L I N K S } >= 0: i max p a c k a g e s t h a t c a n b e s h i p p e d

var Ship (<i.jj in LINKS} >= 0. <= c a p a c i t y [ i , j ] ;


i p a c k a g e s t o be s h i p p e d

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;

F i g u r e 15-3a: Specialized transshipmcnt m o d e l ( n e t 2 . m o d ) .

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 ;

var PD_Ship ( i in D_CITY} > = 0 . <= p d _ c a p l i l :


var DW_Ship ( < i . j ) i n DW_LINKS} >= 0. <= d w _ c a p [ i . j l ;

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 :

sot DW_L1NKS := (ÍJIÍ.BOS) (NB.HMR) ( N B . BWI)


(SB.KWR) (SB.BM1) (SE.ATL) (SH.MCOJ:
param p _ s u p p l y := 450 :

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

BOS 1.7 100


NB BWR 0.7 100
NB BWI 1.3 100
SIÍ ISWR 1.3 100
SIÍ BWI 0.8 100
SIÍ ATL 0.2 100
SIÍ MCO 2.1 100 ;

F i g u r e 15-3b: Data for specialized transshipment mixlel ( n e t 2 . d a t ) .

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:

subjocL Lo P _ B a l : sum (i in I>_C1TY} PD_Shiplil = p supply:

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:

T h e whole nnxlel. with appropriate data, is shown in Figures 15-4aand 15-4b.


T h e approaches shown in Figures 15-3 and 15-4 are eqüivalem, in thesense that they
cause the same linear program t o be solved. T h e former is more convenient for experi-
menting with different network stmetures. since any changes affect only the data for the
initial declaraiions in the nnxlel. If the network stmeture is unlikely t o c h a n g e , howxrver.
326 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15

Mt D_CITY:
ML W_ClTY:
ML DW_LINKS w i t h I n (D_CLTY c r o s s W_CITYJ ;

param p _ s u p p l y >=0: 4 amaunL a v a i l a b l e a L planL


p a r a m w demarxi {WjClTY} >= 0: 4 amaunls r e q u i r e d aL warehouses

chock: p_supply = sum (j in WjClTY} w demand [ j ] •

param p d _ c o s L {ELCITY} > = 0 : 4 shipmcnL cosLs/1000 packaços


param dw_cosL IDW_L1NXS} >= 0 ;

p a r a m pd_ c a p ( D _ C I T Y } >= 0 : 4 max p a c k a g e s LhaL c a n b o shippod


p a r a m dw_ c a p ( D W _ L I N K S } >= 0:

var PD_Ship ( i i n I > _ C I T Y } > = 0. <= p d _ c a p [ i j ;


var DW_Ship ( < i . j ) i n DW_L1NXS} >= 0. < = dw c a p l i . j ] :
4 packagos Lo be shippod

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 ;

subjocL to P Bal: sum ( i in D_C1TY} PD_Shiplil = p_supply:

subjocL t o D Bal ( i in D_CiTY}:


P D _ S h i p l i ] = sum ( ( i , j J i n DW_LIHKS} DMjShip ( i . j ) ;

subjocL t o W_Bai ( j in W_CiTY}:


«um ( < i . j ) i n DWJLINKS} D W j S h i p ( i , j | = w dcmandlj];

F i g u r e 15-4a: Speciali/cd transshipmcnt model, v e r s i o n 2 < n e t 3 . r » c d ) .

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.

Variations on transshipment models

S o m e balance constraints in a network flow nnxlel m a y have t o be inequalities rather


than equations. In the example o f Figure 15-4, if pnxluction at the plant can sometimes
excced total demand at the warehouses, should r e p b c e = by < = in the P _ B a l c o n -
straints.
A more substantial modification occurs when the quantity o f f l o w that c o m e s out o f
an are does not necessarily cqual the quantity that went in. A s an example, a small frac-
tion o f the packages shipped from the plant may be damaged or stolen before the pack-
ages reach the dtvtribuiion center. Suppcxse that a parameter p d _ l o s s is introduced t o
represem the loas rate:

param p d ^ l o s s (D_ClTY} >= 0 . < 1;

T h e n the balance constraints at the distribution centers must be adjusted accordingly:


SECT C N 15.1 M N W W C O S T TRATTS&<FVBVT WCC€LS 327

scL DL.CITY : = NB SH :

SOT W_CLTY := 1 » S BTFR BWI A T L MCO :

soL DW_L1NKS := (NK.BOS) (NH «HMR) (NK.BWI)


<SH.HWRJ <SB.BWI) (SB. ATL) <SH.MCOJ ;

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;

param: pd_cosL pcLcap :


?JH 2. S 2S0
SH 3.S 2S0 ;

param: dw_cost d*_cap :


NB BOS 1.7 100
NB HWR 0.7 100
NB BWI 1.3 100

SH HWR 1.3 100


SH BWI 0.8 100
SH ATL 0.2 100
SH MCO 2.1 100 ;

Figure 15-4b: Data for specializedtransshipmcnt model, version 2 ( n e t 3 . d a t ) .

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:

param o p c inLogcr > 0:

T h e n the dcmand constraints at the warehouses are aJjusted as f o l l o w s :

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 | :

T h e term { 1 0 0 0 / p p c } • E W _ S h i p t i , j ) represents the number o f canons received


at warchouse j when E W _ S h i p [ i , j ] thousand packages are shipped from distribution
center i .
328 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15

15.2 Other network m o d e l s


N o t ali network linear programs i n v o l v e the transpor tal ion o f things or the minimiza-
tion o f eosts. W e dcscribe here three wvíll-known ntxlcl classes — maximum ilow,
shortest path, and transponation&ssignmcnt — that use the same kinds o f variables and
constraints for ditTcrcm purposes.

Maximum flow models

In some network design applications the concern is t o send ai much f l o w as possiblc


through the network, rather than t o send i l o w at lo\v>?st cost. This altcrnative is readily
handled by dropping the balance constraints at the origins and destinations o f Ilow, whi te
substhuting an objeetive that stands f o r total flow in some sense.
A s a specific example. Figure 15-5 presents a diagram o f a simple trafTic network.
T h e m x k s and ares represem intersections and roads: capacitics, shown as numbers next
t o the roads, are in cars per hour. W e want t o f i n d the maximum trafTic f l o w that can
enter the network at u and leave at g .
A nnxlel f o r this situatk>n begins with a set o f intersections, and s y m b o l i c parameters
t o indicatc the intersections that serve as entrance and exit t o the road network:

set IWTKR:

param c n L r symbolic in IWTKR:


param e x i t symbolic in IWTKR, o cnlrj

T h e set o f roads ti defined as a subset o f the pairs o f intersections:

s e t ROADS w i t h i n (IWTKR d i £ f (cxit}J cross (IWTKR d i f f (entr}J:

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

s«t IWTKR; 4 inLcrsocLions


param c n t r symbDÜc in IWTKR; 4 c n L r a n c c L o r o a d noLv*ork
param o x i L symbDÜc in IWTKR. o cntr: 4 c x i L i r e m r o a d neLv»ork
set ROADS w i t h i n (IWTKR d i í í (exit}) cross (IWTKR d i £ £ (entr}J ;
param c a p (ROADS} > = 0 : 4 capacitics
v a r Tra££ ( ( i . j ) i n ROADS} >= 0. <= c a p l i . j l : 4 tra££ic loads
maximize K n L c r i n g _ T r a £ £: sum ((cnLr.jJ i n ROADS} Tra££ ( c n t r . j ] :
s u b j o c L t o B a l a n c e ( k i n IWTKR d i £ £ ( c n t r . e x i t } } :
sum ( ( i . k j i n ROADS} T r a £ £ ( i . k | = s u n ( ( k . j j i n ROADS} Tra££(k.j|:

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 ;

F i g u r e 1 5 4 : M a x i m u m tralYic f l o w nnxlel and data ( n e t r w i x . r > c d ) .

param c a p (ROADS} >= 0 ;


var T r a í í ( < i . j J i n ROADS} >= 0. <= capli.jl:

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 :

W e could equally w e l l m a x i m i z e the total flow into the e x i t T h e entire n n x l e l along


with data for the e x a m p l e shown in Figure 15-5, is presenkrd in Figure 15-6. Any linear
programming solver will find a maximum f b w o f I 3 0 c a r s per hour.

Shortest path models

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:

param Lime (EOADS} > = 0 : rt Limes Lo L r a v e l r o a d s


v a r U s e ( < i . j ) i n ROADS} >= 0: it 1 i f f < i . j j i n sborLesL paLh

m i n i m i z e T o L a l _ T i me: sum (<i.j) in ROADS} Limeli.jl *Use[i.j|:

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:

subjecL Lo S L a r t : sum ((enLr. jj in ROADS} UselenLr. jl = 1;

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 :

a m p l : isodol nat ahort .mod;


ampl: aolvo;
M1NQS S . S : o p L i m a l s o l u L i o n í o u n d .
1 i L e r a L i o n s , o b j e c L i v e 140

a m p l : option arzit zaro roxra 1;


a m p l : diaplay Uao;
Use : =
a b 1
b e 1
e g 1

T h e shortest path is ã b e çj, which takes M O minutes.

Transportation and assignment modeis

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 l.vriíR: 4 inLe rs ecLions

param e n L r symbolic in IWTKR: * e n L r a n c e Lo r o a d n e L w o r k


param e x i L .symbolic in IWTKR. o enLr; * e x i L írom road neLwork
seL ROADS w i L h i n < IWTKR d i £ £ (exiL}) cross (IWTKR d i £ £ (cnLr}J:
param L i m e (ROADS} > = 0 : 4 Limes Lo L r a v e l r o a d s
v a r U s e ( ( i . j ) i n ROADS} >=0: d 1 ií£ ( i . j ) i n shorLesL paLh
minimize T o La 1_. T i m e : sum ((i.jj in ROADS} L i m e [ i . j l * Use[i. j]:

subjecL Lo S L a r L : sum ((enLr.j) in ROADS} Use(enLr.jJ = 1;


s u b j e c L Lo B a l a n c e ( k i n IWTKR d i £ f ( e n L r . e x i L } } :
sum ( ( i . k j i n ROADS} U s e l i . k ) = sum ( ( k . j j i n ROADS} Use(k.jj:
daLa:

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 ;

F f e u r c 15-7: Shortest path nnxlel and data ( n e t s h o r t . r > c d ) .

T h e minimum-cost transshipmcnt nnxlel on this network is known as the transporta-


tion nnxlel. T h e special case in which every origin ti conncctod t o e v e r y destination was
inuoduced in Chapter 3: an A M P L nxxlel and sample data are s h o w n in Figures 3 - I a and
3 - l b . A more general example analogous t o the models developed earlier in this chapter.
where a set L I N K S speeifies the ares o f the network, appears in Figures 6 - 2 a a n d 6-2b.
Every path from an origin t o a destination in a bipanhe network consists o f one are.
O r , ti> say the same thing another w a y . the optimal flow ak>ng an are o f the transportation
nnxlel g i v e s t h e actual amount shipped from some orjgin t o s o m e destination. This prop-
erty permits the transportation nnxlel *> be v i e w e d alternatively a s a s o - c a l l c d assignmcnt
nnxlel, in which the optimal i l o w along an are is the amount o f something from the origin
that is assigned t o the dcstinatk>n. T h e meaning o f assignmcnt in this contcxt can be
brcadly construcd, and in particular need not i n v o l v e a shipment in any sense.
O n e o f the more c o m m o n applications o f the assignmcnt nnxlel is matching people t o
appropriate targets, such as j o b s , olTices or even other people. fcach origin mxle is associ-
ated with one person, and each destination nixle with one o f the targets — for example.
with one project. T h e sets might then be defined ai f o l l o w s :

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-8: Bipartite network.

T h e set A B I L I T I E S takes the role o f L I N K S in our carlier models: a pair U . j > is


placcd in this set if and only if person i can work on project j .
A s one possibility for continuing the nnxlel. the supply at node i could be the number
o f hours that person i is available k> work, and the demand at node j c o u l d be the num-
ber o f hours rcquircd for project j . Variables A s s i g n [ i . j 1 would represent the num-
ber o f hours o f person i ' s time ass^gned t o project j . A l s o associatcd with each pair
{ i , j J would be a cost per hour, and a maximum number o f hours that person i could
contribute t o j o b j . T h e resulting ntxlcl is shown in Figure 15-9.
Another possibility is t o make the assignment in ter nu o f people rather than hours.
T h e supply at every node i is I < person), and the demand at node j is the number o f peo-
ple required for project j . T h e supply constraints ensure that A s s i g n f i , j ) is not
greater than I : and it w i l l equal I in an optimal solution if and only if person i is
assigned t o project j . T h e coelllcient c o s t [ i . j 1 could be s o m e kind o f cost o f assign-
ing person i t o project j , in which case the o b j e c t i v e would still be t o minimize total
cost. Or t h e c o e f f i c i e n t could be the ranking o f person i for project j , perhapson a scale
f r o m I (highest) t o 10 (low\*st). T h e n the nxxlel woukl produce anassignment for which
the k>tal o f t h e rankings is the best possible.
Finally, can imagine an assignment ntxlcl in which the demand at each mxle j is
also 1 : the problem is then t o match fxropk* t o projo?&. In the o b j * x t i v e , c o s t t i . j 1
could be the number o f hours that person i would need t o complete project j , in which
case the nnxlel would find the assignment that minimizes the total hours o f work needed
t o f i n i s h a l l the projccts. Y o u can crcatc a nnxlel o f this kind by replacing ali references
SECT C N 15.3 C€<XARN3 NFTY/OFK WOC&S BV«OTOCAND 333

SOT FDD PL li:


set PROJKCTS;
seL ABILITIKS within (PKOPLK c r o s s PROJWLTSJ :
param s u p p l y ( FDD PL K } >= 0 : i hours each person i s a v a i l a b l e
p a r a m demand ( P R O J K C T S } >= 0: i hours each p r o j o c t r o q u i r t s
check: sum ( i in PKOPLK} supplyli) = sum ( j in PROJKCTS} demandljj:
param c o s L (ABILITIKS} >= 0: 4 cosL per hour o£ work
param l i m i t (ABILITIKS} >=0: i maximum c o n L r i b u L i o n s Lo projcxrLs
var Assign (<i.j) in ABILITIKS} >= 0. <= limiL(i.j|:
minimize ToLal_CosL:
sum ( ( i • j J i n A B I L I T I K S } cosL(i.jj * Assignli.jl:
s u b j e c L L o S u p p l y ( i i n PWDPLK}:
sum ( ( i • j J i n A B I L I T I K S } A s s i g n ( i . j l = supplylij:
s u b j e c L L o Demand ( j i n P R O J K C T S } :
sum ( ( i . j J i n A B I L I T I K S } A s s i g n ( i . j l = demandljj:

F i g u r e 15-9: Assignmcntmodel(netâsgn.mod).

to s u p p l y l i ] and d e m a n d ( j ] by I in Figure 15-9. Objeetive coefficients represent-


ing rankings are an option f o r this nnxlel ai wvll, giving rise t o the kind o f assignment
nnxlel that w e used ai an example in Section 3 J .

15.3 Declaring network models by n o d e and a r e


A M P I . ' s algebraic notation hai great p o w e r t o expressa variety o f network linear pro-
grams. but the resulting constraint expressk>ns are often not as natural as w e w o u l d like.
\Vhile the idea o f constraining 4 ' f l o w out minus flow i n ' ' at each node i s e a s y t o describe
and understand. the corrcsponding algebraic constraints tend *> involve terms like

sum ( < i j k ) in LINKS} Shipli.kl

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

T h e networic extcnsions t o A M P l . include t w o new kinds o f deebration, n c d e and


a r e , thai take the place o f the s u b j e c t t c and v a r declarations in an algebraic c o n -
straint formulation. T h e n c d e decbrations nanie the nodes o f a netwx>rk, and character-
ize the flow halance constraints at the nodes. T h e a r e declarations nanie and define the
ares. by s p e c i f y i n g the nodes that ares connect, and by provkling optional informaiion
such ai bounds and costs that are associated with ares.
This section introduces n c d e and a r e by showing h o w they permit various examples
f r o m earlier in this chapter t o be reformubted conveniently. T h e f o l l o w i n g section pre-
sents the m i e s for these declaratk>ns more sysiematically.

A general transshipment model

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:

node Balance (k i n C1T1IÍS}: neL_in = dcmandlkl - supply [ k ] ;

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

sum ( < i j k ) in LINKS} Sbipli.kl - sum (<k.jj in LINKS} Shiplk.jl

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:

a r e S b i p ( < i . j ) i n LINKS} 0 . <= c a p a c i t y l i . j 1 .


i r e m B a l a n c e l i 1. Lo B a l a n c e l j l . o b j T o L a l _ C o s L c o s L l i . j l :

A n are S h i p t i , j j is defined for each pair in LINKS, with bounds o f 0 and


c a p a c i t y [ i , j 1 on its flow: t o this extent, the a r e and v a r declarations are the
same. T h e a r e declaration cx>ntains additk>nal phrases, however, t o say that the are runs
from the node named B a l a n c e t i ) t o the node named B a l a n c e ( j ) , with a linear
coelTicicnt o f cost li. j ] in the o b j e c t i v e funetion named T o t a l _ C o s t . These
phrases use the keywocds f r o m , t c , and c b j .
Since the informaiion about the o b j e c t i v e funetion is included in the a r e declaration,
it is not needed in the m i n i m i z e deebration, which reduces to:

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:

param s u p p l y (C1T1BS} >= 0 : 4 amounLs a v a i l a b l e aL c i t i e s


p a r a m dcmand (C1T1BS} >=0: 4 amounLs r e q u i r e d aL c i L i e s

checrk: sum (i in CIT1KS} «upply[i| = sum (j in CITIES} dcc\ar>d l j | :

p a r a m c o s L ( L I N K S } >= 0 : 4 shipmcnt cosLs/1000 packages


param c a p a c i L y {LINKS} > = 0 : 4 max p a c k a g e s LhaL c a n b e s h i p p e d

minimize Total_Cost;

node Balance (k i n C1T1KS}: n«t_in = demandlk) - supply [ k ] ;

are S h i p ( < i . j j i n L I N K S } > = 0. <= c a p a c i L y l i . j ] .


i r e m B a l a n c e [ i l . Lo B a l a r x r e [ j | . o b j T o L a l _ C o s L costli.jl:

F i g u r e 15-10: General transshipmcntmodel with n e d e and a r e <netlncde.r>cd).

T h e w h o l e nnxlel is shown in Figure 15-10.


A s this dcscriptk>n suggests, a r e and n e d e take the place o f v a r and a u b j e c t to,
respeetively. In fact A M P L treatsan a r e declaration ai a definition o f variables. s o that
you would still say d i s p l a y S h i p t o look at the optimal flows in the network nnxlel o f
Figure 15-10; h treatsa n e d e declaration ai a definition o f constraints. T h e dilYerence is
that n e d e and a r e present the nnxlel in a way that corrcsponds more directly k» its
appearance in a network diagram. T h e description o f the mxles always c o m e s first, f o l -
lowxxl by a description o f h o w the ares connect the nodes.

A specialized transshipment model

T h e n e d e and a r e declarations make it e a i y t o define a linear program for a networic


that has several ditTerent kinds o f nodes and ares. For an example w e return t o the spe-
cialized model o f Figure 15-4a.
T h e network hai a p b m node. a distribution center node for each member of
D _ C I T Y , and a warehouse node for each member o f W _ C I T Y . Thus the nnxlel requires
three node declarations:

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;

T h e balance conditions say that f l o w out o f node P l a n L must be p _ s u p p l y , while flow


into node W h s e [ j ] is w _ d e r i a n d [ j 1. ( T h e network has n o ares into the plant or out
o f the warehouses. s o n e t _ o u t and n e t _ i n are just the flow out and flow in, respee-
tively.) T h e conditk>ns at node D i s t ( i ) could be written either n e t _ i n = 0 or
n e t _ o u t = 0, but since these are assumed by default need not s p e c i f y any condhion
at ali.
336 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15

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 :

param p _ s u p p l y >= 0: 4 amaunt a v a i l a b l o aL planL


p a r a m w demand (WjClTY} >=0; 4 anwunls roguircxi aL warehouses
check: p_supply = sum ( j in W_ClTY} w dcmandljl:

p a r a m pd__cosL ( D j C l T Y } > = 0: 4 shipnenL cosLs/1000 packages


param d * _ c o s L (DW_LI?JXS} > = 0 :
p a r a m pd__cap ( D _ C I T Y } > = 0 : 4 max p a c k a g e s Lhat can b e shipped
p a r a m d * _ c a p ( D W _ L I M K S } >= 0 :
minimize ToLal_CosL:

node PlanL: noL_ouL = p_supply:


node DisL (i in D_C 1 T Y > :

n o d e Whse (j in W_ClTY}: noL_in = w_ demand l j | :


are PD_Ship ( i i n D _ C l T Y > >= 0. <= p d c a p l i j .
£rom P l a n L . Lo D i s t ( i J . o b j Total_CosL pd_cost [ i j ;
are DW_Ship ( < i . j j i n D W _ L I * K S } >= 0 . < = d * _ c a p l i . j l .
£ r o m D i s L [ i J. Lo W h s e l j j . o b j T o L a l _ C o s L d * _ c o s t l i . j ] :

F i g u r e 15-11: Speciali/ed transshipment mixlel with n o d e and a r e < n e t 3 n c d e . r > c d ) .

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:

a r e PD_Ship ( i in D _ C I T Y } > = 0 . <= p d _ c a p l i j .


íron Plant. to D i s t l i l . obj ToLal_CosL p d _ o o s t [ i l ;

And there is an are from distribution center i to warehouse j for each pair { i , j > in
DW.LINKS:

a r e D W _ S h i p ( < i . j ) i n D W _ L I N K S } >= 0. <= d w _ c a p [ i . j j .


í r o n Di sL l i | . Lo W h s e l j j . o b j T o t a l _ C o s t d w _ c o s L l i . j |:

T h e a r e declaraiions s p e c i f y the relevant bounds and objective coeHlcienti. ai in our


previous example. T h e whole nnxlel ti shown in Figure 15-11.

Variations on transshipment models

T h e balance conditk>ns in n o d e declarations may be inequalities. like ordinary alge-


braic balance oonstraints. I f productk>n at the plant can sometimes exceed total demand
at the warehouses, it would be appropriate t o g i v e the condition in the declaration o f node
P l a n t ai n e t _ o u t < = p _ s u p p l y .
A n a r e declaration can s p e c i f y losses in transit by adding a factor at the end o f the
t o phraie:
SECT C N 15.3 C€<XARN3 NFTY/OFK WOC&S BV «OTOC AND 337

a r e FD_Ship ( i in D_ClTY} 0 . <= p d _ c a p [ i | .


írccn P l a n t . t o D i a t l i ) 1 - p d _ l o s s l i |.
obj Total_Cost p d _ c o s t [ i J;

This is interpreted a* saying thai ? D _ S h i p [ i ] is the number o f packagcs that leave


node P l a n t , but { l - p d _ l o s s [ i l > * P D _ S h i p [ i ) is the number that enter node
Dist[i).
T h e same option can be used to s p e e i f y conversions. T o use our previous example. if
shipments are measured in thousands o f packagcs but demands are measured in cartons.
the ares from distribution centers t o warehouses should be dcclarcd as:

a r e DW_Ship ( < i . j ) i n L I N K S } >= 0. <= d w _ c a p [ i . jj.


frccn D i e t l i j . t o W h s e l j | < 1 0 0 0 , ' p p c j ,
o b j T o t a l _Co s t d / i _ c o s t l i . j | ;

If the shipments to warehouses are a l s o m c a v u r c d in cartons. the facto* should be applicd


at the distribution center:

a r e D W _ S h i p ( < i . j ) i n D W _ L I N K S } >= 0. <= d w _ c a p [ i . jj.


írccn D i s t l i J (ppc/lOOOj. to W h s e l j l .
o b j T o t a l _Co s t d / i _ c o s t l i . j | ;

A k>ss factor could a b o be applicd to the t o phrase in these examples.

Maximum flow models


In the diagram o f Figure 15-5 that w e have used t o illustrate the maximum fk>w prob-
lem, there are three kinds o f intersectk>ns representcd by nodes: the one where tralYic
enters, the one where traffic leaves, and the others where trafllc f l o w is conserved. Thus
a nnxlel o f the network could have three corresponding node declarations:

node lintr_Int: n o t _ o u t >= 0 :


node lixit_lnt: n o t _ i n >= 0:

node In t e r s e c t i o n (k in IWTKR d i f f (entr . e x i t } } :

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:

are Traíf ( < i . j ) i n ROADS} >= 0. <= e a p l i . j l . it NOT R1GI1T


frccn I n t e r s e e L i o n l i | . t o I n t e r s e c t i o n l j j .
o b j Kntering_Tra£f <if i = e n t r then l j ;

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:

a r e T r a í í ( < i . j J i n KOADS} >= 0. <= c a p li.jl. * 5VNTAX ERROR


írccn < i £ i = o n L r L h c n E n L r _ I n L e l s e i n L e r s o c L i o n ( x 1 J.
to < i £ j = e x i t Lhcn E x i t _ I n L c i s o i n L o r s o c L i o n l j J J.
o b j E n t e r i n g _ T r a í £ <i£ i = c n L r L h c n lj ;

H o w ver, the i f - t h e n - e l s e construct in A M P L does not apply t o nnxlel componente


such av E n t r _ I n t and I n t e r s e c t i o n [ i ] : this version will be f c j c c t e d as a syntax
error. Instcad you need t o use f r o m and t o phrascs qualifkrd by indexing expressions:

a r e T r a í í ( < i . j J i n KOADS} >= 0. <= c a p l i . j l .


írccn ( i £ i = e n t r } EnLr_lnL.
írccn ( i í i < > c n L r } I n L e r s o c L i o n l i |.
Lo (ií j = exit} ExiL_InL.
Lo (ií j exiL} InLcrsecLion lj | .
o b j E n L e r i n g J T r a í í < i í i = c n L r Lhcn l j ;

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) :

T h e nodes that were formcrly declared as E n t r _ I n t and E x i t _ I n t are n o w just


I n t e r s e c t i o n [ e n t r J and I n t e r s e c t i o n [ e x i t ] , and conscqucntly the are dec-
laration that w e previously marked " n o t r i g h t " n o w w o r k s j u s t fine. T h e c h o i c e betwven
this version and the previous one is entirely a matter o f convenience and taste.
( I n f i n i t y i s a predefined A M P L parameter that may be used t o specify any " i n f í n i t e l y
l a r g e " bound: its technical definition is g i v e n in Section A . 7 2 . )
Arguably the A M P L formulation that is most convenient and appealing is nehher o f
the above, but rather c o m e s from interpreting the network diagram o f Figure 15-5 in a
sljghtly different w a y . Suppose that w e v i e w the arrows into the entrance node and out o f
the exh node as representing additional ares. which happen to be adjacent t o only one
node rather than t w o . Then flow in cquak flow out at every inter section, and the node
declaration simplifies to:

node InLcrsecLion (k in INTER} :


SECT C N 15.3 C € < X A R N 3 N F T Y / O F K W O C & S BV«OTOCAND 339

scL IOTBR: A inLc rs ecLions

param c n L r symbolic in 1NTKR: * entranço to road network


param c x i L symbolic in 1NTKR. o cnLr; * c x i t írom road ncLwork

set ROADS w i t h i n < 1WTKR d i f £ (cxiL}) cross (IWTBR d i £ £ (cntr}J:

param c a p (ROADS} >= 0: 4 capaciLics oí roads

ixxie Int c r soe t i o n (k in IWTBR} :

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 ] :

are T r a £ £ ( < i . j ) i n ROADS} > = 0. <= c a p l i . j l .


£r«n Intersection (i] . to Intersection l j ] :

maximize KnLcring_Tra££: Tra££_In:

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 ;

F i g u r e 15-12: M a x i m u m f l o w nuxlel with n e d e and a r e ( n e t r « x 3 . r » c d ) .

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:

a r e T r a £ £ ( < i . j J i n ROADS} >= 0. <= c a p l i . j l .


í r o n i n t c r s e c L i o n [ i 1. Lo I n L c r s e c L i o n l j 1:

W h e n the nuxlel is represented in this way, the o b j e c t i v e is t o m a x i m i z e T r a f f _ I n ( o r


equivakrntly T r a f £ _ O u t ) . W e could d o this by adding an o b j phrase t o the a r e dcc-
laration f o r T r a £ £ _ X n , but in this case it is perhaps clearer t o d e f i n e the o b j e c t i v e alge-
braically:

maximize BnLcring_Tra££: Traff_In:

This version is shown i n f u D in Figure 15-12.


340 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15

15.4 Rules for node and a r e declarations


l l a v i n g defino d n e d e and a r e by example, w e n o w describe more comprehensively
lhe required and opiional elements o f these declarations, and comment on their intcrac-
tion with the conventional declarations m i n i m i z e or m a x i m i z e , s u b j e c t t o , and
v a r when both kinds appcar in the same nnxlel.

node declarations

A n e d e declaration begins with the key word n e d e . a name, an opiional indexing


expression, and a colon. T h e expressk>n f o l l o w i n g the colou, which describes the balance
condition at the node, may have any o f the f o l l o w i n g for ms:

nti -txpr = ariih-txpr


nti -txpr <= ariih-txpr
nti -txpr >= ariih-txpr

ariíh • txpr = nti - txpr


ariih-txpr <= nti-txpr
ariih-txpr >= nti-txpr

ariih-txpr <= nti-txpr <= ariih'txpr


ariih-txpr >= nti-txpr > = a riih txpr

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

An a r e declaration consists o f the key w o r d a r e , a name, an opiional indexing


expression, and a series o f opiional qualifying phrases. Each are creates a variable in the
resuhing linear program, w h o s e value is the amount o f flow o v e r the are: the are name
may be used k> refer t o \ht% variable elsewhere. A l i o f the phrases that m a y appcar in a
v a r defini tion have the same significancvr i n a n a r e defini tion: most commonly, the > =
SECT O N 15 4 RULES F O R UttZ H4D XTC C € O J * V « T O M S 341

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.

Interaction with objeetive declarations

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 :

Figure 15-13: M u k i o o m m o d i t y flow w i t h s i d e o o o s U a i M s ( n e t m u l t i . r » c d ) .

Interaction with constraint declarations

T h e componente defined in a r e declaratk>ns may be used ai variables in additional


subject t c declarations. T h e latter represem " s k l e constraints" that are imposed in
addition t o balance o f f b w at the nodes.
A s an example. consider h o w a mukioommodity flow problem can be built f r o m the
node-and-are network formulation in Figure 15-10. F o l l o w i n g the approach in Section
4.1, introduce a set PRODS o f diflerent produets. and add it k> the indexing o f ali
parameters. mxlcs and ares. T h e result is a separa te network linear program for each
product. with the o b j e c t i v e funetion being the sum o f the costs f o r ali produets. T o lie
these networks together, \v>í provide f o r a j o i n t limit on the total shipmentv ak>ng any
link:

param c a p _ j o i n L (LINKS} >= 0:

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.

Interaction with variable declarations

Just av an a r e variable may be used in a s u b j e c t t c declaration. an ordinary v a r


variable may be used in a n c d e declaration. That is. the balance condition in a n c d e
SECTCN 15.5 SOArNGNETY/CFKLNE/tfFTOGRAVS 343

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 ;

W e imagine that at city k, in addition t o the ami>unts s u p p l y ( p . k ] o f produets avail-


able t o be shipped, up t o l i m i t t £ . k ] o f fccdsfcxrk £ can be converted into produets;
one unit o f fcedstock £ g i v e * rise t o y i e l d l p , £ ] units o f e a c h product p . A variable
F e e d [ £ . k ] represents the ami>unt o f feedstock £ used at city k:

var Feed (£ in 1'BBDS. k in C1T1KS} >= 0. <= limit(£.kj:

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.

15.5 S o l v i n g network linear p r o g r a m s


A l i o f the models that w e have described in this chapter g i v e rtse t o linear programs
that have a " n e t w o r k " property o f s o m e kind. A M P I . can send these linear programs t o
an L P solver and retrieve the optimal values, much as for any other class o f L I V If you
use A M P I . in this w a y , the network strueture is helpful mainly as a g u i d e t o formulating
the mixlel and interpreting the rcsuhs.
M a n y o f the m o d e k that w e have described belong ai w e l l t o a more restricted class
o f probtems that ( c o n f u s i n g l y ) are also known ai " n e t w o r k linear p r o g r a m s . " In model-
ing terms, the variables o f a network L P must represem flows on the ares o f a network,
and the constraints must be only o f t w o types: bounds on the flows along the ares, and
limits on f l o w out minus flow in at the nodes. A more technical w a y t o say the same
thing is that each variable o f a network linear program must appear in at most t w o c o n -
straints (aside from \ o w a or upper bounds on the variables), such that the variable has a
c o e f l i c i c n t o f + 1 in at most one constraint. and a c o e f l i c i c n t o f - I in at most one c o n -
straint.
' ' P u r ê ' ' network linear programs o f this restricted kind have some very strong proper-
tie» that make their use partLularly desirable. *So long as the supplies. demands. and
344 PCTVOFKLNEAFRFOGRAVS C H Í F T E R 15

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

p a r a m demand (PWDDS . C 1 T 1 K S } >= 0; 4 amounts required at cities


c h o c k ( p i n PRODS}:
sum ( i i n C 1 T 1 K S } supplylp.il = sum (j in ClTXKS} demand l p . j J :

p a r a m c o s t ( PRODS . L I N K S } >= 0 ; i shirxncnt c o s t s / 1 0 0 0 p a c k a g e s


p a r a m c a p a c i t y (PRODS. L I N K S } >= 0: 4 max p a c k a g e s s h i p p o d o í p r o d u c t
set KKKDS:

param y i e l d ( P R O D S . F K K D 3 } > = 0: i amounts d e r i v o d i r e m f e o d s t o c k s


param l i m i t (FKKDS, C 1 T 1 K S } >= 0: * feodstocks available a t c i t i e s
minimize Total_Cost:

var Food (£ in FKKDS, k i n C1T1KS} >= 0 . <= limitlf.kl:


n o d e B a l a n c e ( p i n PRODS. k i n C I T I E S } :
n e t _ o u t = s u p p l y l p . kl - d o m a n d l p . k 1
+ sum ( í i n PKKDS} y i e l d l p . i l * l ' e o d [ f . k | :

are S h i p ( p i n PRODS. < i . j ) i n L I N K S } > = 0 . <= c a p a c i t y l p . i . j 1 .


í rccn B a l a n c e l p . i J . t o B a l a n c e l p . j j ,
obj Total_Cost costlp.i.jj:

Figure 15-14: Multioommodity flow with side variables (netieeds .r>cd).

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:

a m p l : modol nat3.xaod; d a t a not3. dat; oolvo;


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 1819
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
SECT C N 15.5 SOArNGNETY/CFKLNE/tfFTOGRAVS 345

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:

a m p l : xsodol nat Jnoda .xsod


a m p l : data not3.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 o c t i v e 1819
N e t w o r k c x t r a c t o r í o u n d 7 n o d e s and 7 a r e s .
7 network simplex i t e r a t i o n s .
0 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

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:

node Supply (k in CITIES}: net_out = supply [kl;


node Demand (k in CITIES}: n e t _ i n = demand ( k l ;

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:

param s u p p l y (ClTlIiS} >= 0 : i amounLs a v a i l a b l e aL c i L i e s


p a r a m dcmand (ClTlIiS} >=0: i amounLs r e q u i r e d aL c i L i e s
chock: sum ( i in ClTlIiS} supplylij = sum ( j in C1T1KS} demandljl:
param c o s L (LINKS} >= 0 ; 4 shipmcnL c o s L s per Lon
param c i L y _ c a p ( C l T l I i S } >= 0: i max t h r o u g h p u L aL ciLies
param l i n k ^ c a p (LINKS} > = 0 : i max s h i p n e n L o v e r links

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:

are T h r o u g h ( k i n C l T l I i S } > = 0. <= ciLy_caplkl.


i r e m S u p p l y l k J . Lo D e m a n d l k J ;

Ffeure 15-15: T r a i m h i p f n e n t model with luxle c a p a c i t i e s ( n e t t h r u . i > o d ) .

are Ship ( < i . j ) i n L I N K S } >= 0. <= l i n k ^ c a p l i . j 1 .


irem Demarxilil, Lo S u p p l y l j l , o b j Total_CosL cost[i.jl:

T h e throughput at eity k b representei! by a n e w kind o f are, from S u p p l y [ k ] to


Deatandlk):

a r e T h r o u g h ( k i n c i L i e s } > = D. <= ciLy_cap(kl,


i r e m S u p p l y l k J , L o Dcmand ( k ] :

T h e throughput limit is n o w rcprcscntcd by an upper bound on this are'& f l o w , rather than


by a sitie constraint. and the network strueture o f the nxxlel is preserved. A complete list-
ing appears in Figure 15-15.
T h e preceding e x a m p l e exhibits an addhional advantage o f using the n e d e and a r e
declarations when d e v e l o p i n g a network nnxlel. if you use only n e d e and a r e in their
simple f o r m s — n o variables in the node conditions. and n o optional factors in the i r e s »
and t o phrases — your nnxlel isguaranteed t o g i v e rise only t o pure network linear pro-
grams By contrast if you use v a r and s u b j e c t t o . it is your rcsponsibilhy t o ensure
that the resulting linear program ha* thenecessary network stmeture.
S o m e o f the preceding c o m m c n t s can be extended t o " g e n e r ali/cd n e t w o r k " linear
programs in which each variable still figures in at most t w o constraints. but not necessar-
ily with coefTicients o f + 1 and - I . W e have seen examples o f generali/ed networks in the
cases where there is a loss o f f l o w or change o f units on the a r e s Gencralized network
L P s d o not necessarily have integer optimal solutions, but fast algorithms f o r them d o
exist. A solver that promises a " n e t w o r k ' * algorithm may or m a y not have an extension
t o gener ali a x I networks: chock the solver-specific documental ion before you make any
assumptions.
SECT CN 15.5 SCLV NG NETY/CFK L N E / « FTOGRAVS 347

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 .

1 5 - 4 . I x r each o f lhe falkiwirçg nelwork problems, construi a d i l a file lhal pemiits it l o be


s o h v d usmg lhe general Iranmhipmevit model o f Figure 15 2a.
( a ) The transp<rtalian problem o f Figua? 3 1 .
<b) The assignment problem o f Figure 3-2.
( c ) T h : m u i mum flow problem o f Figure 15 6 .
( d ) The shortestpaih problem o f Figure 15 7.

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

( a ) lomiuLUe on algebraic assignment m o d e l using v a r aixl s u b j e c t t o declmlkMK, for íhrs


psoblem.
<b) S o l w the amçnment problem f<* éic fo How mg table o f rankings:

A ED I Z G III 112 RH S C A ED E Z G III 112 RH S C


Alk-n 1 3 4 7 7 5 2 6 KncíT 7 4 1 2 2 5 6 3
Bbck 6 4 2 5 5 7 1 3 Manheim 4 7 2 1 1 3 6 5
Chung 6 2 3 1 1 7 5 4 Morris 7 5 4 6 6 3 1 2
Cbrk 7 6 1 2 2 3 5 4 Nalhin 4 7 5 6 6 3 1 2
Conners 7 6 1 3 3 4 5 2 Neuman 7 5 4 6 6 3 1 2
Cummirçg 6 7 4 2 2 3 5 1 Patrick 1 7 5 4 4 2 3 6
Devnming 2 5 4 6 6 1 3 7 Rol Km 6 2 3 1 1 7 5 4
Eng 4 7 2 1 1 6 3 5 Schuman 4 7 3 5 5 1 2 6
Tomier 7 6 5 2 2 1 3 4 Sflwr 4 7 3 1 1 2 5 6
Fores t 6 7 2 5 5 1 3 4 Stein 6 4 2 5 5 7 1 3
(ioodman 7 6 2 4 4 5 1 3 Stock 5 2 1 6 6 7 4 3
ILUTÍS 4 7 5 3 3 1 2 6 Truman 6 3 2 7 7 5 1 4
IKIHNES 6 7 4 2 2 3 5 1 Wobnan 6 7 4 2 2 3 5 1
Johnson 7 2 4 6 6 5 3 1 Young 1 3 4 7 7 6 2 5

I l o w many studenfe ore as signed second cff third chciice?

(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

"The student* who have c a n aie:

Churçg Eng Manheim Nalhin Rol li m


Demmirçg Ifobnes Morris Patrick Young

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?

( d ) Your formulatian in ( c ) can be viewed as a transp<»tation model with si de constraints. Hy


definirç; appropriale netwcrk nodes and * c s , reformula* it as a " p u r r " network flow m o d e l as
discussed in Section 15.5. Write lhe f<rmulilkin m A M P L using only n o d e ai*J a r e dcclirolkins
f<r the constraints and variables. Solve with the same dati as in (c),TO show thit the optimal value
isthe sime.

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

Euyít] dcuajfcfi&i^ta^t* ícr<lry r.


C i r r y TC] dcu^^ix^sollcafcu^J^it^c^Jcrfiiiy t
WAfi2l2 [ C ] taoJ aapàakt CD tf* áut a ira d l ) C
WAfl2l4 r t ] «-NCdajpiüs totfx* sfcr»» l i u i i ) jftcrdiY c
TK&flhft] di» t

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

Because the fundamental idea o f an optimi/ation problem i s t o minimize or maximize


a funetion o f the decision variables. subject t o constraints on them, A M P I . is oriented
toward explicit descriptions o f variables and constraints. This is w h y v a r dcvbrations
tend t o c o m e first, f o l b w c d by the m i n i m i z e or m a x i m i z e and s u b j e c t t o d c v b -
rations that use the variables. A w i d e variety o f optimi/ation problems can be formulated
with this approach, ai the examples in this book d e monstra te.
For ccrtain kinds o f linear programs, h o w e v e r , h can be preferable t o declare the
objective and constraints before the variables. Usually in these cases, there is a much
simpler pattern or interpretation t o the c o e f l i c i e n t s o f a single variable down ali the c o n -
straints than to the c o e f l i c i e n t s o f a single constraint across ali the variables. In the jar-
gon o f linear programming. h is easier t o d e s c r i » the matrix o f constraint coeíTicients
" c o l u m n w i s e " than " r o w - w i s e " . A s a result, the f o r m u b l i o o is simplified by first
declaring the constraints and objective, then listing the non/ero coeíTicients in the decla-
rations o f the variables.
O n e example o f this phenomenon is provided by the network linear programs
described in Chapter 15. Each variable hai at most t w o non/ero c o e f f i c i e n t s in the c o n -
straints, a + 1 and a - I . Rather than trying t o describe the constraints algebraically, you
may find it easier t o s p e c i f y , in each variable's declaration. the one or twoconstrainti that
the variable figures in. In fact, this is exactly what you d o by using the special n e d e and
are declarations introduccd by Scction 15.3. The n e d e declarations c o m e first t o
describe the naturc o f the constraints at the network nodes. T h e n the a r e dcvbrations
d e f i n e the network f l o w variables, using f r o m and t o phrases to locate their non/cro
c o c A i c i c n t s a m o n g the node constraints. This approach is panicularly appealing because
iteorresponds directly t o the way most people think about a network flow problem.
It would be impractical for AMPI. t o ofter special declarations and phrases for every
kind o f linear program that you might want t o declare by columns rather than by rows.
lnstead. aJditional options t o the v a r and s u b j e c t t o declarations permit any linear
program to be g i v e n a columnwise declaration. This chapter introduccs A M P L ' * column-
wise features through t w o contrasting examples — an input-output produetion m o d e l and

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.

16.1 A n input-output model


In simple maximum-profit produetion nuxlels such ai the examples in Chapter I, the
gcxxls pnxluced are distinet from the resources consumcd. so that over ali produetion is
limited in an obvious way by resources available. In a more realistic nxxlel o f a complex
operai ion such ai a steel mfll or refinery, however, pnxluct ion & carricd out at a serie» o f
units; av a rcsult, some o f a pnxluction u n i f s inputs may be the outputs from other unifc.
For this situai ion we nced a nuxlel that deals more generally with materiais that may be
inputs or outputs, and with producl ion activities that may involve several inputs and out-
puts each.
W e begin by developing an A M P l . formulation in the usual r o w - w s e (or constraint-
oriented) way. Then we cxpkiin the c o l u m n w k e ( o r variable-oriented) alternative, and
discuss refinements o f the nuxlel.

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};

If i o I i , j ) > 0, it is interpreted as the amount o f material i produced ( a s an output) by


a unit o f activity j . On the other hand. if i o [ i . j J < 0, it represents minus the amount
o f material i consumcd (as an input) by a unh o f activity j . For example. a value o f 10
represents 10 units o f i pnxlucvrd per u n i t o f j , while a vahie o f - 1 0 represents 10 units
consumcd per unit o f j . O f course. we can expect that for many combinations o f i and j
we will have i o [ i . j ) = O.signifying that material i does not figure in activity j atall.
T o see w h y we want to interpret i o [ i . j ] in this manner. suppose we define
Run [ j ] to be the levei at which we operate <mn) activity j :

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:

v a r Run (j i n ACF} > = a c L _ m i n l j l . <= acL maxl j | :

Then i o [ i . j ) * Run I j ) iü the total amount o f material i produccd < if i o [ i . j J > 0 )


or minus the amount o f material i consumcd < if i o ( i . j J < 0 ) by activity j . Summing
over ali activities. w e see that
SECT-ON 16.1 / N N P U T OI/TFUT w o c e . 355

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;

var Run ( j i n ACT} >= a c t _ m i n l j | . <= a c t max [ j ];


maximize ? J e t _ P r o f i t : sum ( j i n ACT} revenuelj] * Run( 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;

Ffcure 16-1: Input-output nnxlel by r o w s < i o r o w . rrxxl).

sum ( j i n ACT} ioli.jl * Runljl

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}:

maximize N e t _ P r o f i t : sum ( j in ACT} revenuelj 1 * Runljl:

The oompleted nnxlel & shown in Figure 16-1.

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:

v a r Run ( j i n A C F } > = a c L _ m i n l j | . <= acL m a x l j l ,


o b j MeL_ProfiL revenue l j I .
c o e f f ( i i n MAT} B a l a n c e l i l io(i,jli

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:

The keyword t o _ c o m e indicates where the terms i o [ i , j ) * R u n t j ] generated by


the v a r declaration are to be "added in.'' You can think o f t o _ c c : n e = 0 ai a template
for the constraint. which will be filie d out ai the coefficienfc are declared. N o template is
needed for the objective in this example, howxrver, since h is exclusively the sum o f the
ter mi r e v e n u e [ j J • Run [ j J. Templates may be written in a limited variety o f ways.
ai shown in Section I6.3 bek>w.
Because the c b j and c o e f f phraies refer k> K e t _ P r o £ i t and B a l a n c e , the v a r
declaration must come after the r ^ a x i m i z e and s u b j e c t t o declaratk>ns in the
columnwise formulation. T h e c o m p l e t e mixlel is shown in Figure 16-2.

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:

Figure 16-2: Columnwise f o r m u l a t i o n < i o c o l l . r > c d ) .


S E C T - O N 16.1 / M NPUT CWTPUT w o c e . 357

Refinements of the columnwise formulation

T h e advantagci o f a columnwise approach become more e v i d e m as lhe nnxlel


beeomes more c o m p l i c M e d . A s one example, consider what happens if w want t o have
separaie variables t o represem sales o f fínished materiais. W e declare a subset o f materi-
ais that can be sold, and use h to index new collcctions o f bounds. revenues and variables:

s e t M ATF w i t h i n MAT: 4 finished materiais

param r e v e n u e {MATF} >= 0;

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 :

var Seii (i in MATF} >= s e l l _ m i n l i | . <= «ell_max(i1;

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:

param c o s t (ACT} >= 0:

In t h e r o w - w i i e approach, the n e w o b j e c t i v e & written as

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

sum ( j in ACT} i o ( i . jl * Runljl

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 io (MAT.ACT}; 4 input-output coeificients

s e t MATF w i t h i n MAT: •» í i n i s h e d materiais

param r e v e n u e (MATF} >= 0:

param s e l l . m i n (MATF} >= 0:


param s e l l max ( i i n MATF} >= s e l l _ m i n ( i 1 ;

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;

subject to Balance (i in MAT}: to..come = 0;

v a r Run ( j i n A C T } > = a c t _ m i n ( j j . < = a c t max[ j ] ,


obj Met_Pro£it - c o s t l j l .
c o e i £ ( i i n MAT} B a l a n c e ( i ] io(i.j|:

v a r S e l l ( i i n MATF} > = s e l l _ m i n ( i ] . <= sell_max[ij,


o b j Met_Pro£ i t revenue ( i j .
coe££ Balancei i l -1;

Figure 16-3: C o l u m n w k e formulation, whh sales a c t i v i t i e s ( i o c o l 2 .r>cd).

v a r Run ( j i n A C T } > = a c t _ m i n l j j . <= a c t maxl j l ,


obj Net__Profit - c o s t l j j .
c o e i £ ( i i n MAT} B a l a n c e l ü ioli.jl:

v a r S e l l ( i i n MATF} > = s e i l _ j n i n ( i j . <= cell_maxlil.


o b j Net__Profit revenue l i
coe££ Balancei i l -1;

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

16.2 A scheduling model


In Section 2A wc observed thai the general form o f a blending nnxlel was applicable
t o c e n a i n scheduling problem*. Ilere describe arclatcd scheduling nnxlel for which
the columnwiseapproach is panicularly attractive.
Suppose that a &ctory's produetion for the next week is divided into fixed time peri-
ods, or shifts. You want to assign e m p b y e e s to shifts. so that the required number o f
people are working on each shift Y o u cannot fill each shift independently o f the other s.
however. because only certain wvekly schedules are allow ed; for example. a person can-
not work five shifts in a row. Your problem is thus more properly v f e w e d ai one o f
assigning empk>yees to schedules. so that each shift is covered and the overall assignmcnt
is the most cconomical.
W e can oonvcniently represent the schedules for this problem by an indexed collec-
tion o f subsets o f shifts:

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

s e t SH1FT__L1OT (SCilKDS} w i t h i n SIIIKTS;

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:

param r a t e {SCllliDS} >= 0:


param r e q u i r e d ( S H I F T S } > = 0:

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:

v a r Work (SCllKOS} >= 0 :


m i n i m i z e T o t a l _ C o s t : sum ( j in SC11KDS} r a t e i j l * Workljl;

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

The coefficienfc o f W o r k l j 2 appear instcad in its v a r declaration. In the objective, it


h^i a coefTicicnt o f r a t e [ j J. In the constraints. the membership o f S H I F T _ L I S T t j ]
tells us exactly what need to know: W o r k [ j 1 a coe (Viciem o f I in constraint
S h i £ t _ N * e d a [ i ] for each i in S H I F T . L I S T [ j 1 , a n d a coefficient o f 0 in the other
constraint*. This leads us to the following conciic declaration:

v a r Work ( j i n 9ClllíDS} >= 0 .


o b j T o t a l _ C O s t r a Lo [ j ] ,
c o e f f ( i in SlUtT_LlSr l j l } Shi£t_fJ©pds[i] 1;

The full nnxlel is shown in Fjgure 16-1.


A s a specific instance o f this nnxlel. imagine that you have three shifts a day on Mon-
day thxough Friday, and t w o shifts on Saiurday. Each day you need 100, 78 and 52
employees on the first. second and third shifts. respeetively. T o keep things simplc. sup-
p*>se that the cost per person is the same regardless o f schcdulc, so that you may just min-
imize the total number ofempk>yees by sening r a t e [ j ] to I for ali j .
A s for the schedulcs, a reavonablc scheduling mie might be that each employee works
five shifts in a wxrek, but never more than one shift in any 2-1-hour period. Pan o f the
daia file is shown in Figure 16-5: don't show the whole file, because there are 126
schedulcs that satfcfy the rule! The resulting 126-variable linear program is not hard to
solve, how* ver:

a m p l : xzodol achod.xaod; data achod.dat; aolvo;


M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
19 i t c r a t i o n s . o b j o c t i v e 2 6 S . 6

ampl: option diaplay opa .000001;


ampl: option arzit zoro r o w s 1;
ampl: option diaplay lcol 0, diaplay xridth 60;

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 :

v a r Work ( j i n SCHKDS} >= 0 .


obj Total_Cost rate ( j j J

coei £ ( i in SlllFT_LlSrlj|} Shi£t_Neodsli) 1;

Figure 16-4: Columnwise scheduling model < s c h e d . r K x l ) .

s e t SHIFTS : = Monl T u e l Wedl T h u l F r i l Satl


Mon2 T u e 2 Wed2 Thu2 F r i 2 Sat2
Mon3 T u e 3 Wed3 Thu3 F r i 3 :
param N s c h o d := 12G

set SHIFT. LIST[ 11 — >tonl Tuel Wedl Thul Fril :


set SHIFT. Lisr[ 21 = >tonl Tuel Wedl Thul Fr i 2 :
set SHIFT. Lisr[ 31 = >tonl Tuel Wedl Thul Fri3 :
set SHIFT. Lisr[ 41 = >tonl Tuel Wedl Thul Satl :
set SHIFT. Lisr[ si = >tonl Tuel Wedl Thul Sat2 •

(SJ76ntx omíkrd)

set S H I F T . L I S T ( 1231 = Tuel Wedl Thul Fr i 2 S a t 2 :


set SHIFT. LIST(1241 = Tuel Wedl Thu2 Fr i 2 S a t 2 •
set S H I F T . L I S T l 12 51 = Tuel Wed2 Thu2 Fr i 2 S a t 2 :
set S H I F T _ L I S T I 12SJ := Tue2 Wed2 Thu2 F r i 2 Sat2

param r a t e default 1 ;

param r o q u i r o d := Monl 100 Man 2 7 B Msn3 52


Tuel 100 Tu* 2 7 B Tue3 52
Wedl 100 Wed2 7 B Wed3 52
Thul 100 Thu2 7 B Thu3 52
Fril 100 Fri2 7 B Fr i 3 52
Satl 100 Sat2 7 B j

Figure 16-5: Kanial data forscheduling nnxlel < s c h e d . d a t ) .

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

v a r Work ( j i n 9ClllíDS} >= 0 .


o b j T o L a l _ C O s L r a Le [ j | ,
c o v o r ( i i n S i l l t T _ L l s r l j l > S h i f L_JJoods[ i ) ;

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.

16.3 Rules for columnwise formulations


T h e algebraic description o f an AMPI. constraint can be written in any o f t h e f o l b w -
ing ways:

airilh-expr <= a ni)\ expr


arilh-expr = arilh-expr
arilh-expr >= arilh-expr
can ti -expr <= arilh-expr <= canslexpr
can ti -expr >= arilh-expr >= canslexpr

Each cunsí-expr must be an arithmetic expressk>n not containing variables. whi te an


ariúx-txpr may be any valid arithmetic expression — though it must be linear in the vari-
ables (Section 8.2) if the resuh is to be a linear program. T o permit a columnwise formu-
lai ion. one o f t h e tiritk-exprs may be given as:

t o . come
Lo. come «- wilh expr
arilh-expr «• Lo come

Most often a "template" constraint o f this kind consists. as in our example*. o f


t o _ c o r » e , a relational operator and a eonst-expr. the constraint's linear terms are ali pro-
vided in subscquent v a r declarations. and t o _ c o : n e shows where they shoukl go. If the
template constraint does cx>ntain variables, they must be from previous v a r declarations.
and the mixlel beeomes a sort of hybrid between row-wise and columnwise forms.
T h e expression for an objeetive funetion may a b o incorporate L c _ c c r » e in one o f t h e
ways shown above. If the objeetive is a sum o f linear terms specified entirely by subsc-
quent v a r declarations. as in our examples. the expression for the objeetive is just
t o _ c o r > e and may be omitted.
In a v a r declaration. constraint coelTicients may be specified by one or mi>re phrases
consisting of the keyword c o e f f , an optional indexing expressk>n. a constraint name.
and an ansh -expr. If an indexing expression is present. a coelTicient is generated for each
member of the indexing set: otherwise, one coefficient is generated. The indexing
expression may also take the special form { i £ logietil-expr} as seen in Section 8.4 or
I5.3, in which case a coelllcient is generated only if the lúgictil-expr evaluates k> tnie.
Our simple examples have required just one c c e f f phrase in each v a r declaration, but
SECT C N 1 6 3 RULES FCR C C L U W W / S E FCFWULATONS 363

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:

p a r a m c o s L ( L I N K S . FWDDS} >= 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 nvax 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 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;

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 l . Lo B a l a n c e l j . p l ,
c o e i £ Mui L i l i . j 1 1 . 0 .
o b j ToLal_CosL c o s t ( i . j . pl :

Figure 16-6: C o l u m n w t i e formubtk>n o f Figure 15-13 ( n e t s > c o l .r>cd).

in general a separate c o e f f phrase is ncedcd for each different indexed coltection o f


constraints in which a variable appears.
O b j e c t i v e funetion ooefTicients may be specified in the same w a y , except that the k e y -
wx>rd o b j is used instead o f c o e f £.
T h e c b j phrase in a v a r declaration is the same ai the o b j phrase used in a r e dec-
larations for netwx>rks (Section 15.4). T h e constraint coefTicients f o r the network vari-
ables defined by an a r e deebration are normally given in f r o m and t o phrases, but
coeff phrases may be present as weD: they can be useful if you want t o g i v e a column-
w i s e description o f " s i d e " constraints that apply in addhion t o the b a b n o e - o f - l l o w c o n -
straints. A s an example. Figure 16-6 shows h o w a c o e f f phrase can be used t o rewrite
the multicommodity flow mixlel o f Figure 15-13 in an entirely columnwise manner.

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)

TI - (1,2,4) *?2 - (2,3) T3 - (1) T4 - (3,4) T5 - (1,3)

the sekxtkins ( T 1 . T 2 J and ( T 2 . T 4 . T 5 j cover S.but thesek-ctkin ( T 3 . T 4 . T 5 ) ckies i x i t


The goal o f é\c set cavcring problem is to fixxl the k-ast costly selecticm af subsets thit cavers S .
Tarmul J e a columnwise linear program that solves thrs problem for any given set aixl subsets.
Copyright O 2003 by R<*>crt Fourcr. D a v i d M . Qay and Brian W . K o n ç l a n

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

Figure 17-1: Piecewise-linear funetion, with three slopes.

17.1 Cost terms


Piecewise-Une jrities are often employed to give a more realistic description o f costs
than can be achicvcd by linear terms ai one. In this kind of applL-ation. piccew&c-linear
terms serve much the same purpose a* nonlinear ones, but without some of the difílculties
to be described in Chapter 18.
T o make the comparison explicit. will use the same transponaiion example as in
Chapter 18. W e introduce AMPl.'s notatk>n for piecewise-linear terms with a simple
example that ha* a fixed number of cost levek <and linear picces) for each shipping link.
Then wvr show how an extension of the notation can use indexing exprcssk>ns to specify a
varying number of piecescontrolled through the data.

Fixed numbers ofpieces

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:

param r a t e i (i i n ORIG. j i n DEST} >= 0:


param r a t c 2 (i i n ORIG. j i n DEST} >= r a t c l l i . j l :
param r a t e } (i i n ORIG. j i n DEST} >= r a t « 2 [ i . j l :
param 1 i m i t i ( i i n ORIG. j i n DESV} >• 0:
param l i m i t 2 ( i i n ORIG. j i n DE5?r} > l i m i t l [ i . j l ;
SECT-ON 17.1 COST TE W S 367

Shipments from i to j are charged at r a t e i [ i . j J per unit up to l i m i t l [ i . j ]


units, then at r a t e 2 t i . j J per unit up to l i m i t 2 t i . j ] , a n d then at r a t e 3 t i . j 1-
Normally r a t e 2 t i . j ] woukl be greater than r a t e i t i . j J and r a t e 3 t i . j J would
be greater than r a t e 2 t i . j ] . but they may be equal if the link from i to j does not
have three distinet rates.
In the linear transponaiion model. the objective is expressed in ter ms o f the variables
and the parameter c o s t as follows:

var Trans (ORlG.DESr* >= 0:

minimize Total_Cost:
sum ( i i n ORIG. j i n DEST} c o s t l i . j | * Transli. j l ;

We could express a piecewise-linear objective analogously. by introducing three collee-


tions of variables. one to represent the amount shipped at each rate:

var Transi (i i n ORIG. j i n D E S T } > = 0. <= l i m i t l l i . j | :


v a r Trans2 (i i n ORIG. j i n QBSX1} > = 0. <= l i m i t 2 l i . j |
- limitlli.j|;
v a r Trans3 (i i n ORIG. j i n QBSX1} > = 0:

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

sei ORIG: * origins


sot C15.ST ; * dosLinaLions

param s u p p l y ( O R I G } > = 0: 4 amounts a v a i l a b i o aL o r i g i n s


param demand (Dl£Sr} > = 0: 4 amounLs r o g u i r o d aL d o s L i n a L i o n s
c h e c k : sum ( i i n ORIG} supplylij = sum ( j i n OBST} demandl j ) :
param r a L o l (i i n ORIG, j i n DlíSr} > = 0:
param r a L o 2 (i i n ORIG. j i n DlíSr} >= r a L o l l i . j l ;
param r a L o 3 (i i n ORIG. j i n DlíSr} >= r a L o 2 l i . j l ;
param l i m i L l (i i n ORIG. j i n DIÍST} > 0:
param l i m i t 2 (i i n ORIG. j i n DIíST} > limiLl(i.jl;
v a r T r a n s (ORIG. DlíSr} >= 0 ; * u n i L s Lo b o shipped
minimizo ToLal_CosL:
sum ( i i n ORIG. j i n D E S T }
« l i m i t 1 ( 1 . j I . I i m i t 2 [ i . j ] .*
r a L o l l i . j l . raLo21i.j1. raLo^li.j1>> Transii.jl:
s u b j o c L Lo S u p p l y ( i i n O R I G } :
sum ( j i n DIíST} T r a n s l i . j l = supply(H;
s u b j o c L Lo Demand ( j i n DB5JT}:
sum ( i i n ORIG} T r a n s l i . j l = demand ( j l ;

Figure 17-2: Pkrcewise-linear model with three s k > p e s ( t r a n s p l l .r>cd).

AMPL a u u m a that a piecewise-linear t une tion evaluatcs to zero at zero. ai in Figure


17-1. Options for other possibilitiesarediscussed later in this chapter.
Summing the c*>st over ali links, the piecewise-linear objective funetion is now writ-
ten

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.

Varying numbers ofpieces

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:

param n p i e c e {ORIG.DEST} integer >= 1;

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.

17.2 C o m m o n two-piece and three-piece terms


Simple piecewise-linear terms have a variety o f uses in othenvise linear nnxlels. In
this section WÊ present three cases: allowing limhed violations of the constraints. analyz-
ing infeasibilhy. and representing costs for variables that are meaningful at negative as
well as positive leveis.

Penalty terms for "soft" constraints

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

s e i ORlG: < origins


r . c l DE .ST: A d e s t i n a t i o ns
param s u p p l y (ORlG} >=0: 4 amaunts a v a i l a b l e a t o r i g i n s
p a r a m demand ( D E S r } >=0: 4 amaunts r e g u i r o d a t d e s t i n a t i o n s
check: sum ( i i n ORIG} supply [ i j = sum ( j i n DBST} demand [ j ] :
param n p i e c e ( O R l G . DESr} integer >= 1;
p a r a m r a t e ( i i n ORlG. j i n DEST. p i n 1. . n p i e c e l i . j 1 }
>= i í p = 1 t h e n 0 e l s e r a t e i i . j . p - l | :
p a r a m l i m i t ( i i n O R I G . j i n DESr. p i n 1 . . n p i e s e l i . j 1 - 1 }
> i £ p = 1 t h e n 0 e l s e 1 imi t ( i . j . p - l | :
var Trans ( O R l G . DBST} >=0; * units t o be shipped

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 | ;

Figure 17-3a: Piecewise-linear nuxlel with indexed &lope&(tranâpl 2 . mod).

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:

param a v a i l _ m i n (1..T} >= 0:


param a v a i l max (t in 1..T} >= a v a i l _ m i n l t |:

param t i m e p e n a l t y (1..T} > 0:


Up to a v a i l _ m i n [ t ) hours are available without penalty in week t , and up to
a v a i l _ r n a x 111 hours are available at a loss o f t i r r > e _ p e n a l t y ( t ] in profit for each
hour above a v a i l _ s n i n 11J.
T o model this situation. we introducc a n e w variable U â e ( t ) to represent the hours
used by produetion. Clearly U s e ( t ) may not be less than zero, or greater than
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: ORIG: supply : =


GARY 1400 CLKV 2G00 PITT 2900

param: D&9T: demand : =


FRA 900 Oar 1200 LAN G00 WIN 4 00
STL 17 00 FRK 1100 LAF 1000 :
param npiocc: FRA DST LAN WIN STL FRK LAF : =
GARY 3 3 3 2 3 2 3
CLKV 3 3 3 3 3 3 3
PITT 2 2 2 2 1 2 1 :
param r a L c : =
[GARY.FRA. *J 1 39 2 SO 3 70 [GARY.DKT. *J 1 14 2 17 3 33
[GARY. LAN. *J 1 11 2 12 3 23 [GARY.WIN. *J 1 14 2 17
[GARY.STL. *J 1 16 2 23 3 40 [GARY.FRK.*J 1 82 2 98
[GARY. LAF. *J 1 e 2 16 3 24
[CLKV.FRA. M 1 27 2 37 3 47 [CLKV.DKT.*1 1 9 2 19 3 24
[CLKV. LAN. *J 1 12 2 32 3 39 [CLKV.WIN. *J 1 9 2 14 3 21
[CLKV. STL. *J 1 26 2 36 3 47 [CLKV. FRK. M 1 95 2 10S 3 12 9
[CLKV.LAF. *J 1 e 2 16 3 24

[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

1 FRA 1 1000 DKT 1 1000 LAN 1 1000 WIN 1 1000


FRK 1 1000 •

Figure 17-3b: Data for piecewise-linear nnxlel < t r a n s p l 2 . d a t ) .

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 :

v a r Use (t in 1..T} >= 0. < = a v a i l . m a x [ t |:

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|:

W e can now describe the hourly penahy in terms o f this n e w variable. If U s e [ t l is


betwvren 0 and avail_min[tl, there t> no penalty; if U s e [ t ) ii between
avail_min[tl and â v a i l _ m a x ( t ) , the penalty is t i : r » e _ p e n a l t y t t l per hour
372 P E C E V / S E L NEAR F T O 3 R 6 W 5 C H í f T Ç R 17

pciulty t - xlape = L i m e pexvalLy l t l

Uselt]
a v a i 1. min l t 1

Figure 17-4: Piecewae-linear penalty funetion for hours used.

thai it exceeds a v a i l _ s n i n l t l . That is. the penalty is a piecewise-linear funetion o f


U â e ( t ) ai shown in Figure 17-4, with slopes o f 0 and tirr»e_penalty [ t ) surround-
ing a brcakpoint at a v a i l _ s n i n [ t ] . Using the syntax previously introduccd. wvr can
rewrite the expression for the objective funetion as:

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:

a m p l : xzodol atoolpll .modj data atoolpll. dat; aolvo;


M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
21 i t e r a t i o n s . o b j e c t i v e 4 5 7 5 7 2 . 8 5 7 1

a m p l : diaplay avail min, U ao, avail aaxj


: avail_min U s e a v a i l max :=
1 35 35 42
2 35 42 42
3 30 30 40
4 35 42 42

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

soL PROD: 4 products


param T > 0 ; i number o £ w c k r .
param r a L e (PROD} > 0 : * tons p e r hour producod
param invO (PROD} > = 0: 4 i n i t i a l inventory
param cccnmit (PROD. 1. . T } > = 0: i minimum t o n s s o l d i n week
param m a r k e t (PROD. 1. . T } 0: i l i m i t o n t o n s s o l d i n wook
param a v a i l _ m i n ( 1 . , T } > = 0; i unpenalized bours a v a i l a b l e
param a v a i l max ( t i n 1. . T } avail_minl t j : i t o t a l hours a v a i l
param t i m e p e n a l Ly ( 1 . . T } > 0 :
param p r o d c o s L (PttDD} > = 0 : * cosL/Lon producod
param i n v c o s L (PttDD} >= 0: * c a r r y i n g c o s t / L o n o£ invenLory
param r e v e n u e (PROD. 1 . .T } >= 0; i revenue/Lon s o l d
v a r Make ( P R 0 D . 1 . . T } >= 0: 4 L o n s prodixrod
v a r I n v (PROD. 0. ,T> > = 0 : 4 Lons i n v e n t o r i o d
v a r S e l l ( p i n PROD. t i n 1 . . T }
> = cccnmi L l p . L j . <= m a r k e L [ p . t ) ; * tons sold
v a r Use ( t in 1. , T } >= 0. <= a v a i l maxlLj; * hours used
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 . L] * S e l l l p . L| -
p r o d c o s L lp 1 " M a k e l p . 11 - i n v c o s L l p ] * I n v lp . L] J
- sum ( t i n 1 . . T } « a v a i l _ m i n [ t | : D. t i m e p e n a l L y l L j » U s e l L ] :
4 ObjecLive: total revenue less costs in a l i weeks
s u b j o c L L o Time (L i n 1 . . T } :
sum ( p i n PROD} ( 1 / r a L e l p l J * Makelp.t] = Uselt];
i T o L a l o£ h o u r s used by a l i p r o d u c L s
rt may noL c x c c o d h o u r s a v a i l a b l e . i n e a c h week
subjocL Lo l n i t _ l n v (p in PttDD} : Invlp.OJ = invOlp]:
* IniLial i n v e n L o r y musL e q u a l given value
s u b j o c L L o B a l a n c e ( p i n PttDD. L i n 1 . . T } :
Makelp.t] + Invlp.t-1) = Sell[p.tJ + Invlp.L);
* T o n s p r o d u c e d and Laken £rom i n v e n t o r y
i musL 0 3 u a i L o n s s o l d and puL i n t o i n v e n t o r y

Figure 17-5a: Piecewise-linear objective with penahy f u n c i i o n ( s t e e l p l l .r>cd).

Deaiing with infeasibiüty

T h e paranieicrs c o r c n i t l p . t ] in Figure l7-5b represem the minimum product ion


aniounts for each product in each week. I f wvr change the data k> raise these commit-
ments:

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: rale invO prodcosL invcosL :=


bands 200 10 10 2.S
coils 140 0 11 3 :

param: a v a i l jnin a v a i 1 max Lime p e n a l L y :=


1 3S 42 3100
2 3S 42 3000
3 30 40 37 00
4 3S 42 3100

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

Figure 17-5b: Data for Figure l 7 - 5 a ( s t e e l p l l . d a t ) .

lhen there are not enough hours to produce even these minimum amounts. and the solver
repons that the problem is infeasible:

ampl: izodal ataolpll .mod;


ampl: data ataolpl2. dat;

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:

a m p l : option diaplay lcol 0;


a m p l : diaplay Inv;
Inv l * . * l <LrJ
• bands coils
0 10 0
1 0 937
2 0 287
3 0 0
4 0 -2700

and produetion o f coils in several perkxLs is below the minimum required:


SECTCN 17.2 CCWWCN T V O P ECE AND THREE P E CE TE W S 375

ampl: diaplay ccrrjrit, Haka,ei


• coninit Make mar k e t
harxis 1 3500 3490 6000
harxis 2 5900 5900 6000
harxis 3 3900 3900 4000
harxis 4 G4 00 G400 6500
coils 1 2500 3437 4000
coils 2 24 00 1750 2500
coils 3 34 00 287 0 3500
coils 4 4100 1400 4200

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:

v a r Use (t in 1..T} >= 0:

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:

The formar bound a v a i l _ r n a x ( t l become a breakpoint. and to its right a very


large slope o f 100,000 has been introducod. N o w get a feasible solution. which uses
hours ai follows:
376 PECEV/SE L N E A R F T O 3 R 6 W 5 C H í f T Ç R 17

pcnilty

Sclllp.tl
conini t l p . t 1

Figure 17-7: IVnaIty funetion for sales.

a m p l : c o d o l 5 t o o l p l 2 .mod; data atoolpl2. dat; aolvo;


M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
19 i t c r a t i o n s . o b j o c t i v e - 1 S 7 6 B 1 4 . B S 7

a m p l : diaplay avail xsax,Uao;


: a v a i l max Uso :=
1 42 42
2 42 42
3 40 41.73S7
4 42 61.2BS7

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

«ccxnmitlp.tl: -100000. 0>> Sclllp.tl

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:

«ccxnmitlp.tl: -100000.0>> Sclllp.tl «• 1 0 0 0 0 0 » c c c i n i t l p . t j

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 :

«ccxnmitlp.tl: -100000.0>> ( S e l l lp. tl . c o m n i t l p . t j J

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

var Soll ( p i n PROD. t in 1..T} >= 0. <= markcL lp. t ] ;


maximize ToLal. P r o f i L :
sum ( p i n PROD. t i n 1 . . T } < r c v e n u e l p . t 1 * S c l 1 lp . t J -
p r o d c o s L l p j l p . L j - invcosL[pJ*Invlp.t]J
- sum (L i n 1. . T } < < a v a i 1. min IL |; 0. Lime p e n a l L y l L j » Use[L]
- sum ( p i n PROD. L i n 1 . . T }
< < c o m m i L l p . L| : - 1 0 0 0 0 0 . 0 » <Sol 1 l p . L | .ccmmiL l p . L] J :

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:

a m p l : isodol atoolpU .xnod; data atoolpl2.datj aolvo;


M1MDS S . S : o p t i m a l s o l u L i o n f o u n d .
24 i t e r a t i o n s . o b j o c L i v e -293BS6347
ampl: diaplay Soll, carzait j
: S e l l conxni L
barxis 1 3S00 3S00
harxis 2 S900 S900
harxis 3 3900 3900
harxis 4 G4 00 6400
coils 1 0 2S00
coils 2 24 00 2400
coils 3 34 00 3400
coils 4 36 S7 4100

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 :

remain valid under this interpretation.


378 P E C E V / S E L NEAR FTO3R6W5 C H í f T Ç R 17

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:

a m p l : xzodol ataalplá .modj data atoolpld. datj aolvo;


M1NQS 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 o c t i v e 1194250

ampl: diaplay Kako, Inv, Soll;


: Make Inv Sell
bands 0 , 10 ,
bands 1 0 -5990 6000
bands 2 0 -11990 6000
bands 3 0 -15990 4000
bands 4 0 -22490 6500
coils 0 , 0 ,
coils 1 0 -4000 4000
coils 2 0 -6500 2500
coils 3 0 -10000 3500
coils 4 0 -14200 4200

The source o f difftcuhy is in the objective function. where i n v e o s t l p ] * I n v [ p . t ]


issubtracted from the sales revenue. When I n v [ p . t ] is negative, a negative amount is
subtracted, incrc&ing the apparent total profit. The greater the amount backordered, the
more the total profit is incrcascd — h e n c e the ixld solution in which the maximum possi-
ble sales are backordered, while nothing is pr oduccd!
A proper inventory cost function for this nuxlel looks like the one graphed in Figure
17-8. It increases bolhas I n v t p . t l becornes more positive <greater inventories) and as
Invtp, tj becomes more negative (greater hackordcrs). W e represent this piecewise-
linear function in A M P l . by dcclaring a hackordcr cost t o g o with the inventory cost:

F f e u r e 17-#: Inventory cost function.


S E C T C N 17.3 OTHER P ECEV/SE L N E / « RJNCTOUS 379

param i n v c o s t (PROD} > = 0 ;


param b a c k c o s t (PttDD} >= 0:

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:

subject to Final (p i n PROD1: Invlp.Tl >= 0:

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

ampl: dlaplay Mako, Inv, Soll;


• Make Inv Sell
barxis 0 . 10 .
barxis 1 4142.8G 0 4152.86
barxis 2 GO 00 0 6000
barxis 3 3000 0 3000
barxis 4 3000 0 3000
coils 0 . 0 .
coils 1 2000 0 2000
coils 2 1680 -820 2500
coils 3 2100 -800 2080
coils 4 2800 0 2000

About 800 tons o f coils for weeks 2 and 3 will be delivered a wxrek late under this plan.

17.3 Other piecewise-linear funetions


Many simple piecewise-linear funetions can be nnxleled in several eqüivalem ways in
AMPL. T h e funetion o f Figure 17-4, for example, could be written as
390 PECEV/SE L NEAR FTO3R6W5 C H í f T Ç R 17

i£ Use[Lj > avail_minlLj


Lhen L i m e p e r v a l L y l L l * <U;selL| - a v a i l _ m i n [ t | J c i s o 0

or more concisoly a*

max(0. Lime p e n a l L y [ L l * (Use[Lj - a v a i l _ m i n l L] J J

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

so the structurecan be noied and passed to a solver.


T h e same advice applies to the ftmction a b s . Imagine that w e would like k> encour-
age the number o f hours used k> be d o s e to â v a i l _ m i n ( t ) . Then w e would want the
penalty term ti> equal t i : r » e _ p e n a l t y 1 1 ] times the amount that U s e [ t ] deviates
f r o m a v a i l _ s n i n [ t J , e i t h e r a b o v e o r bek>w. Such a term can be written as

L i m e p e n a l Ly [ L j * abs(Us*[Ll - a vai l_min l L l J

T o express it in an explichly piecewise-linear fashion, howxrver, you shoukl write it as

Lime p c n a l L y [ L l * « a v a i l . _ m i n l tl ; -1.1» UselLl

or equivalently,

«avail jninl tl : - L i m e p e n a l L y [ Ll . L i m e p e n a l L y l L l » U.ce[Ll

As this example shows, muhiplying a piecewise-linear funetion by a constant is the same


ai muhiplying each o f hs slopes individually.
A s a final example o f a common piecewise-linear hy in the objeetive, \V>Í return to the
kind o f assignment nnxlel that was discussed in Chapter 15. Recai 1 that, for i in the set
P B O P L E and j in the set PROJBCTS, c o s t I i . j ] is the cost for person i to work an
hour on project j . and the decision variable A s s i g n [ i . j ] is the number o f hours that
person i is assigned *> work on project j :

r-eL PBDPLK:
r-eL PROJBCTS;

param c o s L ( PB3PLH. PROJBCTS } > = 0:


var Assign ( PB3PLH. PROJBCTS} > = 0:

W e orjginally formulated the objeetive a* the total cost o f ali assignments,

sum ( i in PKOPLK. j in PROJBCTS} cosLli.jl * Assignli.jl

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

check: sum ( i i n PWDPLlí} s u p p l y l i )


= sum ( j i n PROJflCT,S> d e m a n d [ j ] ;

param c o s L l P I £ ) P L l í . PROJI3CTS} > = 0 : 4 cosL p e r hour of work


param l i m i t (PBDPLK. PR0JI3CTS } > = 0: 4 maximum c o n L r i b u L i o n s
4 Lo p r o j o c L 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;

Figure 17-9: Min-max assignment nnxlel <minrw-ix. r>cd).

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.

17.4 Guidelines for piecewise-linear optimization


A M P L ' s piecewise-linear notation has the powar to speeify a variety o f useful fune-
tions. We summari/e below ifc various for ms, most o f which have been i Ilustra ted earlier
in this chapter.
Because this notation is so general, it can be used to speeify many funetions that are
not readily optimi/ed by any efTicient and reliable algorithms. We conclude by descri b-
ing the kinds o f piecewise-linear funetions that are most likely to appear in tractable mod-
els. with particular cmphasts on the propeny of convexity or concavity.

Forms for piecewise-linear expressions

A n A M P L piecewise-linear term has the general form

« hrtakpoini Da • dope- lixt> > pl • argumeni

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

Suggestions for piecewise-linear models

A s s e e n in ali o f our examples. AMPL'sterminology for piecewise-linear functions o f


variables ti limitcd todcscribing functionsof individual variables. In model dcclarations.
no variables may appear in the brtuk/Mjins lisi. dape-llst and &ru-rxpr (if anyX while an
urg-expr can only be a referenee to an individual variable. (Piecewise-linear cxpressions
in commands like d i s p l a y may use variables without limitation, however.)
A piecewise-linear function of an individual variable rcmains such a function when
multiplied t>r dividod by an arithmetkr expression without variables. A M P L also treats a
sum or dilTerence of piecewise-linear and linear functions o f the same variable as repre-
seming one piecewise-linear function o f that variable. A stparaNí piecewise-linear
function o f a model's variables is a sum or dilTerence (using - or sum) o f piecewise-
linear or linear functions o f the individual variables. Optimi/ers can effectively handle
these scparable functions, which are theones that appear inour examples.
A piecewise-linear function is convex if successive sk>pes are nondecreasing (along
with the breakpoin&). and is concave if the slopes are nonincrcasing. T h e two kinds o f
piecewise-linear optimi/ation most easily handled by solvers are minimt/ing a scparable
convex piecewise-linear function. and maximi/ing a scparable concave piecewise-linear
function, subject to linear constraints. You can easily check that ali of this chapter's
examples are o f these kinds. AMPL can obtain solutions in these cases by translating to
an eqüivalem linear program. applymg any L P solver. and then translating the solution
hack: the whole scqucnce occurs au*>matically when you type s o l v e .
Outvide o f these two cases, optimi/ing a scparable piecewise-linear function must be
viewed as an applicatk>n o f integer programming — the topic of Chapter 20 — and
AMPL must translate piecewise-linear ternfc to eqüivalem inieger programming for ms.
This. too, is done automaiically. for solution by an appropriate solver. Becausc integer
programs are usually much harder to solve than similar linear programs of comparable
size, however. you should not assume that just any scparable piecewise-linear function
can be readily optimi/cd: a degree of experimentaik>n may be necessary to determine
how large an instance your solver can handle. The best results are likely to be obtained
by solvers that accept an option known (mysterk>usly) ai "special ordered sets o f type
2 " ; check the solver-specific documentation fordetails.
T h e shuation for the constraints can be described in a similar way. However. a scpa-
rable piecewise-linear function in a constraint can be handled through linear program-
ming only under a restrictive set of circumstances:
• If it is convex and on the left-hand side o f a £ constraint (or equivalently. the
right-hand side of a 2 constraint);
• lf it is concave and on the left-hand side o f a 2 constraint (or equivalently. the
right-hand side of a £ constraint).
Other piecewise-linearities in the constraints must bedeah with through integer program-
ming techniqucs. and the preceding comments for the case of the objective apply.
I f you have access *> a solver that can handle piecewise-linearities directly. you can
turn o f f A M P L ' s translatk>n k> the linear or integer programming form by setting the
384 PECEV/SE L NEAR FTO3R6W5 CHífTÇR 17

option p l _ l i n e a r i z e k> 0. T h e c a i e o f minimi/ing a convex or maximi/ing a c o n -


cave separable piecewise-linear funetion can in particular be handled very elTiciently by
piecewise-linear generali/atk>ns o f L P tcchniqucs. A solver intended for nonlinear pro-
gramming may a l s o a c c e p t piecewKe-linear functions. but it is unlikely t o handle them
reliably unlcss it has been specially designed f o r " n o n d i f l e r e n t i a b l e " optimi/aiion.
T h e dilTerences betwxren hard and e a i y piecewiie-linear caies can be slight. This
chapter's transponaiion example t% easy, in particular because the shipping rates increase
along with shipping volume. T h e same example would be hard if cconomics o f scale
caused shipping rates t o decrease whh volume, since then wxr woukl be minimi/ing a c o n -
cave raiher than a c o n v e x funetion. W e cannot say definitively thai shipping rates ought
t o be one way or the other: their bchavior depends upon the specifics o f the situation
being modclcd.
In ali caies, the d i f f i c u l t y o f piecewise-linear optimi/atk>n gradually increaies with
the total number o f picccv. Thus piecewise-linear cost functk>ns are most e f l e c t i v e when
the costs can be described or approximaied by r e b t i v e l y f e w pieces. lf you need more
than about a do/en pieces t o describe a cost accurately, you may be beuer oíT using a
nonlinear funetion a* described in Chapter 18.

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 , ) ] )

by a picccwise linear term hiving éiicc picces. S d the breakpoints at (1/ 3 j * l i m i L [ i . j |


anJ ( 2 / 3 J * l i m i t l i . j l . Pick the skípcs so that the approximalktn cquak the crigiiul reinlin
eai term when T r a n s ( i J j ] is 0. 1/3 * l i m i t l i . j l , 2 / 3 * l i m i t l i . j l , <* 11/12 *
l i m i t l i . j 1: you shoukJ fmd thit the three skípcs an: . V i 9/2 aixJ 36 in every lerm, n:gardles*
SECT CN 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 385

o f t h r xiir o f l i m i t [ i , j l . H m l l y . place an explicit upjvr limit o f 0 . 9 9 * l i m i t [ i . j | o n


T r a n s [ i . j J.
<b) S o l v e the approximation wi#i the dita given in Figure 18 5, And cxmp are the optimal shipment
amounts Ki lhe amount* recommcreledby # i e n o n linear model.

( 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:

DARWRR.I*\_ABFL I ) 1 I ^ U C xa MT». TIFRUTAIU-A TC •èaçfeà to )

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:

dar w rr.i*\_p^n fe^ik» pcru-i* ita. a p u r a i * litl tck».» Aarr._rr.ln_aflXI J ]


dan_D*X-P*a pe^ik» pcru-i* ifcki vtu perc^c vc*ece d darr._cr.ax_aflXr J 1

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:

dar w rr.i*\_abfl darr,_jr.in_afl)c darr._cr.ax_aflV. d «r._cr.ax_al>fl


FWi BOO B50 950 1100
DE? 975 1100 1225 1250
LMf 600 600 62 b 62b
W2X 350 375 450 500
SH, 1200 1 500 1 80 0 2000
FRE 1100 1100 1100 1125
LAF 800 900 1050 1175

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.

To make use o f this variable. we introduce a definais constraint.

°<= <y.> - y ..r-l>-

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

flun f } í n QtiES) x i a [ i , J ] • Wt[J]

"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

*\xr> f j í n QtiES) xia[i^J] • Wtíjl > - CMt ávâuh 1 MGOOD


flur; ín OU^S) «ífl r i ^ l • Wtrjl < Cut iYâidtí iaE7J>

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:

Diír[i] - aun [) ín 0«ES) «iflri,Jl • Wt r j ] - Cut

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

fiar. fi í n GOOD) rrax ( 0 , - D Í í f [ 1 ] ) • fiun fi ín BAD) rr.ax < 0 , D Í f f r i l )

lixplam why m i n i n r â i f Ç thw funclkintends lei produre a desirable choice o f w e ç h t s a n d c t f o f f .

<b) The expression above k a p i e c e w w e linear funetion of lhe variables D i £ £ l i J. Rewrite il

usirçg A M H . s rciíilkin kw piecewise hnear funetions.


( c ) Incarponte lhe expnrssian f r o m <b) into an A M H . model for fírxJinglhe wvíghfc anJ c u t o f f .
<d> Given this approach. any positive vahie f o r C u t K as g o o d as any other. W e can fix it at acon
venient round nuniber — say, 100. HxpLun why this lhe case.
( e ) Usirçg a C u t of 100, apply lhe niodel t o l h e folkiwirçg imagirury credit dita:

fl*t CCCD : - _ 1 7 JL B _19 __22 _ 2 4 _ 2 6 _2B J29 ;


fl*t BAD : - _15 _2Q _ 2 1 __23 _ 2 b _ 2 ? _3Q ;

fl*t Q0K8 : - 0 1 02 R I R2 R3 S2 *?4 ;

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 .

An alternatiw: apprcuch instead mm mu/es a s u m o f ahsolute values:

/•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:

ma* |hj - (fln-flli/-/Ja2i?>|.


/•• «
1 armul J e an A M P L linear program thil w i l l minimi/e this quantity. and test it o n the « m e dita as
before. Compare the nrsulàrçg es ti mates and t ; values. Which of the three estomales would you
cha<rse in this case?

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

aixl 11 V. the lengtfi o f the bar (.*,/):

/ , = ?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

(a) Smocith ÍIXJ continuou* íunctian

<b) Di<continuous furvlfcin

( c ) Continuou*. rcinJiffcrentijLhle funetion

F i g u r e 18-1: Claises o f nonlinear functions.

18.1 Sources of nonlinear ity


W e discuss here three w a y s that nonlinearhies c o m e t o be includcd in optimi/ation
modcls: by dropping a linearity assumption. by constrocting a nonlinear funetion t o
achicvc a desired efTect, and by modeling an inherently nonlinear physical process.
A s a n example. wxr describe s o m e nonlinear variants o f t h e linear network flow nnxlel
n e t l . r » c d introduccd in Chapter 15 (Figure l5-2a). This linear program's objective is
t o m i n i m i z e k>tal shipping cost,

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

with lhe nonnegative parameters s u p p l y [ i ] and d e » â n d ( i ) representing lhe units


either available or required at city i .

Dropping a linearity assumption

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

<a) l.incoi cxKta

<b) Pieccw tsc h m r CXKts

( c ) fiwd + vjüiibk: üfKW costs

(d> Concaw nanfinew c«<t<

( c ) Convexnon linear CXKÍS

F i g u r e 1H-2: Nonlinear cost functions.


SECT CN i a i SOURCES CF NCNLNE/R7Y 395

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:

v a r C o s L (ORIG. DiíSr} : * shiomenL c o s t s p e r unit


v a r S h i p (ORIG. DííSr* >• = 0 : * u n i t s Lo s h i p

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;

This is no longer a linear objective, because it multiplies a variable by another variable.


We add some equations ti» speeify how the cost relates to the amount shipped:

s u b j e c L Lo CosL R e l a L i on ( i i n ORIG. j i n naST} :


CosLli. jl =
( c o s L i l i . j l • c o s L21 i . j 1 * S h i p ( i . j 1J / ( 1 * S h i p l i . j l J ;

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

Achieving a nonlinear effect

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

This function is approximately t i n e [ i . j ] for small values o f S h i p [ i . j ] , but goes


to infinity as S h i p [ i . j ] approaches c a p [ i . j ] : a third parameter s e n a [ i . j ) gov-
erna the shape o f the function between the two extremes. This function isahvays convex.
and so has a graph resembling Figure 18-2e. (Exercise 18-1 suggests how thi* travei time
function can be incorporaicd in*> a network nuxlel of trafllc flows.)
A s another example, \v>í may want k> allow demand to bc satisfied only approxi-
mately. W e c a n nxxlel this possibility by intnxlucing a variable D i s c r e p a n c y [ k l , to
represent the deviation o f the amount delivered from the amount demanded. This vari-
able, which can be eithcr positive or negative, is addcd *> the right-hand side of the bal-
ance constraint:

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 :

where p e n fc a positive parameter. AMPl. readily transforms this objective to a linear


one.
Th& form of penalty may not achieve the effect that we want, h o w ; ver. bccause it
penalizei each unh o f the d&crcpancy equally. T o discouragc large discrepancies, w?
would want the penalty to bccome steadily larger per unit as the discrepancy bec ornes
worse, but this is not a property that can bc achieved by linear penalty functions ( o r
piecewise-linear ones that have a flnite number o f pieces). lnstead a more appropriate
penalty function would be quadrai ic:
SECT C N IA2 NCfJL N E X & V A R / é í t - E S 397

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.

Modeiing an inherently nonlinear process

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

Flow(i, J P 2 = c l i . j H * <PrcssliT2 - Prcssl jl '2j

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.

18.2 Nonlinear variables


Ahhough AMPL variables are declarcd for nonlinear programs in the same way a* for
linear programs, two feaiures of variables — initial values and automatic substhution —
are panicularly useftil in working with nonlinear mixlels.
3 9 8 N O M . NE/F3 F R D G R A V S C H í f T E R 13

Initial values of variables

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

var Ship (LINKS} >=0. := 1;

to set every S h i p [ i . j ] initially k> I. or

var Ship ( < i . j ) i n LINKS} >= 0. := c a p l i . j l - 1;

to initialize each S h i p [ i , j ] *> 1 leis than c a p [ i , j j . Alternatively. initial values


may be given in a data statement along with the other data for a nnxlel:

var Ship: FRA DKT LAN WIN STL FRK LAF : =


OARY 800 400 400 200 400 200 200
CLKV 800 800 800 G00 G00 SOO G00
PITT 800 800 800 200 300 800 SOO :

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

Automatic substitution of variables

T h e issue o f substituting variables already arisen in an example o f lhe previous


sectk>n, where declared variables l o represent the shipping costs, and then defined
them in tcims of other variables by use of a constraint:

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:

v a r CosL ( < i . j ) i n LINKS}


= ( c o s L l l i . j l * c o s L 2 1 i . j J * S h i p t i . j 1J / <1 * Shipli.jlJ;

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.

18.3 Nonlinear expressions


A n y o f A M P L ' s ar i t i m e ti c o p e n t o r s (Table 7 - 1 ) and arithmetic functions ( T a b l e 7 - 2 )
may be applied t o variables as w e l l a* parameters. 1 f any resulting o b j e c t i v e or constraint
does not satisfy the rules for linearity < Chapter 8 ) or piecewise-linearity (Chapter I7X
A M P L treats h as " n o t l i n e a r " . W h e n you type s o l v e . A M P L passes ak>ng instmetions
that are suíTicient for your solver to evaluate every expression in every objective and con-
straint. together with derivalives if appropriate.
I f you are using a typical nonlinear solver. it is up t o you to d e f i n e your objective and
constraints in terms o f the " s m o o t h " ftmctioos thai the solver requires. T h e generality o f
A M P L ' s expression syntax can be misleading in ihis regard. For example. if you are try-
ing t o use variables F l o w ( i . j ) representing flow between points i and j . it is tempt-
ing t o write expressk>ns like

costli.j] * abe<Flow[i. j|)

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 )

Figure 1H-3: Smooth nonlinear funetions.

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

Flow(i, J P 2 = c l i . j H * (Prcsc[i|A2 - Frcr-sl j l ' 2 j

If instead the pressure is greater ateity j than ai city i , a similar equation can be written:

Flow(j,i|"2 = c l j . i l "2 * (Pror. = l j T 2 - P n s s l i n )

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 F l o w l i . j l >= 0 then F l o w ( i . j | ~ 2 c i s o -Flow[ i . j T*)


= c l i . j 1" 2 * < P r e s s ( i j * 2 - Frcr.r. l j T 2 j

Normally the use o f an i £ expressk>n would g i v e rise to a nonsnux>th constraint but in


this case it gives a funetion whose t w o q u a d n t i c halves "meet" smoothly where
F l o w [ i , j 1 is zero, av seen in Figure l8-3a.
A s another example. the convex funetion in Figure l8-3b is most easily written
log{Flov(i, jj 1 / {Flowli, j ) - l l , but unfonunately if F l c - p [ i . j ] is I A i s
simplifles k> 0/0. which would be repoitod as an error. In fact. this expression does not
evaluate accurately if F l o w [ i . j ] is merely very d o s e to zero. If instead w e write
402 NOM. NE/f3 FRDGRAVS C H í f T E R 13

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

a hÍL-hly aceurate linear approximation is substhutcd ai small magnitude* of


Flow[i, jl. This ahernaiive is noi s m o o t h in a literal matfiemahcal sense, but h is
numer krally ck>se enough t o being snnx>th t o s u f í i c e for use with s o m e solvers.
In the problem instanee that it sends t o a solver, A M P L dtvtinguishes linear from non-
linear constraints and objectives. and breaks each constraint and o b j e c t i v e expression into
a sum o f linear ttsrira phis a not-linear pan. Additional terms that become linear due t o
the fixing o f some variables are r e c o g n i z c d a s linear. K>r example. in our example from
Scction 18.1,

minimize ToLal_Cost:
suai ( i i n O R I G . j in DEST} C o s t l i . j l * Shipli.jl:

each fixing o f a C o s t [ i . j 1 variable gives rise t o a linear term: if ali the C o s t [ i . j 1


variables are f i x e d , then the o b j e c t i v e is represenied to the solver as linear. Variables
may be fixed by a £ i x command (Scction 11.4) or through the actions o f the presolve
p h & c <Scctk>n 14.1); although the presolving algorithm ignores nonlinear constraints. it
works whh any linear constraints that are available, as w e l l as any constraints that
become linear as variables are fixed.
A M P l - * s buih-in funetions are only some o f the ones most c o m m o n l y used in nnxlel
formulations. L i b r a r i e s o f other use fui funetions can be intnxlucvrd when needed. T o use
cumulativo normal and inverse cumulativo normal funetions from a library called
s t â t l i b , for example. you woukl first load the library with a statement such as

load st_aLlib.dll:

and declare the funetions by use o f A M P L i u n c t i o n staiements:

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.

18.4 Pitfalls of nonlinear programming


While A M P L gives you the poxrcr to formuhte diverse nonlinear optimi/ation models.
no solver can guarantce an acceptable solution every time you type s o l v e . T h e algo-
rithms used by solvers are susceptible to a variety of dilliculties inherent in the complexi-
tie» of nonlinear funetions. This is in unhappy contrast to the linear caie. where a well-
designed solver can be relied upon to solve almost any linear program.
This section oflers a brief introduetion to the pitfalls o f nonlinear programming. We
focus on t w o common kinds o f dinicuhies, ftmction range violations and muhiple local
optima. and then mention several other traps more brieily.
For illustration begin with the nonlinear transportation nnxlel shown in Figure
18-1. It is idêntica] to our earlier transponation example (Figure 3- Ia) except that the
ter mi c o s t I i . j 1 * T r a n s [ i , j 1 are repbced by nonlinear terms in the objective:

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;

Fach term ti a convex increasing funetion of T r a n s [ i . j J like that depicted in Figure


l8-2e: h is approximately linear with slope rate[i,jl at rebtively small values of
T r a n s I i . j J, but goes *> infinity as T r a n s [ i . j ! approaches 1 i m i t [ i . j 1. Asso-
ciated data values. also similar to thosc used for the linear transportation example in
Chapter 3. are given in Figure 18-5.

Funetion range violations

A n anempt k> solve using the nnxlel and data ai given proves unsuecessful:

ampl: xzodol nltrana. zaod;


ampl: data nltrana.datj
ampl: aolvo;
MINOS S . S E r r o r e v a l u a t i n g o b j e c L i v e Total_CosL
c a n ' t cccnpute 8000/0
MINOS S . S : s o l u t i o n a b o r t o : * .
8 iterations. objective 0

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 ) ;

Figure 18-4: Nonlinear transponation model ( n l t r a n s . * » o d ) .

param: ORIG: supply :=


GARY 14 00 CLEV 2600 PITT 2900 :
param: DEST: demand :=
FRA 900 DET 12 00 LAN 600
WIN 4 00 SVL 17 00 FRK 1100
LAF 1000 :
rate : FRA DEI* LAN WIN STL FRK LAF :
GARY 14 11 14 16 82 8
CLEV 27 9 12 9 26 9S 17
PITT 24 14 17 n 28 99 20 ;
1 imi t : FRA DET LAN WIN STL FRB LAF
GARY SOO 1000 1000 1000 800 SOO 1000
CLEV SOO 800 800 800 SOO soo 1000
PITT 800 600 600 600 SOO soo 900

Figure 18-5: Data for nonlinear trans portal ionnuxlel ( n l t r a n s . d a t ) .

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:

a m p l : diaplay ( i in ORIG, j in DEST: Trana [ i , j ) * limit [ i , j ] )/


s e t ( i i n ORIG. j i n DBST: T r a n s l i . j l == l i m i t l i . j j }
: = (GARY.LAF) ( P I T T , L A N J £

a m p l : d i a p l a y Trana [ 'GARY 'LAF' J, limit ['GARY','LAF') j


T r a n s ( ' GARV . ' L A F ' 1 = 1000
l i m i t [ * GARV . ' L A F ' J = 1000
S E C T O N 18.4 P T F A L L S O F WD N L N E A R F T O ^ W W N 3 405

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

r a t c [ G A R Y . LAF] * T r a n s [GARY . L»\FJ


/ <1 - T r a n s [ G A R Y . L A F j / l i m i t l O A R Y . L f c P j )

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

ampl: option aond atatuaoa 0j

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:

a m p l : l o t ( i in ORIG, j in DEST) Trana[i,j) i - limit [ i , j ) /2;


ampl: aolvo;
M1MDS S . S : Lhe c u r r o n L poinL cannoL b c i n r o r o v e d .
32 i t c r a t i o n s . o b j o c t i v c -7 . 38S9033 8 9 c * l 8

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:

a m p l : diaplay ( i in ORIG, j in DEST) Trana [ i , j ) /limit[i, j);


Transli.jl/limitli.jl l*.*l <trj
: CLKV GARY PITT
DKT - 6 . 1 2 S c - l «1 0 2
FRA 0 1..S 0.187S
FRK 0.7 1 O.S
LAF 0.4 0 .. I S O.S
LAN 0.37S 7 ., 0 3 2 8 8 c - l S O.S
SVL 2.9 0 O.S
WIN 0.12S 0 O.S

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:

ampl: option diaplay prociaion 0;


ampl: diaplay Trana ['GARY', 'FRE'), limit ['GARY','FRE');
Trans l ' GARY* , " FRK ' 1 = SOO . 0000000000028
limit [ ' GARY* » • FRK ' 1 = SOO
4 0 6 N O M . NE/F3 F R D G R A V S C H í f T E R 13

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:

v a r Traa-. (i i n ORIG. j in DfiST} >= 0 . <= .9999 * limiLli.jl:

With this modillcaiion, the solver readily finds an optimum:

ampl: option diaplay prociaion 6;


a m p l : xzodol nltranab.mod; data nltrana.dat; aolvo/
M1MDS S . S : o p t i m a l s o l u t i o n í o u n d .
BI i t e r a t i o n s . o b j e c t i v e 1212117
a m p l : diaplay Trana;
Trans [ * . * ] <trJ
• CLKV GARY PITT
DKT SB6.372 1B7 .3BS 42 6 . 2 4 2
FRA 294.993 B1.220S S2 3.7B7
FRK 3 6S.S 369.722 364.77B
LAF •190. S37 0 S09.463
LAN 2 9 4 . 14 B 0 30S.BS2
SVL 469.691 761.672 46B.637
WIN 9B.7S9S 0 301.241
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 407

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

T o illustrate a diíTerent kind o f difíiculty in nonlinear optimi/ation. w e consider a


sljghtly modified objective funetion that hai the following formula:

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:

a m p l : modol nltranse .mod; data nltrano.dat; solvo;


M1NQS S . S : H r r o r c v a l u a t i n g o b j e c t i v e T o t a l _ C o s t :
can*t e v a l u a t e pow'<0. 0.6)
MINOS S . S : s o l u t i o n a b o r t o d .
8 iterations. objective 0

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:

var Trans ( i i n ORIG. j i n DEST}


>= l c - 1 0 . <= .9999 * limit [ i. j]. := 0;
408 N O M . NE/F3 F R D G R A V S C H í f T E R 13

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:

a m p l : xsodol nltranod .aod; data nltrana.dat; aolvo;


M1NQS S . S : o p t i m a l s o l u t i o n f o u n d .
GS i t o r a L i o n s . o b j o c L i v e 4275GB. 1225
a m p l : diaplay Trana;
Trans l * 1 <Lrj
: CLKV GARY PITT
DKT GB 9 . 0 9 1 le-10 S10.909
FRA le-10 199.00S 700.99S
FRB 3B5.32G 32G.13S 3BB.S4
LAF BB5.9G5 114.03S le-10
LAN 1G9.GG2 lo-lO 430.33B
SVL 4G9.95G 7G0.B2G 4G9.21B
WIN le-10 lo-lO 400

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:

a m p l : lat ( i in ORIG, j in DEST) Trana[i,j) i» liiait [ i , j ) /2;


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 .
40 i t o r a L i o n s . o b j o c L i v e 35543B.200G

ampl: diaplay Trana;


Trans l*.*l <Lr1
• CLKV GARY PITT
DKT S40.G01 2GS. S09 393.B9
FRA 32B.S99 le-10 571.401
FRK 3G4.G39 3 7 1 . G2B 3G3.732
LAF 491.2G2 le-10 S0B.73B
LAN 301.741 le-10 29B.2S9
SVL 4G9. 10B 7G2. BG3 4GB.029
WIN 104. 049 le-10 29S.9S1

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:

param a l p h a >=0. <= 1;

var Trans ( i i n ORIG. j i n DIÍST}


>= l c - 1 0 . <= .9999 * 1i m i t [ i . jl- := alpha * limit[i.jl;

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

M a n y other factors can infhience the e f t i c i e n c y and success o f a nonlinear solver,


ineluding the way that the nnxlel is formulaicd and the choice o f unhs (or scaling) f o r the
variables. A s a role, nonlinearities are more easily handled when they appear in the
objective function rather than in the constraints. A M P L ' s option t o substitute variables
automaiically, described earlier in this chapter, may help in this regard. Another m i e o f
thumb is that the values o f the variables should d i f l e r by at most a f e w orders o f magni-
tude: solvers can be misled when some variables are, say, in millions and others are in
thousandths. S o m e solvers auiomatically scale a problem t o try t o avoid such a situatk>n,
but you can h e l p them considerably by judiciously picking the units in which the vari-
ables areexpressed.
Nonlinear solvers also have many mtxles o f failure besides the ones \vv? have dis-
cussed. S o m e methods o f nonlinear optimi/aiion can get stuck ai " s t a t i o n a r y " points
thai are not optimal in any sense, can identify a maximum when a minimum is desired ( o r
vice-versa), and can f a b e l y g i v e an indicaiion that there is n o feasible solution t o t h e c o n -
straints. In these cases your only recourse m a y be t o try a dilTerent staning guess: it can
sometimes h e l p t o s p e c i f y a stan that is feasible for many o f the nonlinear constraints.
Y o u may a b o improve the solver 's chances o f success by placing realistic bounds on the
variables. If you know, for instance, that an optimal value o f 80 is pbusible f o r some
variables, but a value o f 800 is not, you may want t o g i v e them a bound o f -100. ( O n c e an
indicaied optimum is at hand, you should be sure t o check whether these "safety"
bounds have been reached by any o f the variables: if so, the bounds should be relaxed and
the problem re-solved.)
T h e intent o f this section has been t o illustrate thai extra caution is aJvisable in w o r k -
ing whh nonlinear models. I f you encounter a difficulty that cannot be resolved by any o f
the simple devices described here, you may need to consult a textbook in nonlinear pro-
gramming. the documentai k>n f o r the particular solver thai you are using. or a numérica!
analyst versed in nonlinear optimi/atk>n techniques.

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

Ridiard P. 0 ' N e i I l . Marfc W f l f i a f d Hert W i f c m s and Ralph Pi l r , " A Mothemotical Programmins


M o d e l for Alkicatian o f Nilural G a x . " Operations Research 27. 5 (1979) pp. 8 5 7 - « 7 3 . A source
f<* the nan h near relotianships m nilural gás pipelme networks descrihed m Seclkin 18.1.

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?

1 8 - 2 . The falkiwing IstcJo model í c n c c . m s d ck-<ermines é i e d i m e m k i m o f a rectingulir f i e l d o f


maximum oiea thi< can bc surrounded by a fence of given krntfh:

parair. rança > 0 ;


var X f i a l d >- 0 ;
var Y f i a l d >- 0 ;

rr^xitr.iza A r o a : Xfiald • Yfiald;

flu2>}act to E h c l o » a : 2-Xfiald • 2 * Y f i a l d <- f*vsa;

It's well k m w n lha* éie o p é m u n fkrld K a square.


( a ) When w e tried Co salve thi< problem f<» A fence o f me«ers. wilh the ckfauk iratal guess o f
zero fer the variables. we gol the falktwing result:
a n p l : solvo/
K2XOS S . S : C|>timal s o l u t i o n f o u n d .
0 itarationa, objactiva 0

a n p l : dimplãy Xfiald, yfiald/


Xfiald - Q
Yfiald - 0

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.

I 0J0 OS 1.5 2.5 3L5 ±5 5.5 65 7.5 85 93 10.0

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 .

18-4. Uns problem invohes a very simple "traffic f l o w " network:

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:

Iyooí To Time C^uat» Scwa»íy


a b 5.0 10 at
a c 1.0 30 09
c b lo 10 09
b d 1-0 30 09
c d 5X1 10 0.1

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

patrair. BC flynbollc i n Intatra; * an t r a n c a t o rvatworv.


patrair. EC flynbollc i n Intatra; * a x í t ftat. n a t u o r k

aat troada w i t h i n f i í n intatra, } í n intatra: i o EX and } o EK);

patrair. tloM) {troada) > Q;


patrair. oap (troada) > 0 ;
patrair. aana (troada) > Q;

<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:

var X froadfi) >- 0 ; « cairo p * r minute %*ie*rlxiq road (i, J)


var T froadfi); * t r a v a i t i o » for ro^d
subset to I V a v a l j r í m a f(i,J) ín roadfl):
tíí,}] - tiB«ri,j] • tfl«iflri.j]*xri,j]) / (i-xii,ji/<ap[i,)i);
Y o u can confirm thit the t n w l time <*i ( i . j j is ckise t o t i m e l i . j 1 when the road is lightlv
used. but goes to infinity as the u<e apprcuches c a p l i . j 1 cars per minute. The magnitude o f
s e n s [ i . j 1 Controls the rate at which travei time increases. as ntcex- cars try to enter the raad.
Suppose that we want to analv/e how the netwcrk can best hindle some number o f cars per minute.
T h e objective is IO mini mi/e average travei time ÍIXBTI entrance t o c x i t

parair. tíirougn > 0 ; « CAra p * r minuta uaíng ttie ndtworX


minimiza Avg_Tima:
(sum f ( i , J ) ín roadfl) T í i , J ] • Xfi,J]) / tftrougíi;

T h e nonlinear expression T l i , j 1 * X l i . j l is travei minutes o n ruid ( i . j j times cars per


minute entering the road — hence. the number o f cars o n rcud ( i . j j . T h e summstion in the
objcclive thus gives the total cars in the entire system. Dividing by the number o f cars per minute
gettirçg through. we h i v e the average number o f minutes fer each car.
Complete the model by adding the f o l b w i n g :
- A constraint thit total cars per minute in equah total cars per minute out at each intcrscclion.
except the entrance aixl e x á .
- A constraint that total cars per minute leaving the entrance cquils the fctlil per minute (repre
sentedby t h r o u g h ) that are using the network.
- A p p r o p m t e bounds <«i the variables. (The example m Section 18^1 shoukl suggest what bounds
are needed.)
tJse A M H . to show thit. f<* the example givx-n ahove. a throi^ghput o f 4X) cars per minute is opti
nully managed by sendinc h i l f the cars akirçg a—yb—yd arxl h i l f along a —*c—y<L giving an aver
age travei time of about 8.18 minutes.

( d ) By try mg vahies of pirameter t h r o u g h both greater thin and l e w thin 4 j 0 , d c \ v l o p a graph o f


nünimum average travei time as a function o f throughput. A l s o , keep a n x o r d of which travei
routet are used in the optimal solutions f<* different throi^ghputs. and summari/c this information
o n your graph.
What is the relitktnship between the information in your graphand the solution* f r o m p a r * ( a ) arxl
(bp
( e ) T h e moJel m <c) assumes thit you can make the cars' drivers t a l e ceitiin routes. I"<* example.
in the optimal sohitic«i f<r a thr<iughput o f 4J0. no drí\ers an: alkiued t o " c u t thr<ii^gh" from c t o
b.
What would hippen if instead ali drivers could take wh ale ver route they plexsed? Observation has
shown thit. in such a case. the traffic tends to reach a aahlt solution m which no route hts a travei
time less thin the average. The <iptimal solution for a throughput of 4J0 is not stable. since — as
414 NOM. NE/f3 FRDGRAVS CHífTER 13

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:

parair. c h a i c * a i n c a ç a r > 0 ; t rtitrl^a: o f roucas


A*C rouca f 1. . c h o í c a s ) w í c í i í n troadü;

Heie r o u L c is an írxlcurd colk-clkin o f sett; for each r «n l . . c h o i c e s , the expression


r o u l c l r 1 denotes A diffcrcnt subset of road* (hjU together forma route from KN t o liX. our
network. choiccs should be 3, oixl th- rouLo sct< shoukJ be (<a.bj . (,b.dJ},
( < a . c j . < c . d j } and ( ( a . c j . ( c . b ) . ( b . d j } . Uâng these dati values, the subility condi*
tkiro may be craurcd bv one adJitxirul colk-ctxin of comtraints. which say thit the time to trasel
any roule isno k-ssthin th- aserage travei time f<r ali roulex:

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

T the lempcralure mside tfic tink


/ the diicknessofthe insulation

The p i w u r c mside th: tinkis a funclkinof the temperai ure.


p =

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)/!

( a ) I ' < m i u l i t e thw p r o b l e m i n A M H . AS A t w o v a r i a b l e p r o b l e m , a n J a l l e m a t i \ e l y AS A six variable


p x i b l e m in which four of t h : variablescan b e substitutedout. Which farmulitxin would youprcfer
to wcrk with?

<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:

- Some entries, marked ? Jiove. hive nci ivlübk' ettmales.


- In the estimaled the row sumsdo ncit necetarily equal the column sums.
- W e haw s c p m t c es li m a * » of the fcitil f b w s into (or out o f ) each « d a , shiwn Io the right o f
the rows in our table. These ck» not necesiaály equil the sums ofthe estimaled rows <r colunuis.

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

es ti nuted Ki wtool umn su ms, i « £ r

a{i cs ti nuted social accounting nutri* entries. ( i , j)cEA

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:

f<* ali Jc S. Y o u c a n think o í these cquatiansos t h : canstrainfe <m the v m b l » Aif.


There is no best funetion kw measuring " c k i s e " . but one popular choice K the s u m o f squared dif
f e i e m » betuecn the cstinulcs aixl the adjusted values — kw txith the nutrix xixi the raw and cal*
umn sums — scalcd h>- the cs ti nuted values. For can\enicncc. we write the adjusted sunis as
defined v a m b l e s :

T = y i

Then the objccti\e is «o niinimi/e

1'annulJe an A M H . model fcrthis problem. and determine an aptimal adjusted nutrix.

1 8 - 8 . A n e t w c r k o f pipes has the falkiwirç; laxxiut:

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

0 0 3C10 0 0 200 150 0 0 150


50 40 20 0 0 0 20 30

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.

19.1 Sources of complementarity


E o o n o m i c equilibria are one o f the best-known applications o f complementarity c o n -
ditions. W e b e g i n l h a section by slu>wing h o w a previous linear programming example
in produciion economics has an eqüivalem form as a complementarity model. and h o w

419
420 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19

s e L PROD; A produets
s e t ACT; * activities

param c o s t ( A C T } > 0 ; 4 c o s t p e r uni L o £ c a c h a c t i v i t y


param dcmand (PttDD} >= 0: 4 u n i t s o í dcmand í o r c a c h p r o d u c t
param i o (PR0D.>\CT} >= 0: 4 u n i t s o£ c a c h p r o d u c t írccn
* 1 u n i t o£ c a c h activity

var Levei (j i n ACT} >= 0:

minimize Total_Cost: sum ( j i n ACT} c o s t l j l * Levei(jl:

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.

A complementarity model of produetion economics

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,

minimize Total_Cost: sum ( j i n ACT} c o s t l j l * Levelljl:

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: izodal acorazin. xood;


ampl: data ocaa.dat;

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 :

Ffeure 19-2: Data for produetion models< e c o n . d a t ) .

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:

a m p l : diaplay Daxzand .dual;


Demand. d u a l 1*1 : =
AAl 16.7051
AC1 5.445B5
BC 1 57 . Bl B
BC 2 0
MA 2 0
NA 3 0
422 OOWFl£VENTAR7YRF*Dei£VS CHífTER 19

In the convcntional linear programming interpretation. the price on constraint i gives,


within a suHlciently small range, the change in the total cost per unh change in the
demand for product i .
Consider n o w an alternative v i e w o f the produetion economics problem. in which we
d e f i n e variables P r i c e t i ) as wvll as L e v e i [ j 1 and seek an equJibrium ralher than
an optimum solution. There are t w o requirementv that the equilibrrum solution must sat-
isfy.
First, for each product. total output must meet demand and the price must be nonnega-
tive, and in addition there must be a compiemenhirity between these rebtk>nships: where
productk>n exceeds demand the price must be zero, or equivalently, where the price is
positive the produetion must equal the demand. This relationship is expressed in A M P L
by m e a n s o f the c o m p l e m e n t a operator:

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;

W h e n t w o inequalities are j o i n e d by c o m p l e m e n t a , they both must hold, and at least


one must hold with equalhy. Bcvause our example is indexed o v e r the set PROD. it sets
u p a r e l a i i o n s h i p o f this kind for each product.
Second, for each activity, there is another relaiionship that may at first be less o b v i -
ous. Consider that. for each unit o f activity j , the value o f the resulting product i output
in terms o f the modePs prices is P r i c e t i ) * i o [ i . j ) . T h e total value o f ali outputs
from one unit o f activity j is thus

sum ( i i n ACT} Price li 1 * ioli.jl

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;

Here the constraint is indexed o v e r A C T , s o thai w e have a complementarity relationship


for each activity.
Puttmg together the t w o collcctk>ns o f complementarity constraints, w e have the lin-
ear com pie mentarity prMtm shown in Figure 19-3. T h e number o f variables and the
number o f complementarity relationships are equal ( t o a c l i v i t i e s plus products). making
this a " s q u a r e " complementarity problem thai is amenable tocertain solution techniques,
though not the same techniques as those for linear programs.
A p p l y i n g the P A T H solver, f o r example, the complementarity problem can be seen t o
have the same solution a* the related minimum-cost produetion problem:
SECT CN 19.1 SOURC£SCFOOVR^VBVT/«7Y 423

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:

Figure 19-3: Production cquilibrium nnxlel ( e c o n . s t o d ) .

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

Funher applicatk>n of d i a p l a y sho\vs that L e v e i is the same as in the production eeo-


nomies L P and that P r i c e takcs the same vahies that D e m a n d . d u a l has in the L P .

Complementarity for bounded variables

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

SOL PROD; * praducLs


SOL PCTS * acLivities
p a r a m c o s t (ACT> > 0: 4 cosL p e r uniL o í each a c L i v i L y
p a r a m demand (PROD} > = 0; i u n i L s o í demand í o r e a c h p r o d u c L
param i o (PROD.ACT} > = 0; 4 uniLs o í each producL irem
i i unit o í each a c L i v i t y
param levei_min (ACT} > 0: 4 min a l l o w e d ievei íor each acLiviLy
param l e v e i max (ACT} > 0: * max a l l o w e d ievei íor each acLiviLy
var Price (i in PROD}:
var Levei (j in ACT};
s u b j e c L Lo P r i _ C c m p l ( i i n P R O D } :
P r i c e [ i j > = 0 cccnplemcnLs
sum ( j i n A C T } i o ( i . j l * L e v e i ( j l >= demandUl;
s u b j e c L Lo L e v _ C c m p l ( j i n A C T } :
l e v e i . m i n i j l <= L e v e i l j \ <= l e v e i m a x l j l complcments
c o s L l j l - sum ( i i n PROD} P r i c e l i l * ioli.jl:

Figure 19-4: Bounded version o f pnxluction equilibrium nuxlel < e c o n 2 . r > c d ) .

W h e n a d o u b l e inequality is joinod t o an expression by c o : n p l e r > e n t s , the inequalities


must hold. and either the expression must be zero, o r the l o w e r inequality must hokl with
equalhy and the expressk>n must be nonnegative, or the upper inequality must hold with
equalhy and the expression must be nonpositive.
A bounded version o f our complementar hy examples is shown in Figure 19-4. T h e
P A T H solver can be applied t o this nuxlel ai w d l :

a m p l : iiodai ocon2 .mod;


a m p l : data ocon2. dat;
a m p l : option aolvor path;
ampl: aolvo;
PaLh v 4 . S : S o l u L i o n í o u r x i .
9 i L e r a L i o n s (4 í o r c r a s h j : 8 p i v o L s .
22 í u n c L i o n . 10 g r a d i e n t e v a l u a L i o n s .

a m p l : diaplay lovol min, Lavai, lovol max;


: l e v e i min L e v e i l e v e i max :=
Pl 24 0 240 1000
Pia 27 0 1000 1000
P2 22 0 220 1000
P2a 260 680 1000
P2b 200 200 1000
P3 260 260 1000
P3c 22 0 1000 1000
P4 24 0 240 1000

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

param d c m z e r o (PROD} > 0: 4 i n t e r c e p L and s l q p e o£ Lhe demand


param d c m r a t e (PROD} >~ 0: 4 an a £unction o £ p r i c e

var Price (i i n PROD};


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 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|:

Figure 19-5: frice-dependent demands ( e c o n n l .r>cd).

Complementarity for price dependent demands

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

dcmzero ( i l - demratelil * Price(il

where d e ^ z e r o t ü and d e s \ r à t e [ i ] are nonnegative parameiers. The resuhing


complementarity problem simply substitutes ihis expression for d e s t a n d E i ) , as seen in
Figure 19-5. The complementarity problem remains square. and can still be solved by
PA TH. but with clearly different results:

ampl: izodol oconnl.aod;


ampl: data ocannl.dat;

ampl: option aolvor path;

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

ampl: diaplay Lavai;


Levei l*I :=
Pl 240
Pia 710.15G
P2 22 0
P2a 2G0
P2b 200
P3 2G0
P3c 939.0G3
P4 240

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.

Other complementarity models and applications

T h i i baiic example can be extended to considerably more comptex models o f eco-


nomic equilibrium. The activity and price variables and their corresponding complemen-
tar hy constraint* can be compriied of several indexed collections each. and both the cost
and price funetions can be nonlinear. A solver such as PATM handlcs ali of these exten-
sions. so long a* the problem remains square in the sense of having equal numbers of
variables and complementarity constraints (or being eaúly converted to such a form ai
explained in the next section).
More ambitious nnxleU may aJd an objective funetion and may mix equality. inequal-
ity and complementarity constraints in arbitrary numbers. Solution tcchniques for these
so-callcd MPlCs — mathcmatical programs with equilibrium constraint* — are ata rela-
tively experimental stage. howxrver.
Complementarity problems also arise in physical systems, where they can serve ai
models o f equilibrium conditions betwven forces. A complementarity constraint may
represent a discreti/atk>n of the relationship betwvxrn t w o objects. for example. The rela-
tionship on one side of the c o m p i e r » e n t : s operator may hold with equality at points
where the objects are in contact. while the relationship on the other side holds whh equal-
ity where they do not touch.
Game theory provklcs another class o f examples. T h e Nash equilibrium for a bi-
matrix game fc characteri/ed by complementarity conditions. for example. in which the
variables are the prohabilities with which the two players make their available moves.
For each move. either it* prohability is zero, or a relatcd equality holds to insure there is
nothing to be gaincd by incrcaving or decreaiing its probabilhy.
Surveys that describe a variety of complementarity problems in detail are ciied in the
references at the end of this chapter.
SECT CN 192 FOWSOFOOWl^NEOTARTYOOttSTRfcNTS 427

19.2 Forms of complementarity constraints


A n A M P L cx>mplementarity constraint consists o f t w o expressions or constraints sepa-
ratcd by the c o m p l e m e n t a operator. There are always two inequalities, whose poshion
determines how the constraint is interpreted.
I f t h e i e isone inequality on either side o f c o m p l e m e n t a , the constraint has the gen-
eral form

sânglrinrquality complemente single inequalily :

where a slngle-ineejuallty is any valid ordinary constraint — linear or nonlinear — con-


taining one > = or < = operator. A constraint o f this type is satisficd if both o f the single-
inequality relationsare satisficd. and at least one is satisficd with cquality.
I f both inequalities are on the same skle o f the c o m p l e m e n t a operator. the con-
straint has instead one o f the forms

áyublt inrquaüly complemente apirsson ;


expression complemente douhlr inrquoíiiy :

where double-inequality t% any ordinary AMPL constraint containing t w o > = or t w o < =


operators. and expression isany numéricaI expression. Variables may appear nonlinearly
in ehher the double-inequality or the expression (or both). The conditions for a constraint
o f this type to be satisficd are as follows:

• 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

equal iiy complemente expression :


expression cornplemente tquaSity ;

A constraint o f this kind t» eqüivalem to an ordinary constraint consisting only o f the


equality, it places norcstrictionson the expression.
For the use o f solvers that require " s q u a r e " complementarity systems, A M P L con-
verta tosquare any model instance in which the number o f variables equals the number o f
complementarity constraints phis the number o f e q u a l i t y constraints. There may b e a n y
number o f additional inequalhy constraints, but there must not be any objective. Hach
cqualhy is trivially turned into a complementarhy condition. as observed above: each
428 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19

addcd incquality is made complementary t o a new. otherwise unuscd variable, preserving


the squarenessof the problem overall.

19.3 Working with complementarity constraints


A l i o f A M P L ' * features for ordinary equalities and incqualities extend in a straightfor-
ward w a y t o complementarity constraints. This section c o v e r s e x t e n s i o n s in three arcas:
expressions for relatcd solution vahies, eiTects o f presolve and related displays o f prob-
lem statistics. and generic synonyms for constraints.

Related solution values

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 m p l : diaplay Lav Canpl. Llb, Lov Canpl. Lbody,


ampl ? Lav Canpl. Rbody, Lav Coapl.Ralack;

: L o v _ C c c n p l . L l b Lcv_COnrol . L b o d y L e v _ C c m p l . Rb<xiy Lcv_Compl.Rslack


Pl 240 240 13 92.BG Infinity
Pia 270 1000 -B24.2BG Infinity
P2 220 220 2G4.2BG Infinity
P2a 2G0 GB0 S. 00222c-12 Infinity
P2b 200 2 00 5G4.2BG Infinity
P3 2G0 2 GO G14.2BG Infinity
P3c 220 1000 - B O I . 429 Infinity
P4 240 240 5B4.2BG Infinity

Because the right operand o f L e v _ C o : n p l an expression. h & treated as a 4 'constraint*'


with infinite lower and upper bounds, and hence infinite slack.
A sufllx o f the f o r m a u i n t t . s l a c k is also defined f o r complementarity constraints.
For complementary pairs of single incqualities. it is equal to the lesser of
aw/ir^.Lslack and tvur/nf . R s l a c k . Hence it 6 nonnegative if and only if both
incqualities are satisfied and i s z e r o if the complementarity constraint hokls exactly. For
complcmcntary double inequalitiesof the form

trxpr c c c n p l c m e n t s Ibound <= body <= ubtund


Sbttu/kS <= bady <= ubtund c o m p l c m c n L s rxpr

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

m i n ( e x p r . htxiy - Sbaêànd) ií body <= lhound


m i n ( , - e x p r , ubtund - htxiy) H htxiy >= uhtw/xJ
- a b s (expr J <* herw K C

H e nce in this case it is always nonposhive. and is z e r o when the complementa ri ty c o n -


straint is sat&fied exactly.
I f anune for a complementa ri ty constraint appears unsutTixed in an expression. it is
interpreted av representing imune. slack.

Presolve

A s explained in Section I 4 . I , A M P L i n c o r p o r a i s a presolve phaie that can substan-


tially simplify s o m e linear programs. In the presence o f complementarity constraint*.
several new k i n d s o f simplifications become possible.
A s an exampkr. given a constraint o f the form

expr, >= 0 c o m p l c m c n L : : expr2 >= 0

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

Sbttu/kS < = body < = uhtw/xJ c o m p l c m c n L ! : expr

there are various possibilities, including the f o l l o w i n g :

If presolve can deduce f o r ali Then the constraint can be replaced by


fea&ibb points that

body < uhttund lbound <= body c o n ç l c m c n L expr >- 0


Shou/kS < body < uhound expr = 0
expr < 0 body = uhttund

Transformations o f these kinds are carried out automatically, unless o p t i o n presolve


0 fe used t o t u r n o f f the presolve phaie. A s withordinary constraints, resulfc are reporürd
in terms o f the original nnxlel.
B y displaying a f e w predefined parameters:

_nconas the number o f ordiiury constraint* bcfcrc presolve


_nooons th: number o f co mp!enienl jsày conditiom befare presolve
_snconc the number o f ordiiury constraint* after presohx-
_sncconss th: number of co mp!enienlanty conditiom after presohe

or by setting o p t i o n s h o v _ s t a t s 1, you can g e t s o m e informatk>n on the number o f


simplifying transformatk>ns that presolve ha* made:

ampl: rsodal aconl .xsod; data ocon2.dat;


ampl: option aolvor path;
ampl: option ahow atata 1;
ampl: aolvo;
430 OOWFl£VENTAR7YRF*Dei£VS C H í f T E R 19

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 ncona, nccona, anc ano, anccona;


_ n c o n s = 2B
_ n c c o n s = 14
_ s n c o n s = 12
_ s n c c o n s = 12

When first instantiating the problem, A M P L counts each complementarity constraint


ai t w o ordinary constraints < the t w o arguments to c o m p l e m e n L s ) and also as a comple-
mentarity condition. Thus _ n c c o n s equals the number o f complementarity oonstraints
before presolve, and _ n c o n s equak twice _ n c c o n s phis the number o f any non-
complementarity oonstraints before presolve. The presolve messages at the beginning o f
the s h o w _ â t â t 8 output indicatc how much presolve wasable to reduce these numbers.
In this case the reason for the reduetion can be seen by comparing each product's
demand to the minimum possible output o f that product — the amount that results from
setting each L e v e i I j ] to l e v e l _ m i n [ j 1:

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 ;

the right-hand argument to c o m p l e m e n L s never holds with equalhy for N A 2 or N A 3 .


Presolve thus concludes that ? r i c e t ' K A 2 ' l and P r i c e ( ' N A 3 ' ) can be fixed at
zero, remo vim; them from the resuhing problem.
SECT CN 19 3 w c f k p t f ã v r t h o o w l e v b v t a r t y oottstrfcnts 431

Ceneric synonyms

A M P I . ' s generic synonyms f o r constraints (Section 12.6) extend t o complementarity


conditions. mainly through the substitution o f c c o n for c o n in thesynonym names.
From the m o d e l e i s view< before presolveX lhe ordinary constraint synonynfe remain:

_ncons numbcr of ordinary constr.iint< faefbn presolve


_connamc nomes o f t h e crdm.UYcarTstr.unts before presohe
_con synonyms for the ordiiury constrjLinfc befere presolve

T h e complementarity constraint synonyms are:

_nccon5 number of complcinctitority comtnintx befere presohe


_ c c o n na me nomes ofthe oamplcmcnlmty constr.iint< before presolve
_ccon synonyms for the «implcmentarity cx»nstraints befoie presohe

Because each complementarhy constraint a l s o gives rise t o t w o ordinary constraints. ai


explained in the preceding diicussk>n o f presolve, there are t w o entries in _ c o n n â x i e
cor respondi ng *> each entry in _ c c o n n a r n e :

a m p l : diaplay ( i in 1. .6) ( connas*j[i), cconnaoo[i))j


: connamcl i l _ c c o n na mel i l
1 - P r i _ C c c n p l l ' A A l * 1.. L" "Pri^Ccmpl [ ' A A l ' 1 •
2 - P r i _ C c c n p l l ' A A l * 1.. R- "Pri^Ccmpl l 'ACl • 1 •
3 - P r i _ C c c n p l [ ' A C l ' 1.. L" "Pri^Ccmpl[•BC1•1•
4 " P r i _ C c c n p l [ ' A C l ' 1.. R- " P r i ^ C c m p l l ' BC2'1•
S " P r i _ C c c n p l [ * BC1 *1.. L" " P r i ^ C c m p l [ 'NA2 ' 1 •
G - P r i _ C c t n p l [ * BC1 *1.. R- " P r i ^ C c m p l [ ' N A 3 • 1"

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:

a m p l : oxpand Pri Caapl ['AAl ') j


s u b j o c L Lo P r i Compl [ ' A A l ' 1 :
P r i c c [ ' A A l * 1 >= 0
complcmcnLs
G 0 » L c v e l l ' P i • 1 • 8*Levcl l ' P l a ' 1 + B * L c v c l l • P2' 1 +
4 0 * L e v o 1 [ ' P 2 a ' 1 «• l S * L c v e l [ , P 2 b ' 1 «• 7 0 * L c v c l l • P3• 1 «•
25*Lcvell'P3C 1 G0»Lcvcl['P4'l >-= 7 0 0 0 0 ;

a m p l : axpand con[lJ, con[2Jj


s u b j o c L Lo P r i Compl . L I ' A A l ' 1 :
P r i c c [ ' A A l ' 1 >= 0;
s u b j o c L Lo P r i Compl . R I ' A A l ' 1 :
G0*Lcvell ' P i • 1 • 8*Lcvcl l ' P l a ' 1 + B * L c v c l l • P2' 1 +
4 0 * L e v o 1 [ ' P 2 a ' 1 «• l S * L c v e l [ , P 2 b ' 1 «• 7 0 * L c v c l l • P3• 1 «•
25*Lcvell'P3c'1 G0»Lcvcl['P4'l >= 70000;

F r o m the solver* s v i e w (after presolveX a more limited coilection o f synonyms ii defined:


432 oOwfl£ventar7yrf*Dei£vs c h í f t E r 19

_5Dcon5 number of ali com trai nts after preso K c


_5Dccons number of ecanplcmentarity comtraintsafter presolve
_sconname names o f ali constraint* afiei presolw
_5Con synanyms for ali constraints after presolve

Necessarily _ s n c c o n s is less than or equal t o _ s n c o n s , with equalhy only when ali


constraint* are complementar hy constraints.
T o simplify the problem description that is sent t o the solver, A M P L converti every
complcmentarity constraint into one o f the folk>wing canonical fornis:

expr c a r o l e m e n L s lbound <= »ur <= ubttund


expr < = 0 ccmp l e m e n L s var <= uhound
expr > = 0 ccmp l e m e n L s lbound <= var

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:

a m p l : aolaxpand Pri Cox&l [' AAl ' ) j


s u b j e c L Lo P r i _ C o m p l ( ' A A l • l :
- 7 0 0 0 0 + GO* L e v e i ( ' P i ' l + 8 * L e v e i l ' P i a ' l «• 8 * L e v e l l • P2 • l +
40 * L e v e i [ ' P 2 a ' l + 1 5 * L e v e l l ' P 2 b ' 1 + 7 0 * L e v e i l • P 3 ' 1 +
25 * L e v e i [ ' P 3 c ' 1 + 6 0 * L e v e l l ' P4• 1 > = 0
ccmplemenLs
0 <= P r i c e f ' A A l * 1 ;

A predefined array o f integers. _ s c v a r , gives the indiccs o f the complementing vari-


ables in the generic variable arrays _ v a x and j / a r n a m e . This terminology can be used
t o display a list o f names o f such variables:

a m p l : diaplay { i in 1. .3) ( oconnaszo[i), avarnnxzal acvar[i]J)j


: _sconname[il _svarrvame[ _ s c v a r [ i l 1 : =
1 - P r i . C c m p l l • A A l • 1 . R- "Pricel•AAlB1"
2 " Pr i_Cccnpl [ ,AC1B 1 . R" " P r i c e l • PCI • 1 "
3 " Pr i_Cccnpl [ ' B C l ' 1 . R- " P r i c e l • QC1 ' 1 -

W h e n constraint i is an ordinary equality or inequalhy. _ s c v a r [ i ] is 0. T h e names o f


complementarity constraints in _ s c o n n a r » e are suffixed whh . L or . R according t o
whether the expr in the constraint sent t o the solver was derived from the left or right
argument t o c c = n p l e r » e n t s in the original constraint.

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

anJ th: expecled value of pbyer B's winningsis:

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:

parair. n?i > Q; « a c t i o n o a v a i l abi a to p l a y a r A


parair. nB > 0 ; « a c t i o n o a v a i l abi a to p l a y a r £

parair. payoffA ( l . . n A , l..nB); t p a y o f f A to p l a y a r A


parair. p a y o f f E ( l . . n A , l..nB); t p a y o f f A to p l a y a r £

H i e protubilities thit define t h : mixed strstcgics are nccvscarily variables. In adJükin it K c o n v e


níent to define a variable to represent the maximum cxpected j u y o f f ícr each p l i y e r :

var PlayA fi i n 1. . n A ) ; * p l a y a r A'fl rr.lxad atratagy


var PlayB { } i n 1. . n B ) ; * p l a y a r B'fl rr.ixad atratagy

var KaxExpA; * maximim a>pactad p a y o f f to p l a y a r A


var XaxExpB; * maximim tad p a y o f f to p l a y a r B

Write A M H . d c c b r a t i o m for the following conslrointo:

« T h : prubahilities in any mixed strategv must be nonnegotiw.


T h : proba!» hties in each pla\cr's mixed strategv must sum to 1.
F l a w A ' s cxpected return when playirçg any particular í
must not exeved A ' s maximum cxpected returnawr ali pctwftik* plays
F l a w B's cxpeclcd return when p h y m g a n y p o j i i r u b j j
must not excvcd B's maximum cxpeclcd return over ali p a c á b l c p U y s

( c ) Write an A M H . model f o r a squarecomplemcmarity x y í t e m that enforccs t h : cunslrainfc m <b>


aixl t h : conditions in (a).

( 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

1 9 - 4 . T w o comjunies h i v c l o decide now whether to adopt standard 1 o r standard 2 kw future


inUiduction in their p r o d u c * . If éicy decide on the same st.uxJ.ird cxmpanv A his lhe greater juy
o f f because ifc technolqgy is supi-ricr. If they decide <m different stindirds. cxmpanv B hxs the
£XMter p a y o f f became às market shaiv is greaàrr. These consick-ralkin< lead t o a binutri x same
whase p a y o f f nutrices aie

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

M a n y linear programming problems require certa in variables t o have whole number,


or integer, values. Such a requirement arises naturally when the variables represent enti-
ties like packages or people that can not be fraetionally divided — a t least, not in a mean-
ingful way for the situation being nnxlel cd. Integer variables a b o play a role in f o r m u h t -
ing equation systems that nnxlel logical conditions. ai w e will show later in this chapter.
In s o m e situatk>ns, the optimi/ation techniques described in previous chapiers are suf-
ficient t o find an integer solution. A n imeger optimal solution is guarantecd for cenain
network linear programs. a s e x p l a i n c d in Section 15.5. Even where there t% n o guarantee.
a linear programming solver may happen t o find an inieger optimal solution for the par-
ticular instances o f a mixlel in which you are interested. This happened in the solution o f
the multicommodity transpor tation nnxlel (Figure -1-1) f o r the particular data that wxr
specified (Figure 4 - 2 ) .
Even if you d o not obtain an integer solution from the solver. chances are g o o d that
you'11 get a solution in which nn>st o f the variables lie at integer values. Specificalty,
many solvers are able t o return an " e x t r e m e " solution in which the number o f variables
not lying at their bounds ti ai most the number o f constraints. I f the bounds are integral
ali o f the variables at their bounds will have integer values: and if the rest o f the data is
integral, many o f the remaining variables may turnout t o b e integers, too. Y o u may then
be able t o adjust the relatively f e w non-integer variables t o produce a completely integer
solution that i s c l o s e enough t o feasible and optimal for practical purposes.
A n example is provided by the scheduling linear program o f Figures 16-1 and 16-5.
Since the number o f variables greatly exceeds the number o f constraints. mixst o f t h e vari-
ables end up at their bound o f 0 in the optimal solution. and some other variables c o m e
out at integer values as w e l l . T h e remaining variables can be rounded up t o a nearby inte-
ger solutk>n that is a little m o r e c o s t l y but still satisfies the constraints.
Despite ali these possibilities, there rema in many circumstances in which the restric-
tion t o iniegrality must be e n f o r c e d e x p l i c h l y by the solver. Integer programming solvers
face a much more difllcuh problem than their linear programming counterpans, however:
they generally require more computcr time and m e m o r y , and often demand more help

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.

20.1 Integer variables


By adding the Iceywocd i n t e g e r to the qualifying phra%cs o f a v a r declaration, you
restrict the declared variables *> integer values.
A s a n example, in analy/ing the diet nnxlel in Section 2 3 , w e arrived at the following
optimal solution:

ampl: xzodol diot.xaod;


ampl: data diot2a .dat;

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

If we want the fcxxls to be purchased in imegral aniounts. w e add i n t e g e r to the


model's v a r declaration (Figure 2-1) as follows:

v a r Buy (j i n FOOD} intoger >= f _ j n i n ( j l , <= £ m a x l j l :

W e can then try to re-solve:

a m p l : xzodol dioti .xaod; data dlot2a.dat;


ampl: aolvo;
Ml NOS S . S : i g n o r i n g i n t o g r a l i t y o í 8 v a r i a b l e s
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 11B.0S94032

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 : option aolvor cplox;


ampl: aolvo;
CPLKX 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 ; objocLive 119.3
11 MlP s i m p l e x i t e r a t i o n s
1 branch-arxi-bDund n o d e s

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.

20.2 Zero-one variables and logical conditions


Variables that can take only the vahies zero and one are a special caie of integer vari-
ables. By cie ver ly incorpora ti ng these " z e r o - o n e " or " b i n a r y " variables into objeetive*
and constraint*. integer linear programs can specify a variety of logical conditions that
cannot be described in any practical way by 1 inear constraints ak>ne.
T o introducv? the use of zero-one variables in AMPL, we return to the multicommixlity
transpor tal ion nnxlel of Fjgure 4-1. The decision variables T r a n s l i , j . p ] in this
nnxlel represem the *>ns of pnxluct p in set PROD to be shipped from originating city i
i n O R I G todestination city j in DEST. In the small example of data given by Figure 4-2,
the pnxluct* are b a n d s , c o i l s and p i a t e : the origins are GARY, CLEV and P I T T ,
and there are seven destinations.
T h e cost that this nnxlel associates with shipment o f prtxluct p from i k> j is
c o s t ( i , j , p j • T r a n s t i . j . p h regardless o f t h e amount shipped. This 4 'variable' *
cost is typical o f purely linear programs. and in this caie a Dows small shipments betwven
many origin-destinatk>n pairs. In the following examples we describe ways to use zero-
440 MTtGER L NEAR F T O 3 R W S CHÉFTCR20

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

ampl: option diaplay opa .000001j


ampl: option diaplay tranapoao -10j

a m p l : diaplay {i in ORIO, j in DEST)


ampl? SUE {p in PROD) Trona [ i , j , p) ;
sum(p i n PROD} T r a n s [ i . j . pl l*.M
: DEI* FRA l'RE LAF L AN CT'L WIN
CLKV G2S 27 5 325 22 5 4 00 550 200
GARY 0 0 625 150 0 G25 0
PITT 52 S G2 5 225 G2 5 100 G25 17 5

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 :

param v c o s t (ORIG. DECT. PROD} > = 0: * v a r i a b l e c o s t on r o u t e s


param f c o s t (ORIG.DECT} > 0 : * f i x e d c o s t on r o u t e s

We want f c o s t l i . j 1 to be added to the objective funetion if the total shipment o f


products from i k> j — that is. sum { p i n PROD) T r a n s [ i . j . p l — is positive: w e
SECT CN20.2 Z E TO O P C V / « ABLES A F © L05 CA- C O N D T O N S 4 39

want nothing to be added if the total shipment is zero. Using A M P L expressions. w e


could write the objective function most directly as follows:

minimize Total_Cost: * NOT PRACTlCAL


sum ( i i n ORIG. j i n DKST. p i n PROD}
v c o s t l i . j . p l * Transi i, j ,pj
+ sum ( i i n ORIG. j i n DKST}
i í sum ( p i n PROD} T r a n s l i . j . pl > 0 Lhen fcostli.jl:

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

sum ( p in PROD} Transli.j.pl

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 :

v a r Use (ORlG.DKST} binary:

The objective function can then be written ai a linear exprcssion:

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:

If U s e l i . j ] is 0, this constraint says that

sum ( p in PROD} T r a n s l i . j . p l <= 0

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>

sum ( p in PROD} T r a n s l i . j . p l <= l i m i t l i . j l

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

param s u p p l y (ORIG, PROD} >= 0 ; i amaunLs a v a i l a b l e aL o r i g i n s


p a r a m demand (DEST. PROD} >= 0 ; i amaunLs r e q u i r e d a L d e s L i n a L i o n s

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:

param l i m i t ( O R I G . DEST} >= 0: i maximum s h i ç m c n L s on rouLes

p a r a m v c o s L ( O R I G . DESr. PttDD} >= 0: i v a r i a b l e s h i c m e n L c o s L on rouLes


v a r T r a n s ( O R I G . DEST. PROD} >= 0: * uniLs Lo b e shippod

p a r a m í c o s L ( O R I G . D ESI'} >= 0: * £ixod cosL £or using a rouLo


v a r Use ( O R I G . DEST} b i n a r y : 4 = 1 o n l y í o r r o u L e s used

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 L o Demand ( j i n DEST. p i n PROD}:


sum ( i i n O R I G } T r a n s ( i . j . p l = d c m a n d l j . p l :

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:

Ffeure 20-1 a: Muhicomnnxlity nnxlel with fixod costs < mu l t r n i p l . m c d ) .

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 ) :

param £ c o s L : FRA DST LAN WIN STL FRE LAF : =


GARY 3 0 0 0 1200 1200 1200 2S00 3S00 2S00
CLEV 2 0 0 0 1000 1S00 1200 2S00 3 0 0 0 2 2 0 0
PITT 2 0 0 0 1200 1S00 1S00 2S00 3S00 2 2 0 0 :

If \v\r apply the same solver as before, the integraüty restrictions on the U s e variables are
ignored:

a m p l : izodol miltaipl .mod;


a m p l : data x a u l t x & i p l . dat;
ampl: aolvo;
Ml NOS S . S : i g n o r i n g i n t e g r a l i L y o£ 21 variables
M1N0S S . S : o p L i m a l s o l u L i o n í o u n d .
43 i t e r a L i o n s . o b j e c L i v e 223S04

ampl: option diaplay opa .000001;


ampl: option diaplay tranapoao -10;
SECT CN20.2 Z E T O O P C Vt&ABLES A F © LOQ CM. O O N D T O N S 443

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 supply (trj : GARY CLEV PITT : =


bands 4 00 700 800
coils 800 1600 1800
p i a Lo 2 00 300 300 •

param dcmand (trj :


FRA DET LAN WIN STL FRE LAF
bands 300 300 100 75 650 22 5 250
coils 500 750 400 250 950 850 500
p i a Lo 100 100 0 50 200 100 250

param limit doíaulL 62 5 •

param v c o s t :! =

l * . * .baixds] : FRA DET LAN WIN srL FRE LAF


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

l*.*.coilsJ : FRA DET LAN WIN srL FRE LAF


GARY 39 14 11 14 16 82 8
CLEV 2? 9 12 9 26 95 17
PITT 24 14 17 13 28 99 20

l*.*.plALo|: FRA DET LAN WIN srL FRE LAF


GARY 41 15 12 16 17 86 8
CLEV 29 9 13 9 28 99 18
PITT 26 14 17 13 31 104 20

pa ram £ c o s t : FRA DET LAN WIN srL FRE LAF


GARY 3 0 0 0 1200 1200 1200 2 5 0 0 3 5 0 0 2 5 0 0
CLEV 2 0 0 0 1000 1500 1200 2 5 0 0 3 0 0 0 2 2 0 0
PITT 2 0 0 0 1200 1500 1500 2 5 0 0 3 5 0 0 2 2 0 0

Figure 20-lb: Daia for Figure 20- l a ( m u l t » i p l .dat).

ampl: d i a p l a y SUE ( i in ORIQ, j in DEST, p in PROD)


ampl? vcoat[i, j,p) • Trana[i, j,p);
sum(i i n O R I O . j i n DESr. p i n PWDD}
v c o s L l i . j . p | » T r a n s [ i . j .pl = 199500

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 : option aolvor cploxj aolvoj


CPLKX 8 . 0 . 0 : o p t i m a l i n t e g e r s o l u t i o n ; objeetive 229850
295 M1P s i m p l e x i t e r a t i o n s
19 b r a n c h - a n d - b o u r x i n o d e s
a m p l : diaplay {i in ORXG, j in DEST)
ampl? SUE {p in PROD) Trana [ i , j , p) ;
sum(p i n PROD} T r a n s [ i . j . pl l*.M
: Dirr FRA FRK LAF LAN STL WIN
CLKV 625 27 5 0 42 5 3 50 550 37 5
GARY 0 0 625 0 150 G25 0
PITT 525 G2 5 550 57 5 0 G25 0

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 :

s u b j e c t t o M i n ^ S h i p ( i i n ORIG. j i n DKST}: A WR0M3


sum ( p i n PROD} T r a n s l i . j . p l >= 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:

s u b j e c t t o M i n ^ S h i p ( i i n ORIG. j i n DKST}: * NOT ALL/DWKD


sum ( p i n PROD} T r a n s l i . j . p l = 0 or
sum ( p i n PROD} T r a n s l i . j . p l >= m i n l o a d ;
SECT C N 2 0 . 2 Z E TO O P C V / « ABLES A f © L05 CA- C O N D T O N S 4 39

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:

When total shipments from i to j are positive. U s e [ i . j ] t% I. and M i n _ S h i p [ i . j 1


becomes the desired minimum-shipment constraint. On the other hand, when there are no
shipments from i to j . U s e [ i , j 1 is zero: the constraint roduces to 0 > = 0 and ha* no
effect.
With these new restrictions and a m i n l o a d o f 375. the solution ti found t o b e ai fol-
lows:

ampl: isodol xailtmip2 .mod;


ampl: data aultxsip2. dat;
ampl: aolvo;
CPLttX 8 . 0 . 0 : op L i m a i i n L e g e r s o l u L i o n : o b j e c L i v e 233150
27 9 M1P s i m p l e x i L e r a L i o n s
17 h r a n c h - a n d - b o u n d n a d e s
ampl: diaplay ( i in ORIG, j in DEST)
ampl? SUE {p in PROD) Trona [ i , j , p) ;
sum(p i n PROD} T r a n s [ i , j , pl l*.*l
: DST FRA FRK LAF LAN STL WIN
CLKV 625 42 5 425 0 500 G25 0
GARY 0 0 375 42 5 0 600 0
PITT 525 47 5 375 57 5 0 575 37 5

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:

s u b j e c L Lo Max. S e r v e ( i i n O R I G } : * NOT ALLOWKD


c a r d ( j i n DEST:
sum ( p i n PttDD} T r a n s l i . j . p l > 0} <= m a x s e r v e :

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

param s u p p l y (ORIG, PROD} >= 0 ; 4 amaunts a v a i l a b l e a t o r i g i n s


p a r a m demand (DBST, PROD} >= 0 ; 4 amaunts 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 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;

p a r a m l i m i t ( O R I G . DIíST} >= 0; 4 maximum s h i r x n c n t s on r o u t e s


p a r a m m i n l o a d >= 0; 4 minimum ronzero shipmcnt
param m a x s e r v e i n t e g e r > 0 ; 4 maximum d e s t i n a t i o n s s o r v o d

p a r a m v c o s t ( O R I G . DIíSl'. PWDD} >= 0; 4 v a r i a b l e shipnent cost on routes


v a r T r a n s ( O R I G . DKST. PROD} >= 0; 4 units t o be shipped

p a r a m í c o s t ( O R I G . D I í S l ' } >= 0; 4 f i x e d c o s t í o r using a r o u t e


v a r Use ( O R I G . DIíST} b i r v a r y ; 4 = 1 o n l y í o r r o u t e s used

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 Demand ( j i n DIíST. p i n PROD}:


sum ( i i n O R I G } T r a n s l i . j . p l = d c m a n d l j . p l ;

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;

Figure 20-2a: Multicomnnxlhy model whh funher restrictions (mu l t m i p 3 .rr>cd).

Zero-one variables again offer a convcnicnt ahernaiive. vSince the variables


U s e [ i . j ] are I precisely for those destinaiions j served by origin i . and are zero oth-
crwise, we can write sum { j i n D E S T ) U s e ü . j J for the number o f destinations
served by i . Thedesired constraint beeomes:

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 ;

Adding this constraint to the prevk>us nnxlel, and setiing r r u i x s e r v e to 5, arrive ai


the mixed imeger nnxlel shown in Figure 20-2a. whh daia shown in Figure 20-2b. h is
optimi/cd as follows:
SECT ON 20.2 ZETO ONE V/fi A£tES A f C LOQ C/C OONDTONS 447

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 s u p p l y (trj : GARY CLHV PITT : =


bands 4 00 700 800
coils 800 1G00 1800
p i a Lc 2 00 300 300 •

param demand (trj :


FRA DKT LAN WIN STL FRK LAF
bands 300 300 100 7S GS0 22 S 2S0
coils SOO 7S0 400 250 9S0 8S0 SOO
plate 100 100 0 SO 200 100 2S0

param limit d e f a u l t G2S :

param v c o s L :=

L * . * .bands| : FRA DKT LA:J WIN SVL FRK LAF : =


GARY 30 10 8 10 11 71 G
CLKV 22 7 10 7 21 82 13
PITT 19 11 12 10 2S 83 IS

«coils| : FRA DKT LAN WIN STL FRK LAF : =


GARY 39 14 11 14 1G 82 8
CLKV 27 9 12 9 2G 9S 17
PITT 24 14 17 13 28 99 20

.platcl : FRA DKT LAN WIN srL FRK LAF : =


GARY 41 IS 12 1G 17 8G 8
CLKV 29 9 13 9 28 99 18
PITT 2G 14 17 13 31 104 20 ;

param f c o s t : FRA DKT LAN WIN srL FRK LAF : =


GARY 3 0 0 0 1 2 0 0 1 2 0 0 1 2 0 0 2 SOO 3SOO 2SOO
CLKV 2 0 0 0 1 0 0 0 1 S 0 0 1 2 0 0 2 SOO 3 0 0 0 2 2 0 0
PITT 2 0 0 0 1 2 0 0 1 S 0 0 1 S 0 0 2 SOO 3SOO 2 2 0 0 :

param m i n l o a d := 37S :

param m a x s e r v e := S ;

F i g u r e 20-2 b : Daia for Figure 20-2a<multmip3 .dat).

ampl: i s o d o l sailtxnip3 .mod;


ampl: d a t a aultxsip3. dat/

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

a m p l : diaplay { i in ORIO, j in DEST)


ampl? SUE {p in PROD) Trona [ i , j , p) ;
£um(p i n PROD} T r a n s l i . j . p l l*.M
: DKT FRA FRK LAF LAN STL WIN
CLKV G25 37 5 550 0 500 550 0
GARY 0 0 0 400 0 G25 37 5
PITT 525 52 5 625 GOO 0 G25 0

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.

20.3 Practical considerations in integer programming


A s a rule, any integer program is much harder *> solve than a linear program o f the
same size and structure. A rough idea o f the difTerence in the prevk>us examples is given
by the number o f iterations reponcd by the solvers: it is -ll for solving the original linear
multicommodity transponation problem. but ranges from about 280 t o 4 0 0 f o r the mixed
integer versions. The computation times vary similarly: the linear program* are solved
almost instantly, while the mixed integer ones are noticeably slower.
A s the size o f the problem incrcases, the difflculty o f an integer program also g r o w s
more quickly than the difTiculty o f a c o m para ble linear program. Thus the practical limits
t o the size o f a solvable integer program will be much more restrictive. Indeed. A M P L
can easily generate integer programs that are kx> diflicult f o r your computcr to solve i n a
reaionable amount o f time or memory. B e f o r e you make a commitment to use a nnxlel
with integer variables. therefore. you should consider whether an alternative continuous
linear ot network formulation might g i v e adequate answers. if you must use an integer
formulation, try it on collections o f data that increase gradually in size, so that you can
get an idea o f the computar rcsourccs required.
I f you d o encounter an integer program that 6 diíTicult to s o l v e . you should consider
reformulai ions that can make it easier. An integer programming solver attempts to inves-
tigate ali o f the ditTerent possible combinations o f values o f the integer variables;
although it employs a sophisticated strategy that rules out the vast majority o f combina-
tions a* infeasible or suboptimal the number o f combinations remaining to be checked
can still be huge. Thus you should try to use ai few integer variables as possible. For
those variables that are not zero-one, k>wer and upper bounds should be made as tight ai
possible to reduce the number o f combinations that might be investigated.
Sol ver s derive valuable information about the sohitions to an integer program by f i x -
ing or reitricting some o f the integer variables, then solving the linear programming
SEC7CN20 3 P R A C T C A L OONS C G R A T O H S N N T E G E R F W X R W W N 3 449

" 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:

s u b j e c L Lo A v a i l ( i i n ORIG. j i n DEST. p i n PROD}:


T r a n s l i . j . p l < = min ( s u p p l y l i . pl . demandl j . p 1J * U s e l i . j l ;

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

G c o r g e L . Nemhiuser and I.aurence A . W o l s e y , Inie&rr anti Cambinatorial Ofxini&tíivn John


W i b y Si S o m ( N e w York. N Y , 1988). A xurvey of integer programming problem*. theory axxl
oJg<*ithms.

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».

Lauience A . W a l a e y , I n i t & r P m % r a m m i n x . W i l e y Interscience ( N e w York. N Y , 1998). A practi


c a l intermedia*: le\el guide for reoders familiar wilh linear programming.

Excrcises

2 0 - 1 . lucrei*? 1 1 optimi/es an adverti-a ng c a m p n g n thit permits aitvtrary cambmatians of viri-


a m media. Suppose that insteod you must alkicate a $1 milhan ad svrtisxnc campaign onicvig sev-
era! media. but í<r each. your only choice rs whether to use that médium or not. T h e f o l b w i n g
t A l e shows. f<* each médium. the cost and audience in thousands i f yau use that médium, and the
crestire tinte in three categories thit will hase Ic» be conimittcd i f yau use thit médium. T h e fiiul
column shows your hmits <*i cost axxl on hours of cxrative time.

TV MigUüftC Radto Ncnftçer Mil PtkOttC 1-iantw


Actit-xe 300 200 100 130 100 30
Ctoe* 600 250 100 120 200 230 1000
WV*CN 120 30 20 40 30 5 200
>VtM% 120 SO 0 60 40 0 300
( Ü K IN 20 20 20 20 20 200 200

Your goal is to maximize the audience. subject to the Imiits.


( a ) lormulate an A M P l . model f<r this situatian. usirçg a zero-one integer variable f<r each médium.

<b) U s e an integer p r o g r a m m i n g s a h e r to fiixl the optimal sohitian.


Also solve the problem with the integrality lestriclians relavcd and c o m p r e the resultirçg solutían.
Could yau ha\e guessed the integer aptimum from laokiqg at the nan integer one?

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:

porair. Xn apaazXfl > 0 lncaçar; * nurrtoar XnjpflacXs

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

AMPL is a Lnguage kw algebraic model ing -uxJ nuthLHutic.il programming: a computer


nMdibk- Lnguage kw cxprcssing optimi/atiun problems such AS fincar programming in algebraic
notation. This appendix sunuiuri/cs th: features o f AMPL, with particular cmphasis on tcchnical
dctails nciC íully c o w i c d in th: preccdiiç chapter*. Neverthek-ss, noi cvcxy featuiw construi. axxl
Option is foted; th: A M H . wct» site www. ampl. COT contains th: most up to dite axxl coinpk-tc
informal ion.
T h : folkiwirçg rcititiciiul conwmtions *ic med. Literal text K printed in c a n s L a n L width
í o n L . while synticlic catogaiec an: printed in ilaBc f>ni. Phrases <r subphrases cfickised in
slintcd squire hrackct* / aixJ / are optionil. as an: constructs with th: suhscnpt /jpi.

A.1 Lexical rules


A M P I modeh invohv variables. constraint*. and objcclives, cxpnrmed with the help of sets axxl
parameters. T h e » arecalk-d nvxirl rnúúrx. liach model entitv his an alphanumcric nune: a strirçg
o f one <r mere Unicode UTT-Í le*ters, digits. and underscxres. in a juttern thit cannot be mistaken
f<r a numeric constai*. Upper case le«tcrsare distincl from lower case leíter*.
Numeric coiKtmfc are written «n staixlard scientific rcititkin: an optional sçjn. a sequencv o f
digits lhai may contam adecinul point. aixl an optional exponent field that begim with onc of the
letters d . D. e or K. as in 1. 23 D-4 5. AH arithmetic in A M P L is in the same precition (ckiubk- pn:
cisxin <*i most n u c h i n e s s o ali expcinent notations an: sy nonymous.
Literal* an: strings debniited either by sirçgk- qucites • cr by tkiubk- quotes the delmütorçg
etaneter must be doubled if it appcars within the literal as in 'x' 'y \ which K a literal contam
írçg the three characlers x *y. Newline characlers nuv appear wiéiin a literal only if preceded by \.
Tliechoicr o f delâniler k aitâtrtfy; ' a b e * and " a b e * denote the same literal
I.Herah are distorxt from numeric constants: 1 aixl ' 1 ' are unrelafted.
Input is frec ferm; white sjucv (im 1 sequenev of spacr. tib cw newline chararters) nuv appear
betwwn any toKcns. liach stUement ends with a semicokin.
Commcnts begin wüh 4 and extend to the end of the current line, or arcdchmitcd by / * aixl
V , in which case they may extend acros* severa! lines aixl ck» not nest Canmentt may appear
any where in declarations. ccmmand*. and dita.
These wordsare reserved. xixi may not be u*cdin other contexts:

4S3
454 A M = L F E F E F E N C C WAMJ/C AFFENDXA

Curront cearei a manto In togar fi o l v a _ r «fiu 1 r^nuir.


:x ocficainu lOfifi fiuffix
xttxrr dofaulc logical fiuxr.
Infinity dixr*an ttAX fiyiítoolio
Inicial div irdn tabl*
LOCAL AlÜQ c$>tion tJwn
OU? amritron M C Of union
ali * xiar.fi toada until
blnary fotrall toada wMla
by if witíiin
oíwox in

W o r d s begm nirçgwith undersccve w c a k o reserved. T h : other k c y w a n k , funetion names, etc.,


«ire predefmed. but their mcariqgs can be redefined. For example, the* word p r o d is predefined as
a product operator anakigou* to sum, bul itean be redefined in a declaration. such as

aat p r o d ; Ü pro<tiotfi

O n c e a word has been redefined. the crigiiul meaning is moccessfck:.


A M P I pro vides synonyms íor several keywcvds and operators; lhe preíerred ferms an: on the
left.

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:

{ (1,2,3), (1,2, 4), (1,2,5), (1,3,7), (1,4,6))

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

Sasne T>pe KemAx

1 lC-ehan-olfla AS A ú a t i l f l a . tfüú " Í I M 0".r.w


S: " a l » a í/J^v" rcquicd
2 ** II L
* axíata for a l i L krr/xol rc dnu co ope rjür*
4 and LL L
5 < < - - - - O ! - >- > L
6 In nor. í n L mxtxitftip ia *s
6 w i t h i n not w i t h i n L S w i t h i n T a v ^ N C i S c MS ?
7 nat ! L
* ittíon d í í f flyirdíff S flywdí I I -spraneneádicrc&c
9 íntar S sei v*ce«ca*xk
10 orofifl s COM. Cf Ca* <NUâ
11 aatof . . fcy s *e« ooúPtfceecrs
12 • - lâfifl A <2 loflfl h ~ sraxi a - b. 0»
15 «urr. prod min max A jntLCi cü c rata i f o j i t t .
14 • / d í v rrod A d í v -tt\-âoitedi|uc<leaccT luupar*
15 • - A C A I I > pkuv UAUN £RAAU-W
16 • • A ClfVOC/JLutxV,

Operators on: listed in mcreasirçg precedence order. Kxponentiatian and i í - L h e n -


c l . c c a e right associitive: th: other operators are left associitive. Th: ' Type' col-
umnindicates resuk types: A f<* arithmetic. L for kigical S for set

Tahtr A - l : Arithmetic. kigic.il jmd srt operators.

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

ai>c(.0 jtv-okxe vuke |a|


ACOfl (tf u t e r e ccroac. com'"1 < A \
acoflJi(tf vt\e o e h> pe e e osiac. e " 1 < x»
a l i a s ir) atuscrfatxfclcãory r
a a í n (x) sia '(A »
a a l n h IA) tatene h* peitolic *aae. '(A »
aran (X) '(A)
atan2 iy.x) '(J/A)
ar.an2i(tf '(A»
oail(x) c c i a ç otfx (âCAih^eruK^eii
ctlroa ( ) curem o r e a
CXÍtt* (/)
(A) COM»
ocp(A)
f l o o r (A) fkxcof A COCAI kvrtcr IXE/A)
2a?(tf
lo^lO bfidlxt
ttAX ( A . > ' . . . . ) auxixt^ndcrsnoc orçmeati)
crin ( A . > » . . . . ) a* aiaiuai (2 cr anxc arçurc* %»
praciflionU.*) A M_ADED co * dcci.ru] D I Y * .
ROUND ( A . * ) A tn-aded co * FIRA deoaul pooai
ROUND ( A ) A m_aded co oa uic^er
FLÍN(A) JÉK
flính(A) h» peito]* xiúc
«rrt(tf HfUllC nx<
can (tf na^oM
EANFT ( A ) h»pcito]x' UJ^CJÁ
titrri» ( ) curem o r e u
trunc (x. ir) A OL-X'AIOJ co çkz^i pCOil
trunc (tf A W-^- acoj co aa UCE^A-

T a b l e A-2: Ihuk in arithmctic funetions.

a n p l : M C y - motor (i in 1..S) (i,i'2>/


ampl: dimpléy y/
fl«t y : - ( 1 , 1 ) ( 2 , 4 ) ( 3 , 9 ) ( 4 , 1 6 ) (5,25);

4.4.Í Built-in funetions

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

BatAía.h) - -x^'/<r<<2»r</>»/r<<2-tMK (0. I|


CauetyO <lrns)t\U\ - l A x O + x 1 ) !
Exporvancí al () d**siiy<.\\ - \ x>0
Oairír-alfl) <&vt4/i<x> - /r<<tK xfcOl a > 0
Xtrand224 ( ) iace£«r «nfonn o n j a i 2 4 *
Kormal in. c« âccn al il vxr±*-£»:o . . A j c x í h . u ú aac c c
KormalOl ( ) aonnd Jj » « h J a . a UÚX^c ]
Polsoon(}&) pMbakiiiryikl - Jt - 0 . 1. ...
Uni form (m. *) uaiíonn on ( « . **
Itoi f otrmO 1 () «rifam on ( a I»

Table A-3: HuiU inrandom numbcr generation funetions.

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.

A.42 Strings and regular expressions

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

Table A«4: Ihnk m strii^ aixl regular expiession funetiems.


460 A W L F E F E F B ^ S VAWJXL AFFSNDXA

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.

A.4.3 Piecewise-linear terms

In varnble, canstraint and objecti\c declaratians. piecewise linear terms have one of the foi
lowiiç forms:

<< b/*ük[M>inu ; si<\vt >> vai


« b/tolfHtJ*/S ; sJrtfMi >> 1 íéX(V)
« b/tolfHtJ*/s ; sJrtfMi >> {vai, íéxpr)
« Netí^MflMS ; sit\vs >> \<<\(», <<\(»\

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

<< hr*atyit)létíir ; sit\#s >> (/Jifv)


<< k/ratytfinu ; si<\vt >>

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.

A.5 Declarations of model entities


DccUratxins of model enlilies ha\e the folkiwirç; common fcrm:

ttti ky tciíMf tíÜüi^ btxty^ ;

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;

A.6 Set declarations


A setdeclu-atkin hxs the form
462 A W L F E F E F B ^ S VAWJXL AFFSNDXA

Ui J^AV/ÍA-.VA*:
FL%»C A-.'JVMaÜas^i MY.VAÀY,?.,, Oil/tfoMéi,^ ;

in which <üjj'ihuits is a list of Klribul» optianally separated by co minas:

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);

fl%»c raacft - fltap[max_ítar];

computes in set r e a c h the transiti\e ckisuie of the graph represented by n o â a s and a r e s .

A. 6.1 Cardinality and arity functions

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 ) )

may also he wrítten

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.6 2 Ordered sets

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.

A. 6.3 Intervais and other infinite sets

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

rwoer. f * , S , k ) xícxtxek p&aooa*ata a-catorr izhs S


naxc:(/,.$) *i<nc. »itfc A - 1
noxr. (/) acAtauatoroí vsfcrtitudw * durai) ia>lcA
noxtw ( * , £ , * ) a^eaÉerA po%*i chutar auafcrs ^.«r^ça^arcxad
naxew(*,S) nr.fip)â£tcrsuâaínaxe(s, St
n*xr.w(/) .. r-çpa »ersua oí na >: r. o *

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

0Mnbar(/,S) ,/iharataorfS; 1 £ ) £ card<S».y ucc^er

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%

Tahtc- Á - 5 : IHjnclions o f « d e r e d seis.

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

lhe keywcrd i n L c r v a 1 mav be onúled.


T h : pxedefined mfinHe seis R e a i s aixJ I n L o g c r j : an: lhe sds o f ali flculins pciní numKis
anJ inlegefx, n.-specti\vly. in numeric cvdcf. The predefined mfinHe sets A S C I I , E B C D I C aixl
Di . c p l a y ali represem éie universil s d o f slring* and numbers from which members of any one
dimemkinil sei aie drawn; A 9 C I I K ordered by lhe ASCU colLUmg sequence. ÜIKTDIC b>- «h-
SECT CNA.7 Pt&ATJElHl CECLAPATCNS 465

EBCDIC coIIatine sequence. jmd D i s p l a y by t h : oslcring used in the d i s p l a y a n u i u n d (Sec-


tion A . 16). Numbers precede literais in D i s p l a y jmd axe crdered numérica! ly; literais an: sorted
by the ASOU colLUmg sequence.

A.7 Parameter declarations


Parameter declaraik»ns h i v e a list of optional attnbutes. optkiiully sejurated by commas:

{KiictMtt* rdtd ü/a&M*:


pararr. tu/mt aUas^ ktcUxJ/tXi* úürlbMéí^ ;

The tiunbuits may be any af the folkiwirç;:

aurlbau:
binary
i n caçar
flynfcollc
féb/> éxpr
ín léxpr
- êxpr
d a f a u l c éxpr

rdap:
< <- - -- !- <> > >-

The keyword i n L e g o r restricts Oie pirameter to be an integer; b i n a r y restricts it t» 0 cr 1.


If s y m b o l i c is specified. then the pirameter may assunte any Kterei or numeric value (rounded as
kw set membership). xixi the attnbutes involving c , < = . > = aixJ > an: di*ilk>ued: otherwitc the
p j a m e t e r is numeric jmd can only assume a numeric value.
The attnbutes involving compirison operators specify thit the parameter must obey the g j w n
relatxm. The i n attríbute specifies a check that the parameter fies in the given s e i
The = jmd d e f a u l t - attnbutes are aiulogous tci the correspondi rçg ones in set dcclarations. JUXJ
are mu tu ali y exclusive.
Recursiw definitions of indeied parameters aie alkrwed. so kii^g » the assigned values can be
computed in a sequence that only lefenmces previously computed values. For exampk-.

parair. oarob *n chooaa X* fn ín 0 . . X , X ín Q . . n )


- í f X - Q o r X - n t h a n 1 aioa â0fr2>ta-l,k«l] • co<r.brn-l,Xl;

computes the number of w a y s o f choosing n thmgs A A a time.


In a recursiw: defínitian o f a symbolic parameter. the keywcvd s y m b o l i c must precede ali
refeiem» t o the parameter.

A. 7.1 Check statements

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

£ha€X / htáéxifig^ : f ItJfM ;

liach c h o c k statement is evaluated when o n e of the commandx s o l v e . w r i L o . . s o l u t i o n . <r


c h o c k i s executed.
466 A W L F E F E F B ^ S VAWJXL AFFSNDXA

A.72 Infinity

1 n£ i n i Ly is a predefined p « n e i t ; it is lhe threshold abave which uppL*r bounds an: coitcsd


ered ahsent (ir.. infinito}. axxl - ln£ i n i t y is éie threshikl below which b w a r bounds an: coitcsd
ered ahsent. Thus given

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.

A.8 Variable declarations


Varuble declarations begin with the keywcrd v a r :

iti/iaN* ÍAY ÀV/ÍV.'.VA* :


v a r kom* üÜas^ Mt/fart**,^ ;

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

As with parameters. i n t e g e r restricts the varúble Io integer values. aixl b i n a r y re-stricts it Io 0


o r 1. The > = and < = phrases specify bounds. and the : = phrase an initial value. The d e f a u l t .
phrase ^iccifies a default f<r initül vahies that may be provided in a dati section ( A . 122):
d e f a u l t . *\d : = an: mutuallv exclusive. The = expr phrase is allowed only if none of the previ
ous altríbutes appears: it makes the varúbk: a defined witüjhle <A-8.1 >. liich s u f f i x sufmmr
expr phrase speeifies an initial value f o r a previous ly dcclared suffix sufmn k*.
If s y m b o l i c is spccificd. i n aaprimKialso appear and altríbutes requxrinc a numeric value,
surh as > = expt\ areexchided. If i n asxpr appears without r . ^ m b o l i c . the set expression xexpr
must be the union of inlervals aixl discrete sets of numbers. liither w a y . i n sexpr restricts the
v.riable to lie in xexpr.
The c o e i í and o b j phrases are f<r columnwise coefficient generation: they specify c o c f f i *
cients lo be p b c e d in the named constraint <r <tojective. which must have been previously declired
SECT C N A . 3 V A R / e t E CECLAMTCNS 467

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-

A.8.1 Defined variables

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;

where vrxpr isan expression mvolvmg the variables v .


A s thirçgs stanJ. the members o f C * e constraints. and w hase tumed an unconstrained prob
lem «ntc» a constrained one, which may not be a good idea. Se«xnc optkin n u b s t o u t to 1
instruas AMPL to elinüiulc the colk-clkin of constraints C . AMPI. does so by telÜng solvers thit
the constraints define the variables on their k-ft hind sides, so thit, in effect. these defined vari
ables become named common subexpresskins.
When optkin n u b n L o u t is 1. a constraint such as C that provides a definition for a defined
v.riahlc is calk*d a <irfinin% cons*mini. AMPI. dccides which variables an: defined variables by
scinnirçg the constraints <aice. «n <*der of their appearance in the model. A variable is ebgiblc to
bccomc a defined varubk- only if its decliratkin imposes no constraints <«i i t such as mtegrality or
bounds. Once a variable hxs appeared on the right haixl side o f a ckríirunc constraint. it is nc»
longer eligiik- to be a defined variable — without this restriction. A!MfL might have to solve
implicit cquitkins. Once a varubk hxs been nxogni/cd as a defined variable. its subsequent
appearance <«i the k-ft hind side o f what woukl otherwise he a definirçg constraint rcsuks in the
constraint beirçg treated as anordiiury cxinstraint.
Some solsers g i w spccúl treatment to linear variables because their higher derivatives vanish.
Ixirsurh sol\ers. it may he helpful to treat hrx-ar defined varubk-s specially. Otherwise. varubk-s
invohed in the right hind side of the equitkin kw a defined variable appear to solvers as ixinlinear
variable*. even if they are used only hnearlv in the right haixl side. By cktingGaussian ebmmation
rather thin conveyirç; linear varubk definitions expbcitly. AMPL can arrange kw solvers lei see
such right haixl varubk-s as linear variables. This often causes fill in. i r . , makes the problem less
spirse. but it may gise the solsers a more accurate view o f the probk-m. When optkin 1 i n e l i m
has üs ck-fauk vahie 1. AMPI. treats linear defined vambkrs in this special way: when option 1 i n -
e l im is 0. A M P L treats ali defined varubk-s alike.
468 A W L F E F E F B ^ S VAWJXL AFFSNDXA

A varuble decliration may hivc a p h r » e o f the fonn = txpr. « l i e * txpr is an expression


involving varâfck». Such a phrase mdi cates Ihil lhe varuble is k» be defined with lhe value « x p r .
Sudi definmg declarations alkiw some models to be writien more compactly.
Recogn i a ng defined variables is not always a good idea — it leads to a proUevn in íewer vari
abi es. but one lhal may be rncre nonlinear anJ Ihit may be moie expensive to solve because of k»ss
ofspirsity. By usirçg defining constraints (instead of usirçg defining variable dccliralktns) anJ
lunslatirçg anJ solving a problem both with $ s u b s t o u t = 0 anJ with $ s u b s t o u t = 1, one cin
see whether recogni/ing defined v m b b is wcrthwhilc. C)n lhe other hind. if fecognhâng a
defined varuble seems clearly wcrthwhile. defining it in its declmtion isoften rncre oonverienl
thin providing a sepirate defining constraint: in particular, if ali defined v a r á b b an: defined in
thnr declarations. one need not worry about $ s u b s t o u t .
One restrietion <*i definmg declarations rs thil subscripted variables must be defmed before
they are used.

A.9 Constraint declarations


The fcrmof a constraint decliration is

<tMfU/tfí*t dt < liUü&sH:


f AUB^AOR. t o / /ww AUOC,,, aMx, ¥
/ : - t*Mol <AwJ / / d a f a u l t i*i/kti _Aáal f
f z <rMVJ/ai*ttJf>/tiJJrA* f f Mètgix- kÜI M&uk*u f ;

"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:

<ttMi tato! «* >4» * isi <st:


tAfW < - tAft/
tAfW - tJlf)/
tAfW > - tAft/
<tx(» <- êxpr <- <*\(»
ttxpr >- êxpr >- <*\(»

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

optioiuDy preceded by acomnu. where .oifhamt is apreviously declanxl suffix.

A. 9.1 Complementarity constraints

For cxprcssing aimplementarity constraints. in atklifkin ki lh- f o r a » above. conslramt declara


tkins may hive lhe form

ÍIMW tíütís^ ktcUxJ/tXi* : ommx coff4>liamanr.fl ermiifi ;

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 »

tff/vi <- < - /j^V» c o o p liarr~ttr.fi t


«yvj >- *Âp/> > - txpji cooplarr~cir.fi t
t\{w 4 ooo$>loridnr.fi /AJVI < - <- « y v j
t\{w 4 ooo$>loridnr.fi /ajwi > - /.r/vi > - at/Vi

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,

For expressins malhemalical programs wilh cquibhríum conslraints. complementarity con


slraints may coexist wilh other conslraints and objeclivcs.
Solvers see complementarity conslraints inthe slaixJard form

tx(n oao4>loranr.fl lomr tsKHtd <- < - «w?*/ AvawtJ

A synonym ( A . 1 9 4 ) , _ s c v a r ( i in 1. . _ s n c o n s } , i n d k a t e x which variable. if any. comple


ments each constraint lh- soher sees. If _ z v z v a r l i 1 i n 1. . . m v A r s , lhen vxiable
_ s v a r l _ 5 c v a r t i 11 complemento conslramt _ s c o n [ i 1; othcrwise _ s c v a r l i l == 0. aixl
_con l i l is an « d m a r y constraint. The syrxinvms . c c o n n a m e ( l . . _ n c c o n s s } an: lhe nimes
o f lhe complementarity constraints as lhe modek-r sees them.
470 A W L F E F E F B ^ S VAWJXL AFFSNDXA

A.10 Objective declarations


T h : declamian af an objective is ara: o f

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 ;

oral may specify an expression in on? af th: falktwing fcrms:

éx-(ueískm-.

C • /Jl^Z

co_£oma

The t o _ c o m e forms permit «ihimnwisecacfficient generalkin. AS k t constraints (A.9). Specify


irçg nane af the above expressions is th: sime as Specify ing " : t o . c o n e " . Suffix iniiititiziiions
may appear as in com trair* dccliratians.
If there are mukiple objectiNVs. the one senl Io a saher can be set by the o b j e c L i v e com
maixJ: see seclkin A.18.6. By defauk.all abjeclivec are sent

A.11 Suffix notation for auxiliary values


Varúbles, constraints, abjeclives arai problems hive a v n e t y af assacialed auxiliary values.
For example, varâbles hive bouraJs oral reduced costs, and constraints hive diul values and slacks.
Sudi vahies are accessed as name . suffix, where nanur is a simple <r suhscripled varüble. can
straxnl objective <r problem name. arai . sufix is one af the pcrssiNhties hstcd in Tables A 6. A-7.
arai A-8.
T a r a canstraint the . b : x i y , . l b . a n d . ub values correspand Io a modified form af the can
straint If the canstraint invalws a sirçgk- mcquabty, subtracl the right hind side from the left, then
mo\e any constar* temts lo the right haral side; if the constraint invahes a ckiuble inequality. simi
larly subtracl m j ' canstint temts m the nückJle irem ali three expressions ( l e f t míddle. right). Then
the constraint has the f<mi Sb £ br»dy á uh. where Sb arai uh are (possiily infinile) canstants.
The following rules determine lawcr arai upper duil values <c . l d u a l arai c . u d u a l ) for a
canstraint c. The solver relurns a sirçgle dual value. c. d u a l , which might apply either Io
body £ Sb <r Io body £ ub. Taran equility constraint ( I b = uJ»), A ) ü uses the sign af c . d u a l
to decide. For a minimizstian probk-m. c . d u a l > 0 xmplies that the same optimum woukJ be
fouraJ if the canstraint were br»dy £ Sb, sa A M P L seis c . l d u a l = c . d u a l and c . u d u a l = (fc
sxmiLrh. c . d u a l < 0 implies that c . l d u a l = 0 and c . u d u a l = c . d u a l . Far a n u u -
mivalkin problem. the inequalities are resersed.
For mcquility constraints (Sb < uby* AMPL uses nearness to bound to decide whdher
c . l d u a l o r e . u d u a l cquils c . d u a l . If b/»dy - Ib<ub - b<xi\\then c . l d u a l = c . d u a l
oral c . u d u a l = 0 : otherwisc.r . l d u a l = 0 ande . u d u a l = c . d u a l .
Model dccliritkins may referente any o f the suffixcd values described in Tables A-6. A 7 arai
A-8. This is most aften useful «n new decliratkins thit are introduced after ane model hxs already
been Iranslaled arai sahed. In furliculir. the sufrues . v a i oral . d u a l are pravided so that new
constraints can referlo current optimal values af the primai and dual varúbk-s and af the objeclivc.
SeCTlQNA.il S U F R X NOTAT.ON FOR MJX L / « Y VALUES 471

asLaLus A M H . stitus < A . 11.2)


init current initial guess
iniLO initul müul guess (set by : =. d & t a . o r d c f a u l L )
lb current lower bound
lbO initul lower bound
lbl weaker lower bound fram presolve
lb2 stronger lower bound from prcsohe
lrc lower redured cost (for v a r >= lb)
lslack kiwer slick ( v a i - lb)
rc reduced cost
relax ignore integrality restríetion if positise
slack min(lslack, uslack)
ssLaLus solver st*us ( A 112)
s tatus status ( A l 1.2)
ub current upper bound
ubO initül upper bound
ubl weaker upper bound fram presolve
ub2 stronger upper bound from presohe
urc upper redun.*d cost ( f o r v a r <= ub)
uslack upper slick ( u b - vai)
vai current value of variibk-

T a b l e A-6: Dot suffixes for varâbles.

F o r a complemcntority constraint. suffix notation* like a x i a m i n i . \h.con\u<úm . b o d y . cte.,


are extended so thit conamini . LMifix and . R.suffix conespond to « w . t f r , . sufi* oxxl
contir2 . wfilx, respectively. aixl OMfirMmlanl|i<aMJlmjai . s l a c k (or the unodirned name)
stinJs for a measure of th: exlent to which the complcnicrtarity constraint is sitisfied: if amar %
aixl constr2 cach in volve eme inequility. the new measure is

mi mamar, . s l a c X , ttmm l . fllacX},

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

miniéjpti-éxpti, i f /J^WI > - éXfiri


min { é j f n - / J 1 J V 4 ) i f < - M/V)
-aba (AI/V 4 ) i f AI/VI < /JIJVI < « y v )

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.

A. 11.1 Suffix declarations

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

.astatus AMFl. s t i t i M A . i l .2)


.body curxml value o f cxinstroim body
.diniL currentinitial guess for dual variable
.dinitO iniCul müul guess fcrduil varubk* (set by : =. diU. or d e f a u l t )
. dual current d ml varubk-
. lb lower bound
. lhe l b f<* solver (adjwted for fixed variables)
.ldual kiwvr duil value (for b o d y >= lb)
. lslack kiuer slick ( b o d y - lb)
. slack mándslack. uslack)
. sstatus s o l v e r s U t i M A . i l .2)
. st_a t u s status (A.l 1.2)
.ub upper bound
. ubs ub h * solver (adjwted for fixed variables)
.udual upper duil value (for b o d y <= ub)
. uslack upper slick ( u b - body)

Table A-7: Dot suffixes for com trai nts.

. vai cirrenl value o f objecti %e

Table A4fc: Dot suffix f<r objeclives.

Mffl x d* d üiaíkM*:
flUCClX KtíHV tiüas^ a n r t b M à ;

Optonal attnbutes of suffix declarations may be SCpWtod by commas;thesc attnbutes inchide

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

A.fltacufl - i f x.acratufljiuiri « 0 than x. A A t a t u A a l u a jr.afltatufl.

When option astatus_table his üs default value. .r.astatus = 'in' when


x . a s t a t u s _ n u m = 0.

A.12 Standard data format


A M P I suppoits a stindird format Io descrihe the sets and parameter vahies that * combines
with a model to yickl aspecific opti mi/ol kin problem.
A dati section consrsts o f a sequence of tokens (literais and strmgs o f prmtirçg chiracters) sepa
roted by white sjuce (space*. tibs. and newhnes). Tokens inrlude keywcrd*. literais, numbers. aixl
the debmiters < ) l | : , ; : = * . A stitement is a *equence of tokens termmoted by a
semicolon. Ccmiments may appear as in decliratkins. In ali cases, arrangement of dita mio neat
rows aixJ cohimns is for human reodibilny; AMH. igncie* formattmg.
A dita sectkm begins with a d a t a command and ends with end of input cr with a command
thit returns to model mode ( A 1 4 ) .
In a dita section. model entities may be a*signed values m any converient arder, independer*
o f their ceder of declaration.

A. 12.1 Set data

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

<fhy<t t/by<i ...

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.

A. 12.2 Parameter data

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:

po/om - düiau ü.vmt ki :


parair. (xuam-nam* {tü/tim-dtfiMÜ : - (kíj am-í{M< {tü/c/m-spn ... ;

(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:

I «VlHI ffi • ÀVrtt^ / ff!\ffi • AV rtt, . .. ^


iV füffi • tirtW'
ohy<t

"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 • - < * - :

l-kfodtt l-ktadtf i-k*ad*i


ntM-tothtl emry entry entry
KM-lobtl éniry emry entry

iktaèêf.
: ok)tci ok)tei ...

<fhy<t ohjid ...

twmk*/
MUl/fg
ééfàttij-symbol

A s in s « t stitements. Cie notation ( L r J means Uunsposr\ il nuphcs a 2 D table. and a : after


itis optional. Il remains in effect untila new lemplate appears.
A lahle may be gi\en in several chunks of columns.
Kach eniry'* r/m1'Sabei i heaJer entries an: suhstituted kw * *s and : s m lhe tempLue to
define a set member. anJ lhe pirameter or varuble indexed by Ihrs set member is assigned lhe
value specified by lhe entry. The entry may be a number íor varúbles and fer jurameters lhal Iake
numerieml values. or a string for variables and jurameters declired wíéi lhe altribule r ^ m b o l i c .
An enüythxi is lhe defaull symbol (see bckiw) is ignored.
The second ferm o f parameter dati siateiiienl provides for the dcfmition of mukiple parame
lers, anJ also qptionaDy the set over which they are indexed:

(ki/om - diMa-ai H/nai *:


pararr. pa/am-d^faoto^-.
(Ki/aM-itamt paiam- AY.VW ... :- KAW-ÀVAI ITFAW-ÀVM ... ;

parair. param-éáfànto^-. uhnamt-.


(Ki/aM-itamt pa/am-KOMr ... : - kaW-àvai irttav-Avm ... ;

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;

(without a symbol) pops the stack.


Parameters hiving three or more Índices may be given values by a sequence of 1D and 2D
( A b . one er nwre for each slice of nondcfault vahies.
In summary. a param statement defining one indexed parameter stuls with the kcywcrd
p a r a m aixl the rume of the parameter. followcd by an opüonal default vahie and an optiorul : = .
Then comes a sequence o f 1D and 2D param tables. which are similar to 1D and 2D seL tibles,
except that templates involve square brackcts rather thin jurentheses. 2 D tables cortam numbers
(cr. fer a symbolic p n m e t e r , literais) rather thin V s aixl - s, and II) tibk-s cxirrespemding to a
tempLUe of k **s contam k + 1 rather thin k cohimns, the list beèlg a column of numbers or
defauk symbols ( . *s). A speciil í<mu the keyword p a r a m . an optioiul defauk vahie. arxl a smglc
(untranspcrsed) 21) tibk\ defines xexeval parameters iixlcxed by a common set. aixl another speciil
form, p a r a m folkiued h) the pirameter name. an optional : = . arxl a numeric value, defines a
scalar parameter.
Variible arxl constraint namcs may appear m dati seclkins any where thil a parameter name
may appear. to specify initial vahies fer varubks arxl fer the duil v m b l e s associated with con*
straints. The rules fer default vahies are the some as fer parameters. The keyword v a r is a syn-
onym fer param in dati statements.

A.13 Databaso access and tables


AMPl/s L a b l e facihty pemiíts e*)íiinirçg dati irem and returriiç dati to an eUernil médium,
such as a datibase. file. or spreadsheet. A L a b l e ekclaratieii establsshes cormectems betueen
columns eif an externai relitktnil table arxl sets. parameters, variibkrs and expressiems in AMPL.
The r e a d L a b l e arxl wr i L e L a b l e conunarxls use these cxmneclkins to read dita values into
AMPL from tibkrs arxl write than b a d . AMPL uses table handíers to impk*menl these connec
tkins. Builtin table haixlk-rs permit rcading and writiiç " . L a b " and " . b i L " files to sa\e arxl
restere values and experiment with AMPI.'s table facihtes; to access dilatuscs arxl spreadsheets. at
478 A W L F E F E F B ^ S VAWJXL AFFSNDXA

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:

u/.lo^ Ikey-coS-sptc, y-<tfls{*<, ...]

The optionil sei ia phrase hxs the form

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

íé\ "itamt " «AVAV < oi-itam*

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

ktíUxtoX ( /\(»<<fi <i<t< , t>JH-<u , ... )

in which expr-cal de.se hxs the form

txpf f " «VAWÚVHÍ* / A» •ata

An other speciil syntix permits iteratmgdati columns:

foíUxtoX < dMü-*{/*< , daía-spK , ... >


SEC7CNA.14 ODMJAND LAN3UAOE 0 \ € R V EV/ 479

The Ia*cr may not be nestcd.but may contai n the fonner.


After a table declaration, data accem is dane with

road c a b i a JMbu/tp.'^ •
w r i c a c a b i a /abb/wmt Mbu/fa',^ ;

which refer tuck tci lhe informatian given in the t a b l e declaraixin.

A.14 Command languagc ovcrvicw


A M P L lecognizes the c a u m i n A isted in Table A 9. Commands an: rcil pari o f a model but
cause A M H . te» act as describedbekiw.
The command cnvironment nxogni/es two modes. In m o M mn<ie% where AMPL staits up<*i
invocatian. à recognizes mcdel declarations ( A 3 ) and ali of the commMlck described bekiw. t.lp<*i
sccing a d a t a statement it switches to data mndt% where only dita mode statements ( A . 12) an:
recqgnized. It returns to nicxlel mode upon encountering a keyword thai canrcit begin a data mode
statement or lhe end of lhe file. Commands other than d a t a , e n d . i n c l u d e . q u i t j i d s h c l 1
also cause AMH- to enter model mode.
A phrase of the form

í 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ê

The cccnmar>±: conunanJ is anakigous lo i r x r l u d e . but is a statement anJ musl be termi*


nJed by a semicokin. When a d a t a <r conmandr. ccmunand appears in a c<«np<»unJ conunanJ
(Lê., lhe body of a loop or the t h e n or e l . e e pari o f an i f conunanJ (A.3C1.1). cw simply «n a
sequence of commands cncktscd in traces}, it is executed when lhe flow o f control nraches it.
instead of when lhe campounJ oammand is being read. In this case. if lhe d a t a or oommanâs
command does not specify a file. A M H . reads commands or data from the current input fik- until it
encounters either an e n d conunanJ or the end of the current fik".
For i n c l u d e phrases as well as m o d e l . d a t a . anJ c o o m a n d s ccmunand*. fikr* with simple
nanes, c.g„ ncit involving a siash </>, an: soi^ghl in direciones (folders) specified by apüan
a m p l _ i n c l ude ( A . 14.1): oach nonblank hne of $ a m p l _ i n c l u d e specifies a directcry: if
$ampl _ i n c l ude is emptvor entivefy blank. files an: sotçhl in the current dâectcay.
The option i n . c e r t p r o m p L (default ' <%d> • > specificsan ínsertum prcmipt lhal mimcdiately
p c c e d » the usual prompt for input from lhe standard input. If pnrsent. %d is lhe current inseri
460 A W L F E F E F B ^ S VAWJXL AFFSNDXA

czll âwoàe Lnfxtfcd íu-xuixi


cá dxj^rc curou diicat«\
cíwcX pcríecn jII eíiacX c o m u ^
ClOfla ctotcále
carirandfl «cJJ aüd Lttcifrct cccrcria^*. íircna file
data >v»*chtoiKa atxfc. cçtxculK tactude file acáe^ts
dalata ddetc ^xxldc^tâfcN
diaplay f o . * rncdd c^diks aâd CApre ako c f l u l i f l p l a y aãd d i a p l a y
drop dkop a occrva-auí cr e t ) a ove
c^J 141U írcvn ixrrcâc í^fcf fik
amriron ms e B W M i K M fcr a prcfcfcm i^xa^ce
axit cut A&Vi >» th >*aft-> vakuc
Oio» CAfusrsxo of modd c m i e .
fix frcc/c a iaii£>lc jl t . aarcai vakuc
ircluda laeluie file cctitc .as
lat dxj^reiiita vakes
load k-uid> Aiaa: íuactto fatcii)
rrodal vttichio oxxld aicde: cfcictiull) uclule file octitcãtt
objactiva xácct x-i c í ^ a u c «obe cçctru A*d
option *s or divfdaj c f c r a \ u k »
print fO./ axxid e^CáKS aâd CApre.sfc.~tir. L-al«mjncd
printf fo./ axxid c^cáKS aâd CApre.sfc.~tir. ir^uncd
problacr. deíiac ccnw xch to a /u j«:d ftfòlcm
purga aiíxld câocie.
quit KTCúÀftC AMPL
road lüc ufcifrccnafile
road t a b l a tokc Lçmírcvn a dita table
radaclara dxi^cdfdir^ictioí cacrv
raload icL-uddy^iatfc:
r«nova KBttYC frfe
raaat ic>ci vfxxilíAl cauae. to ibem- íicial víate
raatora cAfc» a dropcoamiad
fií»ll ULttfxor» cs:4*: to c f o j t syMcaitotf-jac o M u a ^
flíkaw Ofcy» Aimes of aiixld c.aucie.
flolaxpjcid Ofcy» CAfUãrxti a. sccn by soba*
flOlUtiCtt «aubV: t a k c w . íííuxna saber
flolva xssdcurcãiiaxaâcc toa%cJ*tr o^d rctrfc:*e*^cttti
up&ata aliem ufxiio^ dita
unfix M d o a f l x axrcnaiJ
unload dy^imfc: luâL-Cfc.-ti btci»\
writa wr*c out a prcfcfcaí laaaaec
writa tabla rtTí c dita to a dá a table
xraf >t»yn dcpcadtácie. aavti£

Tahtc- A-9: ComnunJv

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. 14.1 Options and environment variables

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.

A.15 Rcdirection of input and output


A n optional rrdSirciion phrase can bc used wilh a variety of AMH. commands lo capture thcir
output in a fik- for subsequent processing. It appbcs Io ali forms of d i s p l a y and p r inL and also
lo nuisl other commands lhal can produce outpul surh as s o l v e . o b j o c L i v c . £ i x . d r o p ,
r c s L o r c . and e x p a n d .
A rednvctkinhas oncof lhe forms

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 ;

ckises and d e l e * » filtnanir.

A.16 Printing and display commands


T h : d i s p l a y . p r i n L . aixl p r i n L Í «mimands prinl artoitrary expressions. They hive the
forms

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

.UV.V 1 AVAW »tJix»)M )

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/.vcd A:a .rui :*:< sjcu

%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

%f «ixM:- pnoc rasa 11 cai ^-pcaa


U dil^lC-pTCC M-Xi íkuQú^.fCaX ClfCOC^tAil àCtltkX» MBg a
%E dil^lC-pTCC M--0 íkuQú^.fCaX ClfCOC^tAil àCtltkX» «tOg E
«ixbk-prccMDú íkut i ^ / f x a x watç \ t or
%G dxMc-prcc fkx* i ^ - f c a x LM^ % f or % E
%% ftceall

T a b k A• 10: Con\ersion speci ficai kins i n p r i n L f fornuts.

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 )

when: rxpriiM is a nonempty. oomma separaled list o f expressions. The d i s p l a y aimnunJ


pnnts scalar expressions and seis individuallv. anJ pirtitkins indexed entities into groups having
the same number of suhscripts. then prints each group in its own tibk- cr sequence of tibk*s.
By defauk. lhe d i s p l a y command rciunds numeric expresskins to six significar* figures, but
this can be chxngcd with the options d i s p l a y _ p r c x r i s i a n or d i s p l a y _ r ou rxi. as described
bdow.
Severa! options wherse rumes end with _ p r c c i s i o n control the precisicoi with which
fkiatirçg point numbers an: eonverted to printaUe values; positise values implv rounJmg m thit
manv significam figures. aixJ 0 or other values miply round ing to the shoitesl decinul string thit.
when properly rounded Io a nuchâie number. would yield the number m queslion. lí set to integral
values. $di sp l a y _ r o u n d anJ $ p r i n t _ rourxi o\erride $dissplay procicion anJ
$pr i n t _ _ p r c c i s i o n . respeclively, and simiLirly for the anakigous flpéans in Table A l i . For
exampk*. $ d i s p l a y _ r o u n d n causes the d i s p l a y command to round numeric values Io n
pbces past the decinul point (or Io - n pbces before lhe decinul point if n < 0>. A negative pre
eisktn with %£ fornuts as fer the p r i n L command with p r i n t _ r o u n d negative. ()pticois thit
affecl printing include those shown in Tabk- A-11.
484 A M = L F E F E F E N C E WAMJ/C AFFENDXA

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

Ô B ^ C t i va_pr ac i A ien p a w ü fcrctojccoic vakc dr-pli »ed b> volver


ií áixwcnx o m i al^cec coluna* ftrcn djvfii.%
o m l t _ S « ro_r OWB if acoicio. ccn* al^ceo rcr»% írccn dr-pli>s
o\itput_pracifliem p r e e u acatue.* cificvMú ( . n 1»file*
print_praciflion procroxa for p r i n t ccvruruad wfaea Spr int^rourxl a * aunene
print_round piiccvpuaòccLYul i:r p r i n t oxnauad iorc«_aJ
print_fl%*>a trator vep^auríer p r i n t ccvruruad
aolut i o n _ p x a c i a icrn preerra fer a o c r flolutlcn ccuuuaJ wfaea $flolution_round
fcaot—NITIR
flolut plicc* fua (Sccmilfcroolva cr *> l u ti cm oxnauad iorc«_àJ

Tal4rA-ll: Optumsthit contrai printirçg.

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.17 Rcading data


The r e a d command provides a w a y of read mg unfcmialted d i l a inlo A ^ I P L parameters arxl
olher componcnK wilh s\ntix similar l o lhe p r i n L conunarxJ:

tua d / AT^AAT^ : f a/^liu Hélneêkm^ ;

As wilh p r i n L , lhe optioiul indexing causes lhe r e a d o o m m v i d to be e x e c U e d separately for


each member of lhe specified irxlexir^g s e i
The r e a d command treals its input as an unformattcd series of dita vahies. separatcd by white
sfttce. The t i ^ l i a is a ccnuiu sejurated lis! of arguments thil specifies a series o f componcnls to
which these vahies are assigned. As wilh p r i n t , lhe is a comma separated lis! of o r g r ,
which may be arr,- o f
SEC7CNA.18 WCC€LN300VV/*C<S 485

a/f.
COKyOfiêM-Hf
bcdttittx+W «m(NsWAWf
( OfgUli )

The c/jmpnntnlr*f musl be a rference to a possfcly suffixed parameter. variable. cr constraint. or


a suffixed problem name: * is meaninglcss to read a vahie into a set mcvnbcf or any more general
expiesskm Ali indexing m w ( be cxphcit. fer example r o a d ( j i n DEST} demand l j 1 rather
than r e a d demand. Values an: assigned ( o <v j p m lhe order lhal they me read. so Ialer arguments
can use values read earlier in lhe same r e a d ccmunand.
If nci nrdvtctian is specified, values an: read from lhe current inpul stteam. Thus if lhe r e a d
ccmunand was issued at an AMH. prcmipt. eme types lhe values at subsequenl prompls until ali o f
the digito enlries hive been assigned values. The prcmipl changes fremi a a r o l ? tuck to ampl :
when ali the nceded mpul has been read. If instead r e a d is mside a script file thai is read with
i n c l u d e cr c o o m a n d s then the input is read frcmi lhe same file. beginning directly afier lhe :
Ihil ends the r e a d ccmunand.
Most o l e n lhe mpul lo r e a d lies m a separate file, specified by the OftÍQflÜ irdir*cãian; its
ferm is <filmam*.. where fittnamr is a slring <r pouenthesizcd slring expression Ihil identifies a
file. Multi pie r e a d ' s can access lhe same file. in which case each r e a d sloits read mg lhe file
where lhe prevkius one left afF. To f a c e readinc tc» siajt at the beginning *£iin. c i o s o fUmam*
before te reading.
If a script isfc>ccmtiin a r e a d ccmunand lhal n:ads values lyped interactiwly. the source of lhe
values must be redirectedlo the stanJard mpul; specify mg a - (minus s$n)as the fittnam* does so.
This is mcrsl often used to read interacti\e responses fremia user.

A.18 Modeling commands

A. 18.1 The solve command

The . s o l v e ccmunand has the form

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

$ob j e c t i v e p r e c i s i o n significai* chgits. In reading th: solution. A M H rounJs the primai


v j i a b l e s t o $ s o l u t i on_ rourxi places p n t the decimal point if $ s o l u t i o n _ r o u n d is JUI
integer. <r t o $ s o l u t i o n p r e c i s i o n significai* figures if $ ! » l u t i o n p r e c i s i o n is a
positive integer; the ck-fauks kw these options imply thil noroundirçg is performed.
A vxiatile always has a current value. A variable declaration <r dati section can specify the
initiaJ vahie. which is otherwise 0. The option r n s « t _ i n i t i a l _ g uns s n s cantro h the initul
gue-cs oon\eyed to the soher. lf option r c s c L _ i n i t i a l _ g u e s s e s his its default value of 0,
then the current variable values are conveyed os the initul guettf. Settiiç option
rosot_ initial_guossos to 1 causes the crigiiul initial values to be sent. TTius
$ r e s e t _ i n i t i a l _ g u e s s e s affects the starting gue-cs for a second s o l v e command, as wcD
AS kw aninitial s o l v e command thit follows a s o l u t i o n command (described below).
A constraint ahvays his an associited current duil variable value (l.agrange multiplier). The
inital duil vahie is 0 unless atherwise given in a dita section or specified in the constrainfs decla
ration by a : = inisinl jhuii or a d e f a u l t inilial_dikil phrase. Whether a dual initul guess is
con\eyed to sahers is govemed by the option dua 1_ i n i t i a l . g u e s s e s . Its defauk vahie o f
1 cjuses A M H to pass the current duil variables ( i f $ r e s e t _ i n i t i a l . g u e s s e s is 0 ) or the
aâgiiul initial dual variables to the solver; if $ d u a l i n i t i a l . . g u o s s o s is set to 0. AMPI. will
o mil initul vahies for the dual varúbles.
AMPl.'s presolve phise cximputes two sets o f boureJs on variables. The first set xefbcts any
shirpenmg af lhe dechred boureJs implied by ehmxnated constraints. The other set incorporates
shirpenings af lhe first set lhal presolve deduees from constraints it cannot eliminile from lhe
psoblem. The problem has lhe « m e solutions with eilher set o f bounds. but solvers thit use
acthe set strategies (such as lhe simplex method) may have rncre trouble with degcneracies wilh
lhe sharpened bounds. S d \ « n often run faster wilh the first set. bul sometimes run faster with lhe
second. By defauk. AMH- passes lhe first set o f bounds. but if opüan v a r _ b o u n d s is 2, A M H .
passes the second set. The . l b anJ . ub sufíixes f<r variables ahvays reflect lhe current sctting o f
$ v a r _ b o u n d s ; . l b l a n J . u b l are for lhe first s e i . I b 2 aixJ . u b 2 for #ie second s e i
lf the output style is m. A M P L wriles a conwntonal MPS file, anJ lhe vahie of (ipticm
integer m a r f c e r s determines whether integer variables an? indicated in lhe MPS file by
•XOTORO' and ' 1NFHND' " H/UQCHR' hnes. By defauk. $ i n t e g e r m n r k e r s is 1. ciusii^g
these hnes tabe written;specifyíng

o p t i o n incaoar_rr^i:Xarfl 0 ;

causes A M H . lo amit the 'MAR2CKR ' lines.


The option r e l a x ^ i n t e g r a l i t y causes i n t e g e r and b i r v a r y atributes of varúbles to
be igmred in s o l v e anJ w r i t e commands. It is also possible to contrai Ihrs by setting lhe
. r o l a x suffix o f a varuble (A.11).
By default values o f suffixes of type I N or I N (X/T ( A . l 1.1 > are sent to lhe soher, and updated
values for suffixes o f type OlTT <w IWDlfT are obtaincd from lhe soher. bul lhe senJing anJ nxeiv
irçg of suffix vahies can be controlled by settiqg option send s u f f i x e s suitibly: if
$ s e n d _ s u £ f i x o s is 1 <w \ suffix values are sent to lhe soher; and if $ s e n d _ s u £ £ i x o s is 2
or X lhen updiled suffix. values an? nxjuested from lhe soher.
Whether . sstatus vahies ( A . l 1 2 ) an? sent to the soher is detemiined by options
s o n d _ s u f f i x o s and s n n d s t a t u s e s ; setting $ s e r x L s t a t u s e s to 0 causes .sstatus
values not tabe sent when $ s e n d _ s u £ £ i x c s p e r m i t s sending other suffixes.
Most sahers supply a value for AMPl.'s built in symbol ic pmmcter s o l v e message.
AMH. prints the updated s o l v e . m e s s a g e by default but settirçg option s o l v e r msg to 0
SEC7CNA.18 WCC€LN300VV/*C<S 487

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.

arxl its default vahie is 3.


When compk-mentirity constraints are present. the system o f constraints is considered sqmtr
if the number o f "inequality complemento inequality" constraints plus the number of eqiutkins
cquals the number of variables. S<anc complementarily solvers require square systems. so b)
defauk ÁMH- wams ab<iut nonsquire systems. This can be chinged by idjusting optiem
c o m p l _ w a r a which is the sum of

1 » a a l í c u ax*«juirc ccurpleârai jrty


2 aad rçjrd&xaNjuire ccvrplcxcajrsy \\>tcar. ufcusfcfc
4 iWc?.rd cipbc* júxcha^FN oi vjtxèAcs IO EQUIRAAN.

A. 18.2 The solution command

The .sol uL i o n command has th- f<rm

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.

A. 18.3 The write command

The w r i L c command has th- form

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.

A. 18.4 Auxiliary files

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

Ke> Pile Dampoca

a jflufe.ad) c o M i a i a i l e d to cfcjecn »e vaLe.


c íMth.co 1 AMPL aíme. cá %.rxibte. tfae sotversee»
a uuh. a n v eatYOüúUãi(anuâby a flúlw e c a m i a d )
f uuh.fix «ai'&*lcsclLrii.^£cd ivtnthe fwtòlcmtcQiuvüheB- «aludais kúútoa
P mh. a p e MESJOS • • ^ o . " 6le í c c c u p u tf>1e rr.
r inift. r o w AMPL Aime. af aadcfejccoic* lhe solver %cc%
a ale ec^cva-jisés d u u u i c d f n x n lheproèiem
u inift. u n v uâuwed

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.

A. 18.5 Changing a model: delete.purge. redecl&re

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 ;

ddetes each n a m t aixJ ali itsdirect and irelirect dependente.


T h : statement

radaclara «t/Ar» d<<ki/ciik>* •

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:

are funccíon minimizo parair. aac suffix var


ehaeX ff-axíir.ira no<ia problam flu2>)act co cabia

Rcdcclarations that would cause c â c u l i r dependencies an: r e j e c t e d


The c o m o — i d

dalaca ehaeX

ddetes the /Hhcheck. while

radaclara eàaeX * : ... ;

redeclaies the /ith checfc.


SEC7CNA.18 WCC€LN300VV/*C<S 489

4.18.6 The drop, reatore and objective commands

These commands ha\e #ie form*

drop «ssup•<»•<*>) /rtH/rttk/rt ;


< fStt.J -ot -oh) néUtakm^ ;
ôbJâCCÍVâ ohjtíti -/Wéttt

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.

A. 18.7 The f i x and unfix commands

These commands ha\e the forms

fix i/hUjJ/fg^, f :- txpj f nãUêetiím^ ;


unfix ."AV.VA ÀV*.»< itif/wM* I éxpr f rtàbtalm^ ;

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).

A. 18.8 Named problems and environments

The p r o b l e m decliratk>nrcommand has three funetions: dcclaring a new probk-m. makirçg a


pt*vious)y declired prabkm current arxl prmtirçg the rume of the current probk*m (in the form o f a
p r o b l e m command establsshing the current problem).

problam ttom/ bhkAJitg^ Mlfix-KvütetozMkMU^ : kmSUl ;

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/ ;

males nornt (a previously declaredpr(4ik'tu> current orxl


490 A W L F E F E F B ^ S VAWJXL AFFSNDXA

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 .

A. 18.9 Modifying data: reo*t, updãte, let

The r c s c L «mimand his se\eral ferms.

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

A r o s o t d a U í oommand forces recomputilkin o f ali = expressions, and r c s o L d a U í p,


even when p is declired with a = expresskin. forces recomputJkin of n a d a m funetions in tfie =
expiem ion (and o f any user defined functkins in the expiem ion).
Prohlenis (inrluJmg the cunenl o n e ) oiv adjusted when their indexing expressions chance,
except that prevkius explicit dropárestore and f u t a n f i x commands rcniam in e f f c c l . The r c . c « t
p r o b l e m command cancels this tn:atinem o f pievious explicit drop, restore. f u , and unTix c o m
mands. andbrmgs the problem to its declared drop'fix st ale. This command has the f e r a »

raaat problor. ; appStts toík* < u n * M ( n M t m


raaat problor. (ntfb^/mt [suhurifn;

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 ;

gunts update permimiononly to the entities in ntinvr Da.


The l o L command

lat Atd*júfty^, n<m* : - éXfi/ ;

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

«ar AVI.VxJ ftfi,^ AYJVM/. Utfflx : • éXflf ;

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.

A.19 Examining models

A. 19.1 The ahowcommand

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:

eii. . . --> chacXfi c... --> confltraintfl


a... --> anvirorifcantfl f... --> Z\31C tiCflfl
o... --> objactivaa
pr... --> probiacra p... --> paraifratara
flu... --> flufSixafl fl... - - > sarja
t... —> tablaa v... --> variablafl
492 A W L F E F E F B ^ S VAWJXL AFFSNDXA

A. 19.2 The xref command

T h : ccmunand x r e f shows entities thit depend directly or írxlnvclh, <m specified entities:

x r a í ktmUu /fti) tt< AV<%*i ^ ;

A. 19.3 The expand command

T h : expandcornmand pnnts g m c n l n l construiu* aixl objeclives:

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

flolaxpamd tokttoktmüsj néènttítm^ ;

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.19.4 Ceneric names

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.

A. 19.5 The check command

The command

chacX;

causes ali c h e c k statements to be evaluated.

A.20 Scripts and control flow statements


A M P L pio vides stitcments similar to contrai f b w statements in conwntianal programming lan
guages. which make it possfck- to write a program oi statements tobe executed automatically.
SEC7CNA.20 S C R P T S M D OONTFOL FLO// S T A T W E N T S 493

_nvara a^rtererf v.rxihlc%iaeineãi3xxsel


_n<»nfl a^rtererf axvauiLXs u cmcai axxiel
a^rtererf C*»/:CD u c « M axOd
_varnair/a { 1 . . .jurarfl) jxiovscrf t a b l e s laeineãiaxxSel
_<!c«nair/a{ 1 . ._xicona) iuincscd
nair*» { 1 . . . j i o b J a) jxiovs oi ctyco un u eureáá ax>id
_ v a r f 1. . _ n v a r f l ) a * toe s ar&Ales u curvai axOd
f 1. ._ncotia) ícfcccrarjxxw ia eurac n o d d
ferefejeeme* ia enrede modd
_pwts set cá uU doe iited çkmjmq
_SE?S cá ali declired set Aiaie.
^icrfulldeclji-ed manes
_CtKS >ci cá ali declired occ^clii* suanes
_OBJS cT ull dechi-ed cfcjecn *e aiavs
_PK>BS cT j 11 dechi-ed pretten ô i a - s
JEWS CT J11 declired OFT^P—IFLM AÜTICS
SCI c4jU dcc iiicd uvY-defocd fiJttCkX*.
âcjrÉeroí axr^âreâunu cccrfi-ji^ tcfccc prescJ »e
.eoonnaiK» f 1. ._ncccnii) Aimcs af úcu-plcrcãuix) cctíra-jucw
á _ » c v a r í/1 > a _ f l v a r íftcvar [J]] Ti]
_flrú>varfl âcjrÉeroí tu-XftVi ( U l l
âcjrÉeroí c i x w r j i ^ aíieiftcsoKe
_flnivarfl âcjrÉeroí /cúceil uce^a- v j u b t s (eAcftuli^bi£xrie%i
âcjrÉeroí
_flnlne âcjrÉeroí hac^- âcmcrk occraeiu^
ituxtocrcÁ oxnpl oxarstt^: _ » n c o í m f l - _ í í n l e e * _ f l n n l e e
auatoerorf âc^hâc^- eccrarui^
AMrfcerctf âcotue^- ^emerk axscaeiutw
âcjrÉeraí ^XÍIIÍ:^-
_flm'.v auatoerorf âc^hâc^- v^xibks
_flnzecmfl âcjrÉeraí a-craeiuc iaoctaia j u u »
_flnzob}fl ^xixrcÁ ££idicác âoaarrcüw

A.20.1 The for, repeat and if-then-elae statements

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

Ií laopname is specified. b r o a k and c o n t i n u e apply to the named cnclcrsing ki<ip: atherwise


they applv t o the immcdiately cnclasmg loop. A b r o a k termirutcs the kiop. arxl c o n t i n u o
a w « its next iteration tci begin (if pcrmittcd by the optkuul irritai and fmjil opl-while cliuses o f a
r c p e a t loop, <r by the indexing o f a í o r kiop). Dummy indexes from indexing may appear in
cmd in a í o r loop. T h : cntirc index set of a í o r loop is mstantiitcd bcfcre startirçg execution o f
the loop, so the set o f dummy Índices fer which the kiop body is executed will be unaffccted by
assignments in the kiop body.
Variints o f b r e a k ,

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:

t^^r. ... ( . . . ) b no f i n a l c c n d i t i o n or flacricolcn


if ... tftan ( . . . ) * no « I f i a e l a u n a

A M P L hxs three pairs o f prompts whise text can be chaqgcd thrcii^gh option settirçgs. The
defauk scttings are:

option coulptocrptl arr.pl:


option cttAptc(t^t2 ' \ q 1?
option datapro«rç>tl ' a n p l d a t a :
option <Utapro<r^t2 ' a n p l d a t a ?
opt i o n protrçt 1 • jtr^>l: * ;
option prorrçpt2 'Jtr^l?

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

A.20.2 Stepping through commands

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:

atap execute ÉK acu ccutmiadL cx* cccnxut»**


flXíp siup ifae ácu ccutmiadL o r * c c c n x u ^
noxr. iftbe acAt ocvrunaad aâ i f A ^ c h e cclccfa^ axrunasal execae tbe cíâxc
axrçtt-ad ecomiâdL ora c c o m i i K bcfcce jaoppiagapáa
(u&levw tfac oco-p.-«_ad c o m a a d xvelí speeific. co.arrJcidfl - ; \
CCflt execute c-sol lheeadof ali aarcàiK aested úcvnpe«_ad axrunasal*
jttfae

A.21 Computational environment


A M P L runs in an operatirçg system environment. most oíten as a starxlakine program. but some
times betind the scenes in a graphical user interface or a larger system. Its beiiaviar is mf)ucrx-ed
by values from the externai environment. and it can set values thit become part of that etiviran-
ment. The parameter p i d gives the process ll> o f the A M H . process (a number unxjue amorçg
pxicesses runnirçg onthe system).

A.21.1 The ohell command

The .nhel 1 command provides a tcinporary escape to th- Operating system, if such is permit-
ted. to run commands.

fite 11 'etmmMJ-li/t*' rtâhtttio*^ ;


fi2« 11 /«ÜfêtÚOK^ ;

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.

A.21.2 The cd command

The c d command reports cr changes AMH/s wcrkmgdireclcry.

cd ;

c d rttt* -áiit<h>r) ;

l h e parameter _ o d isset to this vahie.


496 A W L F E F E F B ^ S VAWJXL AFFSNDXA

_anp 1 _a lapa a r. i CM elq><*d vtíccc«i. )*k:e ihc ofÉke A & ü prcec*.


_anp:_ayB icr/a >>MemCPI* v i o i l . u v : d b > lhe A&ffi fuccv.
_ a n p : _ u » a r _ t : iifca o e r C PT vx*otadt uv:d b» AMR. pnxe«v»tNdí
_anpl_t:irfra _arr4>l_flyflc%»fr._cícr«a -t _aff4>l_uflar_tiifca
ha 11 _ a l apn r. í ma eUp-ed vxccdk fccav»* irceai >&eU axnaxiad
I l_flyfl tarr^t irr*a >>MemCPI* sazoadk uvrdb» m o * icce^c >âeU ecomiúd
1 l_uflar_tirfca BJírCW y x c o l . M d bv moi4 e c o a ^ l l i O M u a l
_ f l h a l l _ f l y f l t a c r ^ c i f r ^ -t _ f l h a l l _ u í i a r _ t
_ f l o l v a _ a l a p f l * l _ r . irr»a CÍf*CdttXCtia*.ÍCC3V»* BÍCCiU ÚLXTimaad
_floIva_flyfl t*tti_t i cm >>MemCPI* sazoadk uvrdb» m o * ceoat sobe axnaxiad
_flolva_uflar_titr,a BJírCW y x c o l . med by receai NCJ\C CCCMUÍIÍ
_flolv%»_flyfltacr^cifr^ + _ f l o l v a _ u f l a r _ t í r r * a
_ t o t a l _ f l h a l l _ * l a p o a d _ t lira elq><*d vtíccc«i. M d b) ali j&elcorauaifc
_total_flfta 1 r.«r._t irr«a >>Mem CPI*rtUCtíAuv:db> aU vfcc 11 ecamiúd*
_total_flíiall_j:flar__tíff*3 n e r C W vxccd* M d b> ali ^ 1 1 ecamiãdt
_total_fl2ioll_tima _ t o t a l _fl*u»11 _flyfltacr^_ c irr,a -t _ t o t a l _ f l h a l 1 _ u f l o r _ t í rr*a
_total_tt>lva_*lapftad_T:iIM elq><*d vtíccc«i. M d byuIscJveccoimaifc
>>Mem CPI* «ecoai» uv:db> ali « d coatru^
_total_tt>lva_*:flar__t: lma n e r C W vxccd* M d b>allNcJ\c c caiouadt
_ t o t a l _ t t > l v a _ _ t ima _ t o t a l _ a o l v a _flyfltacr^_ c l o » -t _ t o t a l _ f l o l v a _ t lor*a

TaMc A-14: Hi-jk-iaaro^pirattecciN

A.21.3 The quit, e x i t and endcommands

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;

A.21.4 BuilNn timing parameters

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

If option l o g _ f i l e is a nonempty string. it is taken as the name o f a file to which A M H .


copies eveiythiiç itreads fnmithe standard mput If option l o g . .cnodol is 1. then commands and
SEC7CNA.22 WFCRTEDRJNCTCttS 497

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

A.22 Importcd funetions


Somcémes it K conwnient to expres* model* with the help of funetians that an: n<it bink infci
AMH-. AMH. h» fácil ities kw nnp<irtinc funetkin* and optiomlly checking the consistenry o f
their Vgument bsts. Note: U i e practical details of u*mg imp<rtcd funetions are highly system
dcpcixlcnt. "Hii* scction i* concerned only with syntax: specific infonnation will he found m
system specific dacumcntaion. c.g* <*i the A M Ü w c t ) site.
A n imp<rted functkin may need tc» be evaluited tc» tran*Utc the pffdblem; kw instam:. if it plays
a ixile m detemünirçg the contents of a s e i AMH. mu*t be abk- to evaluite the funetkin. In this case
the funetion mu*t be bnkcd. perhips dynamicallv. with A à f f L C)n the other h i n d if an imported
funetion'x only ixile is m c<«nputing the vahie of a constraint or objectiw. AMPL ne\er need* lei
evahute the functi<*i aixi can simply juss refeienees lo iton t» a (nonlinear) solver.
Imp<rted funetions must be declared in a f u n e t i o n decluatkin befcie they an: refetenced.
This stitement has the f<mi

f u i c t l a i Ki/mr aikiiK¥ (úVwwAv-v.w i >f< / pipa / tormat fem f f ;

in which mmr is the name of the funetion. and chmain-xper amount* t» a funetkin protatypc:

ckfMaírt-ifM*:
àtmühtHu

AYAW v \ - ,.V.*M ab< h: , ...

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:

( AYMVIM (H\ ..V.SVRJ F< H: )

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 : tünction jaoan2 pipm •ãwk '(print ($l*$2)/2) '


a n p l : dimpléy 3aoén2 (1,2) • 1/
maan2(l, 2 ) • 1 - 2 . 5

The funetkin m o a n 2 is expected ( b y d e f a u k ) Io return numeric values: A M H . w i l l compLun if it


returns a string thit does not represent a number.
The folktwirç; funetions aie . • s y m b o l i c . to illustrate krmattirçg and the jussirç; o f arguments.

anpl: tünction tl myabolic pipm *AWX '(printf A*Na», t l ) ' •'•/


anpl: tünction gl mynbolic pipm 'âw* " (printt 'XXWsSn*, S I ) " ' /
anpl: tünction cmt myxt>olic pipm tornkt *>>\m«\n*r

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:

a n p l : dimpléy cét('mox» wordm ' ) /


c a t ( • s a n a u v a : d a ' ) - * » ' soura wordu • « •

The decliratxin of f 1 specifies a Dlsrq of 3 literais, while g 1 specifies o n e literal: c a L . h a v i r ç g an


empty Iil.fq, is treated as t h o t ç h its lil.fq weie ' c a l ' . The hlerals in each Blxtq an: stripped o f
the quoles thit enclace them. h i v e one o f each adjacent pair of these quotes remo\ed, and h t v e
(bücksJash. nrwSnr) juirs chinged to a single newline chiracter: the results an: aireatcrutcd Io
SECT CN A 23 AWR. NVOCAT O N 499

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

anpl: funetion noan pXpa 'av* " ( x - 0\


for (i - 1/ i <• UFj i**) x $i \
printf x/UF) " ' /
a n p l : dimpléy no&n < (i in 1..100) i)/
n * a n ( f i in 1 . . 100) ( i ) ) - B 0 . 5
a n p l : dimpléy x>oan((i in 1.. 50) (i, i*SO) ) /
nvaan({1 in 1 . . M ) ( i , i • S O ) ) - M . 5
a n p l : dimpléy xio anCfi in 0..90 fcy 10)((J in 1..10) i t J)),
n * a n ( f i in d . . M b y 10) (fj 1 •• (i • * ) ) ) -

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.

A.23 AMPL invocation


AMPl. is most oflen invoked as a scpiratc command in scmie operating sysiem cnvironment.
When AMPL begins cxccutian. lhe deelaratians. ccinnunds. and dila sectkins described above
( A . 14) can he enlered interacti\cly. IX*pcnd«ng on lhe opcralirçg syslem where AMPL is rua lhe
invocolian may be accomjxxnicd by one or mere comnvirxi ünt <vyunvni\ Ihil set various proper
lies anJ oplkins and specify fik-s lo be read. These can be examined by Ivpirçg lhe comnunJ

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

Ar. i n fuiKtKin 115, 458 ixmlinearity in 38


a s i n h funclxin 113,458 . b o d y see com trai nl body
assicrubk: cxprcssKin 185 bounded varubk- cxanpk-mcnurity 423-421
assignment model 49-61, 53, 135, 330-333, bounds on variables 10,14, 17, 32,35, 13a
348 139, 211-242, 276. 279, 466. 470-471,
. a s t a t u s suffix 294-295 486
anLaLur. _ L a b l e option 294 Bracm'* juradox 414
A l a n . a L a n 2 fcinclxm 113.458 b r © a k stUemcnt 266,493
a L a n h funclkin 113.458 brcakpomt . w piecewise Imcar exprcssion
aitribute buüfin function .wfunclK>n
: = 131,398,466,468 built in
= 74,118-120, 211, 46Z 465 ubk-hwdlcT 174,201
b i r v a r y 117, 122, 131,441,465-466 t n u n j jurameterv Obk- o í 496
c i r c u l a r 83,98. 146.463 by elause 75, 457
c i r c u l a r b y 86,463
c o c í í 356. 362, 466
CO v e r 361,467 c a r d function 79,98. 46Z 464
d e í a u l L 74, 119-12a 160-161,462, carchrulitY rcstriclkins 445
465-466,468, 47^-477 C"artesun producl seecross producl
d i m e n 93,96.462 calercr problem 347,350
i r e m 331,336,338,341,353,361,363, C a u c h y funetun 459
467 c d commaixl 495
i n L © g e r 36. 116. 131,438,441,465-466 _cdcurrcnl dircelorv 479,495, 500
o b j 334, 339, 311, 356, 363,466 c e i l Íuncticíi 2 I Z 237,458
o r d e r ©d 83, 98, 146, 463 c h a r funetum 459
o r d e r ©d b y 86. 463 c h © c k x M e n m 46.56. 117,465
o r d e r o i . inhentarxv of 86,463 Chcny, Lorínd» L . xxi
p i p e 498 C h v i t a l Vasek 30,317
rareiam 497 circular
r e v e r s e d 86.463 aitribute 83,98. 146.463
s u í í i x 466. 469-47(1. 489 b y altríbute 86,463
s y m b o l i c 123,465,476.497 c l o s e commaixl 251,481,485
Lo 331,336,338, 311, 353, 361, 363, 467 cxndprcmpLl. cmdprcmpL2 optem 494
v e r b o s © 200 c o e i f attnbule 356.362.466
auxüury fikrs.ljblcof 488 collcclions o f
dita columns, indexed 1%
seis. indexed 100-101,161-162
tibk-s, indexed 193
h a d s u b s c r i p L s tiptuffi 253
column
b * k solution 287, 289-29a 29Z 298. 473
Beadc, I : . M . L. xxi kev 170 17Z 175, 178, 18d 183, 193
Heixlers decompctsition 301 rume. valid 171-172,177, 185
Bcvtfky, JonL. xxi column name
Bcitsckas. Dimitri P. 347 abbrcviaéon. $ Z30
Be La function 459 operafctr. 177, 184-185. 188. 190 478
bzmotnx gome 426.433 comma separafcir indati 144
bm.r\ fílenamecxlensicii. . b i L 201,477 command seeal.v) stilcmcnt
b i n a r y aitribute 117,122, 131,411, command nude see model mode
465-466 command
bip*litc graph 330 bnguage 479-496
Bissdicj). Johinnes xxi nu 11 494
. b i L hirury fik~name cxtcnskin 201,477 cxnuiiand
Bixby, Robert K. xxi * i n o p L i o n 205,481
bk-ixJmg c d 495
model 37-39 close 251, 481, 485
PCEX 503

c o n t 495 argument, - ? 499-500


c c v d i s p l a y 484 argument, - i 500
d a t a 11, 143-144.206.214.256,473, argument. - o 485
479 argument. - R 500
d o l o t e 213,488 argument. - s 458
d o l o L o c h o c k 488 argument. - v 500
d i s p l a y 12,58,67,81, 104. 124, command*
219-238.482-48* sleppmg through 268-270.495
d r o p 214,489 tibk* of 480
e n d 304. 496 c o n m a n d s statement 256.479
o n v i r o n 490 commenC / * . . . * / 10.453
e x i t 496 comment* in dita 47, 453. 473
e x p a n d 13.247-248.492 cxmparaon operatevs see relational operalcrs
í i x 215.489 c o m p l w a r n o p t i o n 487
i n c l u d e 255-256,479 cxmp lemen tin i\
l o t 36,210-212.405.491 txiundcd varubk- 423-424
l o a d 4(12,477,498 constraint 4 2 7 - 4 2 8 . 4 W . 471.487
model 11.206,214,256,479 constraint. sufrues f<* 428. 431, 471
noxt 20,495 generic runies anJ 431
o b j o c t i v c 135-136,206,489 presohe anJ 429
o p t i o n 204. 481 problem 420-423
p r i n t 238-239,482-484 c o m p l c m e n t s opevator
p r i n t f 124. 2 3 9 - 2 i a 261,482-481 ccmputcd pirameters 118-121
p r o b l e m 301,307.311,489 concaftmation . w s t r i i ç concalerulkm
p u r g o 213.488
operator
q u i t 5,204,214,4%
conca\e funetions 383. 393
r e a d 163,484
conditional declaratian see i f iixlcunc
r e a d t a b l e 175, 177, 18a 477 expression
r e d o c l a r o 213,488
conditumal expression ser kigical expression.
r e d o c l a r e c h o c k 488
if-then else
r e l o a d 498
ccm^anl expression 455,457,461
r e m o v e 482 constraml
r e s e t 17,214,481,490 bod> 35,242,280.470
r e s e t d a t a 122,209-210,490 comp lemen Uri ty 427-428. 469. 471. 487
r e s e t o p t i o n s 205,490 declaration xv, 2 , 5 , 9 , 16. 137-139,340,
r e s e t p r o b l e m 491 461.468-469
r e s t o r e 214,489 defining 386.399.467
s h e l l 214,495 double inequ&lity 3 Z 139.470
s h o * 246,491 dther/cr 59
s k i p 270,495 equaity 21,30. 130
s o l e x p a n d 248,492 nonlinear 59,140,492
s o l u t i o n 487 a-dunJant 276-278
s o l v e 206-207,485-486 constraml declaratian. t o c c m e 356. 362.
s o l v e p r o b l e m 315 468
s t e o 268,495 c o n t ccmmand 495
s u f f i x 296. 299, 3(12 contanualion see line continiulkin
u n f i x 215,489 c o n t i n u e siUemenl 266. 493
u n l o a d 498 conãnuity assumption 38. 391
u p d a t e d a t a 209,491 contrai flow statements 492
w r i t e 487 ccmerskin from
w r i t e t a b l e 178, 186.477 arithmetic Io kigical 123,457
x r e f 213,247,492 number fc» string 271,459
command line con\erskin clurjcters. Uble of p r i n t f 483
a m p l 203,499 con\ex funetions 383,393,396
504 NCCX

c o c fcinction 113.458 jurometcT 8. 110-111.465-466


cart functiems. nonlinear 394 problem 489
C o « l e , R i d i M d W . 432 set 8.74,461-465
Coullard. Collette xxi, 136.14], 166. 287 tabl: 174. 178. 1 « ) . 186.477
covoretribuiu- 361.467 variable 5.8.466-467
cxivcring pmblem. set 362,361 declaration
C P L K X solver 36. 5 a 308. 281 f u n e t i o n 40 Z 497
Cramer. (iarv I. xxi t o . . c o m o constraint 356.362.468
creeit sceirmg model 386 dcciarations. suffix 471
defauk read/wnte status ser 1WOUT
crew schcdukrçg.airkne 362
defauk data value 160 161
crois product 97-98. 456
defauk svmbol . 130.153. 156-157,228.
c r o s r . operalcr 98.456
c s v d i s p l a y command 4ÍU 477
CL i m o funetion 458 default
c u t . m e x i . f i l e 306 atlribule 74.119-130.160-161.462.
cutàr^ slaci problem 41,305.364.452 465-466.468. 476-477
\ersm = initial values 119
defined varubles 466-468
DxnC/j£. Gcerge D. xxi. 39.52 defini rç comtrainl 386. 399. 467
. d a t file « f i l e do l o t e
dJareset . w r o s o L d a t a a n u i u n d c h o c k commaixJ 488
Jjta value. omitted .wdefault svmbol ccmunand 213.488
d*a derivaiive 407
columns. indexed collectxim o f 196 dx* model 27-37, 39. 77-78. 135
ccmtma separator m 144 mle£cr solutions in 36.439
commenfe in 47.453,473 d i f f operator 76.98. 456-457
fer mclexcdcoDecticm 101.161 differenliability avsumpticm 391
fermat 473-477 d i manai tribute 93.96.462
nuxle 143. 3CWÍ. 256. 479 dmxted nctwcrk graph 320
multidimerwionil Irst 148 151 . d i r o c t i o n suffix 296
mui ti dimensional tabular 156-160 Dirkse. Steven F. 433
one dimensional list 145-146 d i s p l a y command 484
parameter 477 d i 5=p l a y
set 473-475 ccmimand 1Z 58.67, 81. 101. 124.
set and jurameter 151-152 219-238.482-4
table. set and parameter 476 fcrmaltirç* options 227-230
two-dimcnsional bst 146-148 fcrmattirç; optxins. table o f 227
two dimensional tibular 151-156 numeric eiptiems Z^2-Z38
unfcrmatted 163 numeric options. table of 232
valxlation 12.46.93,118 D i s p l a y set 87.461
value. defauk 160-161 d i s p l a y _ l c o l optxm 63.228.231
drfaspeci ficai ion. < . . . > 196-197.479 d i s p l a y _ c p s optem 235
d a t a ccmmand 11, 143-144.206.214.256. d i s p l a y p r o c i s i o n option 233. 363,
473,479 406.483
dJahase harxller srr table handker d i s p l a y _ r o u n d optiem 231-235.483
d Ja-model separation 7, 11,74. 143 d i s p l a y _ t r a n s p o s e option 229
d a t a p r o m p t l , d a t a p r o m p t 2 optem 491 d i s p l a y _ w i d t h eiptiem 201.229
d orlara* cm s r r a h o statement drsptams
dolaratcm mdexmg expression 224-227
are 334-311.353.467 parameters 22O-224
constraint xv. Z 5. 9. 16. 137-139. 310. sets 220
461,468-469
d i v operalcr 111,456
ix.de 331-340.353.468
dciubleincqualily constraint 32. 139. 470
objeetive 134-137.470
d r o p command 214.489
NC€X 505

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

m u l L m i p l . m o d 442 £i r s L funetion 84,463


mulLmip3.daL 447 R A e r , Morshilll.. 317
mulLmip3 .mod 446 f i x ainunonJ 215.489
n e L l . mo d. neL 1. daL 322 fixed
n e L l n o d o . m o d 335 ca*K 440-444
neL2. da L 325 variables 131,241,4(12
n o t 2 . m.od 324 Hdcher, Roger 410
neL3. daL 327 f*>o«irçg point lepnsxcntation 76. 87, 144.
noL3. mod 326 233,235. 263. 271, 279. 453-454, 483
ncL3nodo.mod 336 f l o o r functkin 212. 457-458
n e L a s g n . m o d 333 flow ser network flow
n e L f c o d s . m o d 344 f o r stjtfemenl 258-26Z 493
neLmax3.ood 339 f o r a 11 aperttor 115.456-457
ncUnax. mod 329 Ford. Lesfcr R. Jr. 347
noLmcol . o o d 363 fcrmottirç; optkin*
n o L m u l t i . m o d 342 d i s p l a y 227-230
no Lshor L. mod 331 ubkrof d i s p l a y 227
n e L t h r u . m o d 316 lourer. Rcfceit* xxi. 20.318.381
n l Lrans .mod. n l L r a n s . d a t 404 frccn oltribute 334. .336. 338. 311, 353. 361,
p r o d . d a t 10
363,467
prod.mod 8
Fu&oson. D. R. 317
s c b o d . d a L 361
funetion
sch&d .mod 361
a b s 113. 14a 380. 458
s L © e l 2 . d a L 14
a c o s 113,458
s L o e l 3 . m o d . s L e e l 3 . d a L 15
a c o s h 113,458
s L e e l 4. daL 17
a l i a s 458
s L o e l 4. mod 16
a r i L y 462. 464
s L e e l . m o d . s L o e l . d a L 11
as i n 113,458
c L o e l P . d a L 65
as inh 113,458
s L e e l p l 1 .daL 374
a L a n . a L a n 2 113.458
s L o e l p l l . m o d 373
aLanh 113,458
s L o e l H. mod 6:
Be La 459
s L o c l T O .mod 59
s L o e l T 2 . d a t 85 c a r d 79,98.462,461
s L e e l T 2 .mod Zi Cauchy 459
s L e e l T 3 . d a t 102 c e i l 212,237.458
s L o e l T 3 .mod 101 c h a r 459
s L e e l T . mod. s L c c l T . d a L 62 o o s 113,458
Lransp2 .mod 93 c t i m e 458
Lransp3 . d a t 95 e x p 113,458
t r a n s p 3 .msd 95 ü x p o n e n L i a l 459
L r a n s p . daL 48 f i r s L 81,463
L r a n s p l 1 .mod 368 f l o o r 21Z 457-458
L r a n s p l 2 .daL 371 Cianma 459
L r a n s p l 2 .mod 370 ç s u b 273,460
L r a n s p . mod 47 i c h a r 459
füevnme x y « a 11. 144. 165. 204, 479 i n d e x a r i t y 46Z 464
filename I r a n d 2 2 4 459
l a s L 84,463
- stanJard inpul 165. 283. 485. 495 l e n g L h 271,459
extemxm. . b i L tvniry 201,477 l o g , l o g l O 113.458
cUcmxin. .mdb Acces* 199-200 maLch 271.285.460
cUciMoa . t a b ASCII 201,477 max 113, 380. 458
cxtcmion. . x i s lixcel 199-200 member 463
files, table of auxilury 488 min 113, 14a 458
NC€X 507

n o x t 84-85,463 G r a v e , liric II. xxi


n o x t w 84-85, 463 ç s u b funcHon 273, 460
rina 1, nna 101 209,459 g u L L o r _ w i d t _ h aplian 230
num. num D 460
o r d o r d O 85,463
P o i s s o n 459 liiesslcr. RabcrtW. 318
p r o c i s i o n 458 lligcr. W . W . 318
p r o v , p r o v w 83-84,463 h*idler w t a b l e harxlkr
r o u n d 21Z 458 h a n d l c r l i h 477
s i n 113, 458 JI>VJDLKRS 477
s i n h 113,458 Ifteam. D. W . 318
s p r i n t f 271,459,483 IfcUl. SajdS. 39
s q r t 113,458
s u b 273, 460
- i command hne argument 500
s u b s L r 271,459
i c h a r funetion 459
L a n 113,458
113:1: arithmctic strr fbafcrç; pomt
Lanh 113,458
t i m e 458 representa ío n
t x une 21Z 458 i í indcxirç; cxprccskin 138,338,341,362,
Un i í o rin. U n i £ ormOl 459 460-461,467
£ u n c L i o n decliration 402,497 i£-Lhen o l s o
functions nested 266
cancro? 383,393 operator 115,117,133,264.457
cunsex 383.393.396 statement 261-266,493-494
«mp<«tcd 497-499 • i i s suffix 299
<if sets 83-85 i i s f i n d , i i s _ t a b l e option 299
af sets. t i b l e o f 464 impoftcd funetons 497-499
IMDlTTsuíruatlribute 472
piecewise linear 365, 379-384. 393. 395 i n operaltv 78,98. 114.455-457,465
separablc 381,383 IM read/wnte status 174, 177, 180,182, 186,
smooth 391,400-402 478
table o f arithmetic 113,458 i n c l u í d o srealu) nx-xiel.ciaLa
tiblc ofranckim numbcr 459 includo
iiblc afregular expressem 459 cxnunand 255-256,479
tibk- of roundirçg 212 search path 479
ttblei of string 459 index w f dummy index
i n c i o x a r i t y funetion 46Z 464
indexed
Gatuna funetion 459 cal lect ío a dita for 101,161
(hrillc. SusanGjinxrr 39 collections o f dita columns 196
Qisx..Saull. 39 collections af sets 100-101.161-162
(jassmann. H. I. xxi callectkins of Ubles 193
Ciay, Divid M. 318 abjecthes 134
generic rumes 249, 291, 429, 492 indexing
and complemcntahtv 431 expression 9,79-82,99-100. l i a 138.455
übfc aí 493 expression. dispUymg 224-227
g o n t - i m o s option 250 expression. scope "af 80,94-95,455-456.
€SD, Ptohpl:. 410 482
(aimoré Gomary algorithm 305-306
over empty set 82,146
gkihil siptimum .£08
indexing expression. i £ 138,338, 311, 362.
Cflovcr, Ired 347
4 « ) 461,467
gnph
in feasi hi h ty i n prescil \e 279
hpirtüe 330
mfeasible solutions 34. 299, 374
di recled networi 330
infinite
transiti\e ckisureaf 462
bop 26Z267
508 RC€X

sets 86. 463 kiuptack problem 23, 306. 451


i n f i n i t y 212. 276. 538. 456.466 Kontogkirgis. Spyros 384
inhcntance o f o r d o r o d at tribute 86.463 Kostreva. Michael M . ±19
InitÍAl Kuhn. I tiro kl W . xxi
environment 316,490 Kuip. C . A . C . x u
problem 311,315,489
ínituJ values
of dual variables 185. 468. 47Z 477, 486 1 agrange mu kip her .uvduil vxiables
of variables 131, 162, 398,405,408-409, l » g e scale optinu/atxin xvi
466,471, 477,486 Lasdon, Leon 318.414
initial values l a e t funetiexi S I . 463
: = VCJSITI = 2 1 1
. l b kiuer bourxl 35, 241 -242,279.4IX).486
d o í a u i t VCJS i a = 119
. l b O . . l b l . . I b 2 lower bound 279
initiaJi/alxin. s u f i i x 466,4*0-470,489
Itast sqiures 388.412
1N0UT readAvrite stitu* 186.193,195
l o n g L h funetion 271,459
iflput redirectum. < 163. 165.481.485
1-enstra, Jan Kanrl xxi
input oulput model 37, 42,351-358
l o c c <ijierak»r 111.456
i n s o r L p r o m p t option 268. 479
l o t command 36,210-212.405,491
integer
l i i a r y w i m j x » r t e d funetkin*
program. relixatitm o f 309,448 L i c t m n , Judith 414
programnurçs xvi. 36.437-438.448-449 Ime continua* on \ 205,453
sohititxi. rounding t o 35. 309. 36a 439, IBIOÍT
448 expies* kin 132-131,139,383
solutions si diet model 36,439 program. network 319,343,353
solutcns m network model programming xvi, 1-5. 129
solutions BI schedubng model 360 Imiant) o f costs. yiekl 38. 393
solutions BI transp<ita«ion model 51, l i n o l i m oplkin 467
439-448 Isiked linear programs 55. 60
intogar látdata
atribute 36,116,131,438,441,465-466 multidimcmkiiul 148-151
sei 86,463-461 one duncmkuul 145-146
i n t e g o r m a r k o r r . o p l x i n 486 two dmiensuaial 146-148
I n t o g a r s set 87, 464 lucrai
i n t o r operator 76, 98.1(13,456-457 number 75. 111, 144,453-454
infiTior pcimt algorithm 287 set 74,451
intcrsection. set xrr i n t o r string 74. 144. 453-454, 473
i n t o r v a l set 86. 463-464 l o a d cxxnmand 402,477,498
l r a n d 2 2 4 funetion 459 local cpémum 407-408
iseducible infeasftik* subset 299 ÜDCALsuffíx aftribute 472
íteraled operatt* arr opero»:) r l o g , l o g l O funetkin 113, 458
l o g _ f i l o option 251,496
l o g m o d o l , l o g d a t a option 2 5 2 , 4 %
Jaxib*. Walter 317, 351
logical
iohmon, I:Di« L. 449
anthmetic. set operalcrs. table o f 456
con\erskin. arithmetic fci 123,457
Kahan. GeraU 363 expies*kin 8 a 99, 114-116,455,457
Kelly, Paul I Ú operafcirs 114,457
Kendnck. D a v i d A . 20 jurameters 122-123
Kemighxn. Mark D. xxi loop
«nfinite 262,267
column 17a 17Z 175. 178. 18a 183, 193 rume 268,494
spccificjtion. empty 182 nested 261,267
kcj' wird .%er reserved word ICKS in network fiou- 326. 336
Klmgman. RITWBI 347 Ijoue, Todd xxi
NC€X 509

ICTVSVT bound network f b w 319, 333-339, 416


. l b 35,241-242,279.470,486 rxi nl mear trans portal k»n 403-410
. l b O , . l b l , . I b 2 279 o i l r e f i n c r y 31-25
piccewiisc linear product km 370-377
piecewise Imeartranspoitâtxin 366-369
Magnanli. T h o m a s L . 317 produetiem 6 - 1 2 . 1 5 . 4 2 0
morei rui vahie str DIUI value produetiem and transportitxin 63-67
M a r i c á R o y E . 384 scheduhr^g 3 7 , 3 5 9 - 3 6 2 , 4 5 1
m a L c h funcixin 271, 2 8 5 , 4 6 0 shertest path 329-330
mathematical procramnung x v - x v i steel produetiem 2 - 7 , 1 0 - 19
nutri* str twc^imcnsiemal s d . parameter stress anah sis 388
matrix gcncrator xvii. x x i transpertatiem 41-49, 5 2 , 3 3 0 - 3 3 3
max transshipment 3 1 9 - 3 2 7 , 3 3 1 - 3 3 7 , 3 4 7
functicm 113, 3 8 a 458 m o d e l command 1 1 , 2 0 6 , 2 1 4 , 2 5 6 , 4 7 9
cjierator 114.456 model d a t i separaticm 7, 11,74. 143
m a x i m i z o str efcjectivc declararem modehrçg languigc x v i - x v i í
maumum flow mode) 328-329, 337-339. M P E C s y s t e m 426
412 M P S file' 486
nuu min objcctivc 382
mukicommodity transixirtilxin model 56-59.
. m d b Access filename extension 199-200 450
Mceraus. Alciander xxi. 20 mukxlimerisxirul
member, dummy .«•«•dummy index list data 148-151
m e m b e r function 463 ObulardaU 156-160
membership test str i n , w i L h i n multiperiod
membership operatovs. set 78-79 plarmmg model 67-69. 452
rnemcry use 8 8 , 9 7 , 4 4 8 produetiem model 5 9 - 6 3
messages str error messages mukiple
meticharacters. regular expressiem 460 objective* 131-137,206,240
min solutiems 6 , 4 9 , 137,407
function 113, 14a 458 M u v a y . Walter 410
operator 114,456 MuHy. K a t t a G . 347
mi n i m i z e str objcctivc declaration
min max cfcjectivc 382
M l N O S solver 6 . 2 0 8 , 2 8 1 , 3 9 8 nane
mixed integer programming 441 kictp 268.494
. m o d file str File synUx 453
mad eiptraler 111,456 nancd
m o d e l file str file environments 316-317
model problems 309-316
activity 4 3
nanes
adverti sins 21,450
gcncric 2 4 9 , 2 9 1 , 4 2 9 , 4 9 2
aggregatcd 55, SS
table of generic 493
assignmenl 4 9 - 5 1 , 5 3 . 135.330-333,348 Nash equilibrium 426,433
blendmg 3 7 - 3 9 Nemhauscr, Cícorge L . 450
credit scormg 386 NKCXS x x
diet 2 7 - 3 7 . 3 9 , 7 7 - 7 8 . 135 nested lexip 261, 267
cconomicctjiiilihnum 4 1 9 . 4 2 2 netted i í - L h c n - o l c e 266
ctjuüAnumstrcss 388 n o t _ i n . n e t _ o u t 331,340,469
input oulput 3 7 , 4 2 , 3 5 1 - 3 5 8 network
m a u m u m f b w 328-329, 337-339, 412 f b w , bss in 326. 336
mode 143, 206. 256. 479, 496 f b w model 319, 333-339, 416
nuilticummodity transpoytitkin 56-59, 450 graph. dmrcted 320
multiperiod p b n n i q g 67-<W,452 linear preigram 3 1 9 . 3 1 3 . 3 5 3
multiperiod produclxin 59-63 m o d e l integer solutkins in 314
510 ecex

new Ene 144.453.473.498 omáled d*ta value . w d c f a u k sjmbol


\ n n e w l m c m p r i n t f 239.261,482 one dimensional
noxt list data 145-146
command 2tf). 495 p&rametcr 110
funetion 84-85.463 set 110.454
n o x t w funetion 84-85.463 set dati 473
n l p c r m u L c option 487 O-NetlL Richird P. 411
Nocedal. Jorge 410 operador
node declaratian 334-340,353.468 precedence 9.77, 111-114. 116. 133,456,
non existcnt dita value . w d e f a u k xymbol 459
nonincar synonyms 454
constraint 59. 140 492 operalor
cxist funetions 394 column name 177,184-185,188,190,
expression 114,133.400-40^ 478
procramnum; xvi. 391-397. 403-410
& string conralemtwn 270,459
transportation model 403-410
a n d 114.456
variables 397-400
c o m p l c m c n t s 469
nonbnearity m
c r o r . 5 98.456
blending" 38
d i f f 76.98.456-457
physical models 397
d i v 111,456
noniiegitive varubk-s 3, 10,45. 130 377
e x i s t e 115,456-457
N o r m a l , J t o r i n a l 0 1 fcjiKtion 209.459
f o r a l l 115,456-457
not
i f - t h e n c i s e 115,117, 133,264.457
i n operator 79,456 i n 78. 98. 114, 455-457, 465
íjierator 114,456 i n t e r 76,98. 103.456-457
w i t h i n opero*)r 79, 456 l e s s 111.456
null command 494 max 114.456
num. numO funetion 460 m i n 114.456
numbtr reprcscnlation see flcutmg p<inl mod 111.456
rcpresentatxm n o t 114.456
nunba n o t i n 79.456
literal 75,111,144,453-454 n o t w i t h i n 79,456
to strirçg.conversian from 271,459 o r 114,456
numbas. sei of 75-76 p r o d 74. 114.456
nunieric Io lógica! con\erskin 457 s o t o f 98.272.457
numeric options. d i s p l a y 232-238 sum 74, 113,456
s y m d i f f 76.98,456-457
u n i o n 76,98. 103,456-457
w i t h i n 78, 93,97-98, 114,456-457,462
- o command hne argument 485
operators
o b j atribule 334,339,341,356,363,466
ará hmetic 456
objcctive 3 , 9
arithmctic reduction 456
declaratian 134-137,470
kigical 114,457
funetiem xv, 31,240.341
relalkinal 114.465
max min. mm max 382
set 76-78
objcctive functkm. t o c o m e 362,470
o b j o c t i v c cxínnumd 135-136,206,489 set mcmbcrshq> 78-73
o b j c c t i v c ^ p r o c i s i o n opdon 484-485 tible of anthmetic 112
objectives tibk* of anthmetic, kigicaL set 456
indexed 134 tuple 98- 100
mui ti pie 134-137,206.240 optmial tusis seebasic solutum
O D B C table handler 169, 174. 194, 198 optanum
oil refincTY model 24-25 global 408
cm i t _ z o r o _ o o l s option 66,232 kical 407-408
cm i t _ z e r o _ r o w s option 50.66.231 optkin
N C € X 511

ampl i n c l u d e 479 s o l u t i o n p r e c i s i o n 236. 238. 264,


AMPLl'1«C 498. SOO 481,486
a s t a t u s t a b l e 294 s o l u t i o i v rourxi 236,238,481,486
b a d sub s c r i p t s 253 solve_exitcode.
cmdprccnpLl, cmdprompL2 494 s o l v * _ e x i t e o d e ^ m a x 285
compl warn 487 s o l v e m e s s a g c 285
da LAp rompL 1, da Lap rompL 2 494 s o l v o _ r e s u l t , s o l v e result_num
d i s p l a y l c o l 63.228.231 283-281
d i s p l a y « p s 235 so 1 ve._r esu 11 _ t a b l o 283
d i s p l a y p r o c i s i o n 2X3,263.406. s o l v e r 37,207
483 s o l v e r msg 260
d i s p l a y _ r o u n d 234-235,483 s s t a t u s L a b l e 289
d i s p l a y t r a n s p o s e 229 s u b s t o u t 399.414.467-468
d i s p l a y _ w i d t h 204. 229 t i m e s 250
d u a l i n i t i a l a g u e s s o s 486 TMPD1R 285.485
o e x i t 252 v a r _ b o u n d s 279.486
v e r s i o n 500
c x p a n d p r e c i s i o n 484
o p t i o n cxmnLind 204.481
g e n t i m e s 250
g u t t e r . w i d t h 230 * m 205,481
i i s í i n d , i i s t a b l e 299 optxin rume fulfcrrn 481
i n s e r tprcmpL 268,479 oplKHK 201-205,481
i n t o g e r m a r k o r s 486 cnvffonnwnl 490
l i n e l i m 467 opfiom
l o g _ f i l o 251,496 d i s p l a y ícmuUtng 227-230
l o g m o d e l , l o g _ d a t a 2 5 i 496 d i s p l a y numene 232-238
n l pormuLe 487 tible af d i s p l a y formaltorçg 227
o b j o c t i v e p r o c i s i o n 481-485 tiblc af d i s p l a y numerie 232
a n i t _ j t o r o _ c o l s 66.232 op t i o n s . r e s e t 205.490
c m i t _ z o r o _ r o w s 50.66,231 0PT10NS IN.OPTIONS_OUT.
p l _ l i n o a r i z o 383 OPriOWSLiMDUT 490.499
p r e s o l v e 139,278.290 Çopiinn value 4 6 a 481
p r e s o l v e ^ e p s , p r e s o l v e ep.rmax $$apáan default value 481
281 o r opcralcr 114. 456
o r d . ordO funetun 85. 463
presolve_f ixeps. oxlcr of evalu afcan 100,111,132,467, 473
p r e s o l v o _ f i x e p i a n a x 282 axJered sets 82-87, 98. 223, 261, 463-464
p r e s o 1v « _ i n t e p s , o r d e r ©d
p r e s o l v o _ i n L e p í a n a x 279 attribute 83,98. 146.463
p r e s o l v e w a r n i n g s 252.282 altribirte, inheritance of 86,463
p r i n t _ p r o c i s i o n 239,482-483 by altribute 86,463
p r i n t _ r o u n d 239,482-483 Odm. James B. 317
p r i n t _ s e p a r a L o r 238,482 OUT
prccnptl,prccnpL2 204,494
r a n d s o e d 12Z 458 readfwri* «atus 177, 186. 190 192.478
r e l a x i n t e g r a l i t y 215,217,309, auffi* atenta* 472
486 output redircet ion. >, » 230,239, 251, 273,
481
reset_initial_guosses 291,297,
486
s e n d _ s t a t u s e s 288 pars
s e n d s u f f i x o s 486 setsofordned 91-92
SI1ELL 495 slices of 93-96
s h e l l _ « n v _ f i l e 495 sutxc* of 9 3 - %
sho*f s t a t s 250. 275, 282 Pang. Jong Shi 432-433
s i n g l e s t e p 268 pjrametex
512 NC€X

and setdati tibk- 476 p r e s o l v e w a r n i n g s optkin 25Z 282


dUa 477 p r e v . p r e v w functxin 83-81,463
dll a sttfcment 475 pace. shackiw sre dual value
datatahle 151 prima] variables 213, 398. 485
dita template 147-148. 15a 475 p r i n L commarxJ 238-239,482-181
declaration 8. 1 IO-111. 465-466 p r i n t _ p r e c i s i o n opt x» n 239,482-483
definitacm. recursiw 130.122.465 p r i n t _ r o u n d optem 239,482-183
eme dimcmxirul 110 p r i n t _ s o p a r a Lo r o pt x > n 238.482
t w o dimensional 110 printí
ccmunand 121,239-240,261,482-481
ccmputed 118 121 ccmwrskin chiracter, t 239,482
di sp living 22ÍV-224 can\ersk>n chiraclcrs. tibk- of 483
logical 122-123 \ escape sequences 482
randamly generated 121 -122.209 string quotes. %0 483
restrictkím on 116-118 . p r i o r i t y suffix 296
symbolic 123-124.323.328 pxiblem .wtiL\o model
tibkr af b i n k m tmung 4 % pxiblem
Panfela*. P M . 318 caieier 347,350
PAT1I solver 422 compk-mcniintv 420-423
pJtcrn. optem rume 481 cuttrçg stock 41,305,361,452
penaky funetion 369-377, 385, 396 declaration 489
piccewisclmear 3 7 Z 375-376 knaptack 23, 306. 451
Philbpt. Nancy 347 setcowrirçg 362,361
phvsicil models. rxinlmcantv «n 397 pxiblem. I n i t i a l 311,315,489
_ p i d procest ID 495 p r o b l e m commaixl 301,307,311,489
pieeewise linear pxiblcms. named 309-316
funetem at zero 367,376 p r o d operator 74, 114,456
funetians 365,379-381,393,395 pxiductian
penakv funetem 372,375-376 and tramporutx>n model 63-67
produetian model 370-377 model 6 - 1 Z 15,420
transpcilaticm model 366-360 nicxlel «n algchraic form 7
p iecewi se linear expres si an « . . . » 367. mcxleL multípcriod 59-63
mcxleL pieccwise Imcar 37(V-377
360,376, 380-38Z 460 pxigramnurç;
Pike. Ralph 411 mlegcr xvi. 36,437-438,448-449
p i p o aftributc 498 linear xvi, 1^5,129
p l ^ l i n o a r i z e optkin 383 mathcmafccal xv-xvi
pUrmmg mcxleL multpencxJ 452 mixed integer 441
P o i s s o n funclkin 459 nonlinear xvi. 391-397, 403-410
p r e stjiiK 276 stochastic &)-7\
p « x e d e i K e . operator 9, 77,111-114.116. pximpt
133.456. 459 a m p l : 5, 165,204.485
p r e c i s i o n funetion 458 a m p l ? 165,204.485
ptxJcfmed wofdf 74. 1 1 Z 4 5 1 a m p l d a La 144
reck-fira t o n o f 213,451 p r c m p L l , p r o m p L 2 optem 201,491
p r s o l w 6 a 65.207.241,275-282, 486 p u r g e c o m m a i x J 213,488
arxl camplcmcntarity 429
«n feasi tá b ty in 279*
p r e s o l v e option 139,278.290
p r e s o l v e . e p s . p r e s o l v e epsmax
optxin 281 *t0 p r i n L Í string quotes 483
presolve. íixeps, quibficd name .UY suffix
p r e s o l v e _ í i x e p s z n a x optem 282 query, S Q L 184. 199
p r e s o l v e _ inLeps. q u i t ccmunand 5.201,214,496
p r e s o l v e _ i n t e p s m a x optem 279 quites 74. 144. 165. 204-205. 453,473
NC€X 513

-R command line argumcnt 500 command 17,214,481.490


rarxlom number da La command 12Z 209-210.490
fundi ens. table of 459 o p L i o n s cxmmand 205,490
gcncratorseed 12Z 210 458 p r o b l e m command 491
randem ünbulc 497 r c 5 o L _ i n i L i a i g o e s s e s option 291,
randomly gencraled paramcterN 121 -122,209 297, 486
r a n d s õ c d option 122.458 r e s L o r e command 214,489
. r c w reducedcost restrictkim on pArametcrs 116-118
road . r e s u l L suffix 287
command 163.481 r e v e r s e d atribute 86. 463
La b l e commaixl 175, 177, 180 477 re\ersfck- activitics 377-379
reading files .wrmodeL. da La Ri di ton. Robert E xxi
rcadinc scalir from table 182 Rinnooy Kan. Alcxander It. G. xxi
readmiti te status roII trim probk-m JW cutting stock problem
- > 189,193,478 r o u n d funclkin 21Z 458
•c- 175,177.182, 193 rounding 76. 87,233,237, 263, 271, 279,
< - > 193,478 451, 457, 483
I X 174,177,180, 182, 186. 478 functions. Ubk- of 212
IWCWT 186. 193. 195 to integer sokition 35. 309, 36a 439, 418
OUT 177, 186. 190. 19Z 478
R e a i s set 87,461
reciasivc - s command hne arg umcnt 458
juranurter dcfmitkm 120. 12Z 465 Saundcrs. Michacl A . xxi
set dcfmitkin 462 s a l ar from table, readmg 182
redeclare saling akrng are « • kiss m network f b w
c h e c k command 488 scaling of variables 410
cxmmand 213,488 sdicdubrç;
redefinition of pnrdcfincd word* 213, 454 airlinecrew 362
redirection model 37. 359-36Z451
>, » output 220 239, 251, 273, 481 model mlegcr solutkim in 360
< mput 163, 165, 481, 485 Schsigc. lanus 414
nrducvd coít 17,22,40 67,243-245 Schâjver. Alcxander xxi. 450
reduction operator*. arithmetic 456 scope seralm dummy irxlcx
rcdurxlant constraint 276-278 scope of
regulir expressxin 273, 460 dummy mdex 47. 321
functions. Ubk- of 459 indexing cxprvssxm 80,94-95, 455-456.
mcticharocters 460 482
reltfkirul
script 18.179, 195.255,304,485.495
opero*) rs 114.465
script
ubk- 170-171, 173,178
c u L . r u n 308
. r e l a x suffix 486
d i e L . r u n 284
r e l a x _ i n L © g r a l i L y optkin 215,217, d i e L u . r u n 256
309, 486 s L e e l T . s a l 258
rclixatum of integer program 309. 448 s L o e l T . sa2 259
r e l o a d command 498 s L o e l T . sa3 260
r e m o v e a m n u n d 482 s L o e l T . sa«l 263
r e p e a L statement 262-264, 493 s L o e l T . s a 5 266
representation. fkiaérç jximt 76.87. 144, s L o e l T . s a ? 267
233, Z35, 263, 271, 279, 453-454. 483 S L o e l T . L a b l 261
reserved soarch path. i r > c I o d e 479
word syrxinvms 454 seed. rarxlom number generater 12Z 210
wirds 74,112 458
wordí, table of 451 Seip. Robcrllt. xxi
reset sdf referente 117
514 NC€X

scmicolon sutcmcnt tcrnunafcir 9, 144.2CM. s h e l l _ o n v _ f i l o option 495


256,453. 473,494 Shepheard. J. R. xxi
s o n d s L a L u s e ! : option 288 sh«1cst path model 329-330
sond _suf f i x o s optem 486 sher* cxBiimand 246.491
sensitivity analysis 194,256.262,301 s h o * stat-soptkin 25a 275.282
seporohlc furvtkins 381.383 side
scpara*>r in dita, coxiuiu 144 constraint 342.345.363
sd diffcrence . w d i f £. s y m d i f f variable 343
sd intersectkin .w i n L c r significar* figures 233
set oí sets xte írxlcxcd collectkin simplex algcnthm xvi. xxi. 279. 287. 314.
sd 486
and parameter dati 151-151 simplificatian of expression s t r a l » ) presoKe
and parameter dati uble 476 srnipkficatian of expression 46. 13a 134.
arithmetic. kigical operators. tible of 456 139
cavcring problem 362,361 s i n funetkin 113.458
dita 473-475 s i ng l o _ s L e p option 268
dita. one dimensional 473 singleslep mode 495
dita stitcment 474
smguhnty 406-407
dita table 474
s i n h functicm 113.458
dita tcmplate 147. 15a 474
Sinha I.aishman P. xxi
dita. two dimenskirul 475
s k i p command 270.495
declaration 8.74.461-465
defini tion. i v u r a w 462 . s l a c k suffix 81. 311-21Z 241,472
cxpre-cskin 455.457 shee 58.91.95.97.147-149.455
bteral 74.451 shees of pairs 93-96
member rui rs 454 skipe . w piecew ise hnear expresskin
mcnihers hi p < ip crafc»rs 78-79 smooth functions 391. .0KV-402
of numbers 75-76 SNOPT solver 48. 338
one dimcnsioml l i a 454 social accounfcrç matnx 415
operators 76-78 soft consfraaits .wr perultv funetion
two dimensional 110.455 s o l o x p a n d command 248.492
sd sohitian. hisie 287. 289-29a 29 Z 298. 473
A S C I I 87.461 s o l u t i o n a»mmand 487
dita table. - in 156-157.475 so l u LÍon_ p r o c i s i o n opti<*i 236.238.
D i s p l a y 87.464 261.481.486
KBCD1C 87.461 s o l u L i o n ^ r o u n d option 236. 238. 484.
i n L o g e r 86.463-464 486
I n L o g e r s 87.461 sokitians
i n Ler v a i 86.463-461 fcasiblc 4, 35
R o a l c 87.461 mfeasible 31.2W.374
s c Lo í operolc» 98. 27Z457 mui ti pie 6 49. 137.407
xdx solve
disp living 220 command 206-207.485-486
functi<*is of 83-85 p r o b l em cxnunand 315
indexed collectkins of 10C1-101. 161-162 solvo oxiLcodo.
mímitc 86.463 c o l v o c x i t c o d o max option 285
af crdcred pairs 91-92 s o l v o m e s s a g e option 285
af tu pies 96-98 s o l v o r e s u l t . s o l v o _ r o s u l L num
option 283-284
<rdered 82-87.98. 223. 361. 463-464
s o l v o _ r o s u l t _ t a b l c opt<m 283
unerdered 73-74
_ s o l v o _ t i m e pirometcT 251.4%
shukiw price . w d u i l value
soher
s h e l l command 214.495
CPLKX 3 6 50.208.281
SllIÍLLoptkin 495
MINOS 6 308.281.398
shell script 500
PATII 422
pcex 515

S N O P T 48. 308 s u b funetion 273,460


status s u f í u c s 2 8 6 . 2 8 8 s u b j e c L t o see constraint declaration
x d v v r ü W w . . s t a t u s 473 subscnpt 8,16. l i a 455
s o l v e r cjiticm 37, 307 subset test see i n , w i t h i n
s o l v e r msq option 360 subsets o f paxrs 93-96
xol\vr*defined sufHxcs 298-301 substtutaem o f variables 399-400,414
s p i c c requircmcnl m e o K M y use s u b s t o u t option 399,414,467-468
spme s u b s t r funetiem 271,459
set III
such that condüion see kigicalcondilion
subset 94
sufru declarations 471
spreadsheet 238
suffix
II* cri 174.176,1% . a s t a t u s 294-295
s p r i n L f funetion 27 J. 459. 483 atlribute. I N . IHOOT.OUT. LOCAL 304.
S Q L query 1 S I . 199 472
S Q L S K L K C T statement 199 . d i r e c t i o n 296
s q r t funetem 113, 458 . i i s 299
squav sy«cm 422, 425. 427. 487 . p r i o r i t y 2%
. s s t a t u s suffix 290.292.295.473 . r e l a x 486
s s t a t u s _ t a b l e optem 289 . r e s u l t 287
s . L . see constramt declara* an . s l a c k 81,241-242, 244.472
stuxJard mput rüemme. - 165. 283. 485. 495 . s s t a t u s 29a 29Z 295, 473
stirtirçg £uess see milul values o f varubles . s t a t u s 295
stitemrnt seealsit command. declarai x>n suffix
stitement atlribute 466. 469-47a 489
jurameter dati 475 ccmunand 296,299,302
set dati 474 initialúation 466,4*0-470,489
termiiutcr. senucalcm 9. 144, 304. 256. suffix cs
453.473. 494 fer compk-mcntiritv cxmstramt 428,431.
statement 471
h r e a k 366.493 sohcr status 286.288
c h o c k 46.56. 117.465 sohcr defined 298-301
c o a m a n d s 256.479 table of 472
c o n t i n u o 366.493 user defined 296-297,302
£ o r 258-362, 493 Suhl, U w II. 449
i f t b o n e l s o 364-366.493-494 sumofsquarrs 388.412
r e p e a t 362-364.493 sum operalcr 74. 113,456
tfatements, ccmtrol flow 492 symbolic parameters 123-131.323.328
.status s y m b o l i c attn bule 123.465.476.497
solver status 473 s y m d i f f operator 76.98. 456-457
sufru 295 sy nunetnc diffcxence m * s y i n d i f f
sícel product em model 2-7,1(V-19 synonyms. table of 454
stcpccmuiiand 268,495 synlax errer see errar mes*iges
stepping through command s 368-27a 495
stochastic programnung 69-71
Stonc Richard E 432
stnr*s anahsis model 388 . t a b A S C I I f i l e n u n e e x t e n s . c n 301.477
tibkr
string
declaraécm 174, 178. 18a 186. 477
con\ersion frcrni number to 271, 459 entry, empty 173.187
expression 191,197,273,459 hindler 169. 197-30Z 477
funetiem*. tibk- of 459 handlcr. bink-in 174.301
fiteval 74,141,453-451,473 handler, O D B C 169,174,194.198
tfring of arithmetic funetions 113, 458
ccmcatenatcm operalcr. & 270. 459 of amhmetae. kigical set operaters 456
quoles. feq,%0print£ 483 of anthmetic operaters 112
516 PC€x

af ouxilury files 488 transpôs* km see libk* tronsp<Mtx»n


af buüt in imune porometers 496 trmvshipmcnt model 319-327,331-337,347
afcommond* 480 t r u n c funetion 21Z 458
af environmcnt varubk-s 484 ti^ile operotars 98-100
af funetions af set* 461 tuples 73,91,96. 146
af geticric nomes 493 sets af 96-98
aí rondem number funclxin* 459 two dimensional
af xeguhr expression funclxim 459 kstdoti 146-148
af reserved wcvds 451 piromcter 110
af raundmg functkim 212 set H O 455
af string íurvlxim ^ sctdoti 475
af suírixes 472 Ubulardoti 154-156
af synonyms 454
jxiromctcr dati 154
rcoding scohr from 182 . u b upper bound 35, 240-242,279,470,486
reLUxirul 170-171,173.178 • ubO. . u b l . . ub2 upper bound 279
sei doto 474 u n f i x command 215.489
tAle unfomutted dou 163
Unicode 453,459
af d i s p l a y fcrmotting aptkim 227
U n i f o r m . U n i f o r m O 1 functkm 459
af d i s p l a y numeric options 232
unionoperolcr 76, 98, ia3,456-457
cif p r i n t L conversum chorocters 483
u n l o a d command 498
tronsp<*itxin ( t r j 32, 155, 157,228-229,
urxirdered sets 73-74
475-476
urtspccificd dito vohie .wvdcfouk symbol
( A l e s , mdexcdcollcctians of 193
u n t i 1 condãxin 26Z 267,494
tJiulordoü
upda t o d a t a cxxnmand 209, 491
mui ti di ntent x» rui 156-160
user defined suffixes 296-297.302
two dimensiono! 154-156
t a n fundxm 113,458
t a n h f urutu m 113,458
- v command hne argument 500
T * vobkhon. Michael T. 20
volxl cohimn nome 171-17Z 177, 185
tanpbte
volxlotian. dito 1Z 46,93, 118
furometer doti 147-148. 150 475
V m W y k . C h r K j . xxi
set dou 147, 150 474
Vjndevbei. Robert J. 20
tanp<rory file 485
v a r _ b o u n d s a p t x i n 279.486
t i mo funetum 458
v*ioble
t i mas option 250
dito 16Z 398.477
timifç prometer*. table af b\ák~m 496 declaratian 5. 8. 46<v-467
TOPDIR option 285.485 vxiaMcs xv, Z 129-132
t o ottnbule .334. 336. 338. 341,353,361, botrndt on 10.14. 17. 32,35, 130 139,
363, 467 241-242, 276. 279, 466. 470-471. 486
tocano defined 466-468
constraint declaratian 356,362,468 duo! 162,243,468.472,485
objective functxin 36 Z 470 environmcnt 205,481
taleronee, fcosihility 281 fued 131,241,402
( t r j . l o b l c trjnspõtilKin 3 Z 155. 157. inául values o f 131, 16Z 398. 405.
228-229, 475-476 408-409.466.471. 477,486
troffic flow ser max «mum flow modcl mául vakicsofduil 185. 468. 47Z 477,
txxnsiti\e ckisureof graph 462 486
tunsp<rtoti(m modcl 44-49.52.330-3.33 nonlincar 397-400
integer salutxim in 51.439-448 nomegative 3. 10.45. 130 377
mui ticxmmodi ty 56-59, 450 primai 243.398.485
rxinlmear 403-410 scoling cif 410
piecewise lineor 366-369 substitution o f 399-400.414
produetum ond 63-67 zero one 439-418
i«x 517

verter .weme di mentiu rui sei pwirtey reserved 74. 112


v e r b o . e e al tribute 200 Wrifiht
v e r s i o n optkin 500 Mor corei H. xxi. 410
viewing dati . w d i s p l o y command Stcphcn J. 410
Vignab. iuliam xxi wr i t e
Vukhac. Tfcang xxi command 487
L a b l e command 178.186.477
v M W . a a p l . o c a xviü, xx, 19, 453
Waren. Alixn 414
w h i l e condition 26Z 267,494
while spice 144,453. 413 . x l s Excel filemme extension 199-200
wild card • 205,481 x r e í command 213,247,492
WiHmv Hert 411
Willums. I« Paul 67 /ero
Willúrd. Mork 411 piecewise linear funclxinal 367, 376
w i L h i n operator 78. 93, 97-98. 114. suppressx>n 231-232
456-457. 462 zero o ix- programmirç .wr integer
Wokcy, l.aurence A . 450 programming
word* /eroone variables 439-448
predefined 74. 112.454 /cio-or mmimum restriction* 444

You might also like