Sunteți pe pagina 1din 13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization


English

Technicaltopics

Evaluationsoftware

Community

Signin(orregister)

Events

TheGNULinearProgrammingKit,Part1:Introductiontolinear
optimization
Findthebestsolutionstocomplexnumericproblems
RodrigoCeron(rceron@br.ibm.com),StaffSoftwareEngineer,IBM,SoftwareGroup
Summary:TheGNULinearProgrammingKitisapowerful,proventoolforsolvingnumericproblemswithmultipleconstraints.ThisarticleintroducesGLPK,
theglpsolclientutility,andtheGNUMathProglanguagetosolvetheproblemofoptimizingtheoperationsforGiapetto'sWoodcarving,Inc.,afictionaltoy
manufacturer.
Date:08Aug2006
Level:Intermediate
Alsoavailablein:RussianJapanesePortuguese
Activity:65860views
Comments:5(View|AddcommentSignin)
Averagerating(226votes)
Ratethisarticle
Introduction
"Linearprogrammingisatoolforsolvingoptimizationproblems.In1947,GeorgeDantzigdevelopedanefficientmethod,thesimplexalgorithm,for
solvinglinearprogrammingproblems.Sincethedevelopmentofthesimplexalgorithm,linearprogramminghasbeenusedtosolveoptimization
problemsinindustriesasdiverseasbanking,education,forestry,petroleum,andtrucking.InasurveyofFortune500firms,85%oftherespondents
saidtheyhadusedlinearprogramming."
FromOperationsResearch:ApplicationsandAlgorithms,4thEdition,byWayneL.Winston(Thomson,2004)seeResourcesbelowforalink.
Manytoolsareavailabletosolvelinearprogrammingproblems.Theproprietarytoolsarewellknown,butmanymembersoftheopensourcecommunitymaynot
knowaboutthefreeGLPKtool.
ThefirstinaseriesofthreearticlesthatshowGLPK'scapabilitiesandusage,thisarticlebrieflydescribesGLPKandthendemonstratesandappliestheGNU
MathProgLanguageinGLPK.
Ifyouarejuststartingwithoperationsresearchtheoryandwanttolearnhowtomodelandsolvelinearproblems,thisarticleisagoodguide.
TheGNULinearProgrammingKit
TheGNULinearProgrammingKit(GLPK)isalibraryofroutinesthatusewellknownoperationsresearchalgorithmstosolvelinearproblems.Theroutines
implementthesimplex,branchandbound,primaldualinteriorpoint,andmanyotheralgorithms.ChecktheGLPKmanualincludedwiththeGLPKdownloadto
findoutmore.(TodownloadtheGLPK,seetheResourcessectionforalinktotheGLPKpageongnu.org.)
GLPKisnotaprogramitcan'tberunandhasnomain()function.Instead,clientsfeedtheproblemdatatothealgorithmicroutinesthroughtheGLPKAPI
andreceiveresultsback.GLPKhasadefaultclient,theglpsolprogram,thatinterfaceswiththisAPI.Usually,aprogramlikeglpsoliscalledasolverratherthana
client,soyou'llseethisnomenclaturefromhereforward.
TheGNUMathProgmodelinglanguage
TheGNUMathProgmodelinglanguageisniceandsimplefordeclaringlinearproblems.Ingeneral,aproblemdeclarationconsistsof:
Problemdecisionvariables.
Anobjective(target)function.Notethatobjectiveisanoun,notanadjective.Thenameisstandardinoperationsresearchtheory.
Problemconstraints.
Problemparameters(data).

www.ibm.com/developerworks/linux/library/l-glpk1/

1/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Let'sstartwithasimpletwovariableexample:Giapetto'sWoodcarving,Inc.
Giapetto'sWoodcarvingInc.
ThisproblemisfromOperationsResearch:
Giapetto'sWoodcarvingInc.manufacturestwotypesofwoodentoys:soldiersandtrains.Asoldiersellsfor$27anduses$10worthofrawmaterials.
EachsoldierthatismanufacturedincreasesGiapetto'svariablelaborandoverheadcostsby$14.Atrainsellsfor$21anduses$9worthofraw
materials.EachtrainbuiltincreasesGiapetto'svariablelaborandoverheadcostsby$10.Themanufactureofwoodensoldiersandtrainsrequirestwo
typesofskilledlabor:carpentryandfinishing.Asoldierrequires2hoursoffinishinglaborand1hourofcarpentrylabor.Atrainrequires1hourof
finishingand1hourofcarpentrylabor.Eachweek,Giapettocanobtainalltheneededrawmaterialbutonly100finishinghoursand80carpentry
hours.Demandfortrainsisunlimited,butatmost40soldierareboughteachweek.Giapettowantstomaximizeweeklyprofits(revenuescosts).
Tosummarizetheimportantinformationandassumptionsaboutthisproblem:
1.
2.
3.
4.
5.
6.
7.

Therearetwotypesofwoodentoys:soldiersandtrains.
Asoldiersellsfor$27,uses$10worthofrawmaterials,andincreasesvariablelaborandoverheadcostsby$14.
Atrainsellsfor$21,uses$9worthofrawmaterials,andincreasesvariablelaborandoverheadcostsby$10.
Asoldierrequires2hoursoffinishinglaborand1hourofcarpentrylabor.
Atrainrequires1houroffinishinglaborand1hourofcarpentrylabor.
Atmost,100finishinghoursand80carpentryhoursareavailableweekly.
Theweeklydemandfortrainsisunlimited,while,atmost,40soldierswillbesold.

Thegoalistofindthenumbersofsoldiersandtrainsthatwillmaximizetheweeklyprofit.
Modeling
Tomodelalinearproblem,thedecisionvariablesareestablishedfirst,sincetheywillchangewitheachiterationofthesimplexalgorithmanddeterminethevalueof
theobjectivefunctionand,hence,theoptimalsolution.InGiapetto'sshop,theobjectivefunctionistheprofit,whichisafunctionoftheamountofsoldiersand
trainsproducedeachweek.Therefore,thetwodecisionvariablesinthisproblemare:
x1:Numberofsoldiersproducedeachweek
x2:Numberoftrainsproducedeachweek

Oncethedecisionvariablesareknown,theobjectivefunctionofthisproblemissimplytherevenueminusthecostsforeachtoy,asafunctionofx1andx2.

Notethattheprofitdependslinearlyonx1andx2thisisalinearproblem.
Itmayseematfirstglancethattheprofitcanbemaximizedbysimplyincreasingx1andx2.Well,iflifewerethateasy,let'sstartmanufacturingtrainsandsoldiers
andmovetotheCaribbean!Unfortunately,therearerestrictionsthatlimitthedecisionvariablesthatmaybeselected(orelsethemodelisverylikelytobewrong).
Recalltheassumptionsmadeforthisproblem.Thefirstthreedeterminedthedecisionvariablesandtheobjectivefunction.Thefourthandsixthassumptionsaythat
finishingthesoldiersrequirestimeforcarpentryandfinishing.ThelimitationhereisthatGiapettodoesn'thaveinfinitecarpentryandfinishinghours.That'sa
constraint!Let'sanalyzeittoclarify.
Onesoldierrequires2hoursoffinishinglabor,andGiapettohasatmost100hoursoffinishinglaborperweek,sohecan'tproducemorethan50soldiersper
week.Similarly,thecarpentryhoursconstraintmakesitimpossibletoproducemorethan80soldiersweekly.Noteherethatthefirstconstraintisstricterthanthe
second.Thefirstconstraintiseffectivelyasubsetofthesecond,thusthesecondconstraintisredundant.
Thepreviousparagraphshowshowtomodeloptimizationproblems,butit'sanincompleteanalysisbecauseallthenecessaryvariableswerenotconsidered.It's
notthecompletesolutionoftheGiapettoproblem.Sohowshouldtheproblembeapproached?
Startbyanalyzingthelimitingfactorsfirstinordertofindtheconstraints.First,whatconstrainsthefinishinghours?Sincebothsoldiersandtrainsrequirefinishing
time,bothneedtobetakenintoaccount.Supposethat10soldiersand20trainswerebuilt.Theamountoffinishinghoursneededforthatwouldbe10times2
hours(forsoldiers)plus20times1hour(fortrains),foratotalof40hoursoffinishinglabor.Thegeneralconstraintintermsofthedecisionvariablesis:

www.ibm.com/developerworks/linux/library/l-glpk1/

2/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Therearemany(x1,x2)pairsthatsatisfythisinequality,sothisdoesnotdeterminethebestcombinationforGiapetto'sshop.
Nowthattheconstraintforthefinishinghoursisready,thecarpentryhoursconstraintisfoundinthesamewaytobe:

Great!There'sonlyonemoreconstraintforthisproblem.Remembertheweeklydemandforsoldiers?Accordingtotheproblemdescription,therecanbeatmost
40soldiersproducedeachweek:

Thedemandfortrainsisunlimited,sonoconstraintcanbewrittenforit.Themodelisfinishedandconsistsoftheequations:

Notethelastconstraint.Itensuresthatthevaluesofthedecisionvariableswillalwaysbepositive.Theproblemdoesnotstatethisexplicitly,butit'sstillimportant
(andobvious).
NowGLPKcansolvethemodel(sinceGLPKisgoodatsolvinglinearoptimizationproblems).
Alittlebitoftheory
Let'schecktheproblem'ssolutionspace.Withtwodecisionvariables,ithastwodimensions.
Figure1.Giapetto'sunboundeduniverse

The(x1,x2)solutionsoutsidethefirstquadrant(whereallvaluesarepositive)havealreadybeendiscarded.Note,however,thatthissolutionspaceisstillinfinite
(thatwouldbeasituationinwhichI'dmovetotheCaribbean!)
Astheconstraintswerewritten,thisunlimitedsolutionspacegainedboundaries.Withinequality6,above,theresultismoreinteresting.

www.ibm.com/developerworks/linux/library/l-glpk1/

3/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Figure2.Giapetto'suniverseconsideringthefinishingconstraint

Thesolutionspacecontainsallthepossible(x1,x2)solutionsinthefirstquadrantthatsatisfythefinishinghoursconstraint.
Afterinequality7,theresultsetshrinks.
Figure3.Giapetto'suniverseconsideringthefinishingandcarpentryconstraints

Notethatthesolutionspaceissmaller.Thismeansthatevenfewer(x1,x2)solutionsareinit.Afterinequality8,theresultisevensmaller.
Figure4.Giapetto'sfeasibleregion

www.ibm.com/developerworks/linux/library/l-glpk1/

4/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Thesolutionspacegetssmallerstill.Thesolutionspacethatsatisfiesalltheconstraintsiscalledthefeasibleregion.Figure4showsthefeasibleregionfor
Giapetto'sshop.Any(x1,x2)pairthatfallsintothatregionisapotentialsolutiontotheproblem.
Thequestionnowis:whichonemaximizesGiapetto'sprofit?
UsingGLPKtosolvethemodel
GLPKisanexcellenttooltosolvethatquestion.ThemathematicalformulationofGiapetto'sproblemneedstobewrittenwiththeGNUMathProglanguage.The
keyitemstodeclareare:
Thedecisionvariables
Theobjectivefunction
Theconstraints
Theproblemdataset
ThefollowingcodeshowshowtosolveGiapetto'sproblemwithMathProg.Thelinenumbersinthiscodearenotpartofthecodeitself.Theyhavebeenadded
onlyforthesakeofmakingreferencestothecode.
Listing1.FirstsolutiontoGiapetto'sproblem:giapetto.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#
# Giapetto's problem
#
# This finds the optimal solution for maximizing Giapetto's profit
#
/* Decision variables */
var x1 >=0; /* soldier */
var x2 >=0; /* train */
/* Objective function */
maximize z: 3*x1 + 2*x2;
/* Constraints */
s.t. Finishing : 2*x1 + x2 <= 100;
s.t. Carpentry : x1 + x2 <= 80;
s.t. Demand
: x1 <= 40;
end;

Lines1through5arecomments.#anywhereonalinebeginsacommenttotheendoftheline.Cstylecommentscanalsobeused,asshownonline7.Theyeven
workinthemiddleofadeclaration.
ThefirstMathProgstepistodeclarethedecisionvariables.Lines8and9declarex1andx2.Adecisionvariabledeclarationbeginswiththekeywordvar.To
simplifysignconstraints(checkinequality9),MathProgallowsa>= 0constraintinthedecisionvariabledeclaration,asseenonlines8and9.Everysentencein
GNUMathProgmustendwithasemicolon(;).Recallthatx1representssoldiernumbersandx2representstrainnumbers.Thesevariablescouldhavebeen

www.ibm.com/developerworks/linux/library/l-glpk1/

5/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

calledsoldiersandtrains,butthatwouldconfusethemathematiciansintheaudience.
Line12declaresthetarget(objective)function.Linearproblemscanbeeithermaximizedorminimized.Remember,Giapetto'smathematicalmodelisa
maximizationproblem,sothekeywordmaximizeisappropriateinsteadoftheoppositekeyword,minimize.Theobjectivefunctionisnamedzandequals3x1
+ 2x2.Notethat:
Thecolon(:)characterseparatesthenameoftheobjectivefunctionanditsdefinition.
Theasterisk(*)characterdenotesmultiplicationand,similarly,theplus(+),minus(-),andforwardslash(/)charactersdenoteaddition,subtraction,and
divisionasyou'dexpect.
Lines15,16,and17definetheconstraints.Althoughs.t.isnotrequiredatthebeginningofthelinetodeclareaconstraint,itimprovesthereadabilityofthe
code.
ThethreeGiapettoconstraintshavebeenlabeledFinishing,Carpentry,andDemand.Eachofthemisdeclaredasinthemathematicalmodel.Thesymbols<=
and>=expresstheinequalities.Don'tforgetthe;attheendofeachdeclaration.
EveryGNUMathProgfilemustendwithend;,asseenonline19.
Now,glpsolcanusethisfileasinput.Butwaitaminutewhere'sthedatasectionofthisproblem?Well,thisproblemissosimplethattheproblemdataisdirectly
includedintheobjectivefunctionandconstraintsdeclarationsasthecoefficientsofthedecisionvariablesinthedeclarations.Forexample,intheobjectivefunction,
thecoefficients3and1arepartoftheproblem'sdataset.WhenIrewritethisproblemusingadataset,itwillbecomeclearhowitworksfornow,don'tworry
aboutit.
It'sgoodpracticetousethe.modextensionforMathProginputfilesandredirectthesolutiontoafilewiththeextension.sol.Thisisnotarequirementyoucan
useanyfilenameandextensionyoulike.Giapetto'sMathProgfileforthisexamplewillbegiapetto.mod,andtheoutputwillbeingiapetto.sol.Now,run
glpsolinyourfavoriteconsole:
glpsol -m giapetto.mod -o giapetto.sol

Thiscommandlineusestwoglpsoloptions:
The-moptiontellsglpsolthattheinputiswritteninGNUMathProg.
The-ooptiontellsglpsoltosenditsoutputtogiapetto.sol.
Thesolutionreportwillbeingiapetto.sol,butsomeinformationaboutthetimeandmemoryGLPKconsumedisshownonthesystem'sstandardoutput:
Listing2.Outputfromglpsol
ceron@curly ~ $ glpsol -m giapetto.mod -o giapetto.sol
Reading model section from giapetto.real.mod...
19 lines were read
Generating z...
Generating Finishing...
Generating Carpentry...
Generating Demand...
Model has been successfully generated
lpx_simplex: original LP has 4 rows, 2 columns, 7 non-zeros
lpx_simplex: presolved LP has 2 rows, 2 columns, 4 non-zeros
lpx_adv_basis: size of triangular part = 2
*
0: objval = 0.000000000e+00 infeas = 0.000000000e+00 (0)
*
2: objval = 1.400000000e+02 infeas = 0.000000000e+00 (0)
OPTIMAL SOLUTION FOUND
Time used: 0.0 secs
Memory used: 0.1M (151326 bytes)
lpx_print_sol: writing LP problem solution to `giapetto.sol'...

Thereportshowsthatglpsolreadsthemodel,callsaGLPKAPIfunctiontogeneratetheobjectivefunction,thencallsanotherAPIfunctiontogeneratethe
constraints.Afterthemodelhasbeengenerated,glpsolexplainsbrieflyhowtheproblemwashandledinternallybyGLPK.Attheend,there'sinformationaboutthe
solutionandtheresourcesusedbyGLPKtosolveit,andthesolutionisnotedtobeoptimal.
Great,butwhataretheactualoptimalvaluesforthedecisionvariables?Theyareinthegiapetto.solfile:
Listing3.ThesolutiontoGiapetto'sproblem:giapetto.sol
Problem:
Rows:
Columns:
Non-zeros:

giapetto
4
2
7

www.ibm.com/developerworks/linux/library/l-glpk1/

6/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Status:
OPTIMAL
Objective: z = 180 (MAXimum)
No. Row name St Activity
Lower bound Upper bound
Marginal
------ ------------ -- ------------- ------------- ------------- ------------1z
B
180
2 Finishing
NU
100
100
1
3 Carpentry
NU
80
80
1
4 Demand
B
20
40
No. Column name St Activity
Lower bound Upper bound
Marginal
------ ------------ -- ------------- ------------- ------------- ------------1 x1
B
20
0
2 x2
B
60
0
Karush-Kuhn-Tucker optimality conditions:
KKT.PE: max.abs.err. = 0.00e+00 on row 0
max.rel.err. = 0.00e+00 on row 0
High quality
KKT.PB: max.abs.err. = 0.00e+00 on row 0
max.rel.err. = 0.00e+00 on row 0
High quality
KKT.DE: max.abs.err. = 0.00e+00 on column 0
max.rel.err. = 0.00e+00 on column 0
High quality
KKT.DB: max.abs.err. = 0.00e+00 on row 0
max.rel.err. = 0.00e+00 on row 0
High quality
End of output

Thesolutionisdividedintofoursections:
Informationabouttheproblemandtheoptimalvalueoftheobjectivefunction
Preciseinformationaboutthestatusoftheobjectivefunctionandabouttheconstraints
Preciseinformationabouttheoptimalvaluesforthedecisionvariables
Informationabouttheoptimalityconditions,ifany
Forthisparticularproblem,weseethatthesolutionisOPTIMALandthatGiapetto'smaximumweeklyprofitis$180.
TheFinishingconstraint'sstatusisNU(theStcolumn).NUmeansthatthere'sanonbasicvariableontheupperboundforthatconstraint.Ifyouknowsome
operationresearchtheory,buildthesimplextableauandcheckitout.Ifyoudon't,here'saabriefpracticalexplanation.
Wheneveraconstraintreachesitsupperorlowerboundary,it'scalledaboundedconstraint.Aboundedconstraintpreventstheobjectivefunctionfromreaching
abettervalue.Thinkofitasavolumeknob,forexample,thatcan'tbeturnedanyfurther.Whenthatoccurs,glpsolshowsthestatusoftheconstraintaseitherNU
orNL(forupperandlowerboundaryrespectively),anditalsoshowsthevalueofthemarginal,alsoknownastheshadowprice.Themarginalisthevalueby
whichtheobjectivefunctionwouldimproveiftheconstraintwererelaxedbyoneunit(ifthevolumeknobcouldturnalittlemore).Notethattheimprovement
dependsonwhetherthegoalistominimizeormaximizethetargetfunction.Forinstance,inGiapetto'sproblem,whichseeksmaximization,themarginalvalue1
meansthattheobjectivefunctionwouldincreaseby1ifwecouldhaveonemorehouroffinishinglabor(weknowit'sonemorehourandnotoneless,because
thefinishinghoursconstraintisanupperboundary).
Thecarpentryandsoldierdemandconstraintsaresimilar.Forthecarpentryconstraint,notethatit'salsoanupperboundary.Therefore,arelaxationofoneunitin
thatconstraint(anincrementofonehour)wouldmaketheobjectivefunction'soptimalvaluebecomebetterbythemarginalvalue1andbecome181.
Thesoldierdemand,however,isnotbounded,thusitsstateisB,andarelaxationinitwillnotchangetheobjectivefunction'soptimalvalue.
Tryrelaxingthevalueofeachboundedconstraintoneatatime,solvethemodifiedproblem,andseewhathappenstotheoptimalvalueoftheobjectivefunction.
Alsocheckthatchangingthevalueofunboundedconstraintswon'tmakeanydifferencetothesolution,asexpected.
Finally,glpsol'sreportshowsthevaluesforthedecisionvariables:x1 = 20andx2 = 60.ThistellsGiapettothatheshouldproduce20soldiersand60trainsto
maximizehisweeklyprofit.
Giapetto'sproblemwasverysmall.Youmaybewondering,inaproblemwithmanymoredecisionvariablesandconstraints,wouldyouhavetodeclareeach
variableandeachconstraintseparately?Andwhatifyouwantedtoadjustthedataoftheproblem,suchasthesellingpriceofasoldier?Doyouhavetomake
changeseverywherethisvalueappears?Thenextsectiondiscussesthat.
UsingmodelanddatasectionsinGiapetto'sproblem

www.ibm.com/developerworks/linux/library/l-glpk1/

7/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

MathProgmodelsnormallyhaveamodelsectionandadatasection,sometimesintwodifferentfiles.Thus,glpsolcansolveamodelwithdifferentdatasetseasily,
tocheckwhatthesolutionwouldbewiththisnewdata.ThefollowinglistingstatesGiapetto'sprobleminamuchmoreelegantway:
Listing4.Giapetto'sproblemwithamodelandadatasection:giapetto2.mod
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

#
# Giapetto's problem
#
# This finds the optimal solution for maximizing Giapetto's profit
#
/* Set of toys */
set TOY;
/* Parameters */
param Finishing_hours {i in TOY};
param Carpentry_hours {i in TOY};
param Demand_toys
{i in TOY};
param Profit_toys
{i in TOY};
/* Decision variables */
var x {i in TOY} >=0;
/* Objective function */
maximize z: sum{i in TOY} Profit_toys[i]*x[i];
/* Constraints */
s.t. Fin_hours : sum{i in TOY} Finishing_hours[i]*x[i] <= 100;
s.t. Carp_hours : sum{i in TOY} Carpentry_hours[i]*x[i] <= 80;
s.t. Dem {i in TOY} : x[i] <= Demand_toys[i];
data;
/* data section */
set TOY := soldier train;
param Finishing_hours:=
soldier
2
train
1;
param Carpentry_hours:=
soldier
1
train
1;
param Demand_toys:=
soldier
40
train
6.02E+23;
param Profit_toys:=
soldier
3
train
2;
end;

Ratherthantwoseparatefiles,theproblemisstatedinasinglefilewithamodelingsection(lines1through27)andadatasection(lines28through49).
Line8definesaSET.ASETisauniverseofelements.Forexample,ifIdeclaremathematicallyxi, for all i in {1;2;3;4},I'msayingthatxisanarraythat
rangesfrom1to4,andthereforewehavex1,x2,x3,x4.Inthiscase,{1;2;3;4}istheset.So,inGiapetto'sproblem,there'sasetcalledTOY.Wherearethe
actualvaluesofthisset?Inthedatasectionofthefile.Checkline31.ItdefinestheTOYsettocontainsoldierandtrain.Wow,thesetisnotanumericalrange.
Howcanthatbe?GLPKhandlesthisinaninterestingway.You'llseehowtousethisinafewmoments.Fornow,getusedtothesyntaxforSETdeclarationsin
thedatasection:
setlabel:=value1value2...valueN;

Lines11,12,and13definetheparametersoftheproblem.Therearethree:Finishing_hours,Carpentry_hours,andDemand_toys.Theseparameters
makeuptheproblem'sdatamatrixandareusedtocalculatetheconstraints,asyou'llseelater.
TaketheFinishing_hoursparameterasanexample.It'sdefinedontheTOYset,soeachkindoftoyintheTOYsetwillhaveavalueforFinishing_hours.
Rememberthateachsoldierrequires2hoursoffinishingwork,andeachtrainrequires1houroffinishingwork.Checklines33,34,and35now.Thereisthe
definitionofthefinishinghoursforeachkindoftoy.Essentially,thoselinesdeclarethatFinishing_hours[soldier]=2andthat
Finishing_hours[train]=1.Finishing_hoursis,therefore,amatrixwith1rowand2columns.
Carpentryhoursanddemandparametersaredeclaredsimilarly.Notethatthedemandfortrainsisunlimited,soaverylargevalueistheupperboundonline43.

www.ibm.com/developerworks/linux/library/l-glpk1/

8/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Doesthatvalueseemfamoleiartoyou?
Line17declaresavariable,x,foreveryiinTOY(resultinginx[soldier]andx[train]),andconstrainsthemtobegreaterthanorequaltozero.Onceyou
havesets,it'sprettyeasytodeclarevariables,isn'tit?
Line20declarestheobjective(target)functionasthemaximizationofz,whichisthetotalprofitforeverykindoftoy(therearetwo:trainsandsoldiers).With
soldiers,forexample,theprofitisthenumberofsoldierstimestheprofitpersoldier.
Theconstraintsonlines23,24,and25aredeclaredinasimilarway.Takethefinishinghoursconstraintasanexample:it'sthetotalofthefinishinghoursperkind
oftoy,timesthenumberofthatkindoftoyproduced,forthetwotypesoftoys(trainsandsoldiers),anditmustbelessthanorequalto100.Similarly,thetotal
carpentryhoursmustbelessthanorequalto80.
Thedemandconstraintisalittlebitdifferentthantheprevioustwo,becauseit'sdefinedforeachkindoftoy,notasatotalforalltoytypes.Therefore,weneedtwo
ofthem,onefortrainsandoneforsoldiers,asyoucanseeonline25.Notethattheindexvariable({i in TOY})comesbeforethe:.ThistellsGLPKtocreate
aconstraintforeachtoytypeinTOY,andtheequationthatwillruleeachconstraintwillbewhatcomesafterthe:.Inthiscase,GLPKwillcreate
Dem[soldier] : x[soldier] <= Demand[soldier]
Dem[train] : x[train] <= Demand[train]

Solvingthisnewmodelmustyieldthesameresults:
Listing5.ThesolutiontoGiapetto'sproblemwithadatasection:giapetto2.sol
Problem:
Rows:
Columns:
Non-zeros:
Status:
Objective:

giapetto2
5
2
8
OPTIMAL
z = 180 (MAXimum)

No. Row name St Activity


Lower bound Upper bound
Marginal
------ ------------ -- ------------- ------------- ------------- ------------1z
B
180
2 Fin_hours
NU
100
100
1
3 Carp_hours NU
80
80
1
4 Dem[soldier] B
20
40
5 Dem[train] B
60
6.02e+23
No. Column name St Activity
Lower bound Upper bound
Marginal
------ ------------ -- ------------- ------------- ------------- ------------1 x[soldier] B
20
0
2 x[train]
B
60
0
Karush-Kuhn-Tucker optimality conditions:
KKT.PE: max.abs.err. = 0.00e+00 on row 0
max.rel.err. = 0.00e+00 on row 0
High quality
KKT.PB: max.abs.err. = 0.00e+00 on row 0
max.rel.err. = 0.00e+00 on row 0
High quality
KKT.DE: max.abs.err. = 0.00e+00 on column 0
max.rel.err. = 0.00e+00 on column 0
High quality
KKT.DB: max.abs.err. = 0.00e+00 on row 0
max.rel.err. = 0.00e+00 on row 0
High quality
End of output

NotehowtheconstraintsandthedecisionvariablesarenownamedaftertheTOYset,whichlookscleanandorganized.Verygood.Youhavemaximized
Giapetto'sprofit!
Conclusion
You'veseenhowtoformulateasimple,twovariablelinearproblem.ThenyousawhowtouseasimpleMathProgprogramtosolveitusingsets,parameters,
constraints,decisionvariables,andanobjective(target)function.Theprogramusedsummationoversetsandaparametersdatasection.Finally,youlearnedhow

www.ibm.com/developerworks/linux/library/l-glpk1/

9/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

tointerprettheresultsofamaximizationproblem.
Thenextinstallmentinthisthreearticleserieswillshowyouhowtomakethemostoutofabaddiet.

Download
Description
Solutionstotheproblem

Name
solutions.zip

Size
1KB

Downloadmethod
HTTP

Informationaboutdownloadmethods

Resources
Learn
TheproblemsinthisarticlearetakenwithpermissionfromOperationsResearch:ApplicationsandAlgorithms,4thEdition,byWayneL.Winston
(Thomson,2004).
TheonlinedocumentationforGLPKgivesmoreinformationaboutGLPK,howtogetthesoftware,andhowtojointheGLPKcommunity.
CheckouttheWikipediaentryforGLPK.
SubscribetotheGLPKhelpmailinglistorbugreportsmailinglist.
InthedeveloperWorksLinuxzone,findmoreresourcesforLinuxdevelopers.
StaycurrentwithdeveloperWorkstechnicaleventsandWebcasts.
Getproductsandtechnologies
WithIBMtrialsoftware,availablefordownloaddirectlyfromdeveloperWorks,buildyournextdevelopmentprojectonLinux.
Discuss
CheckoutdeveloperWorksblogsandgetinvolvedinthedeveloperWorkscommunity.
Abouttheauthor

RodrigoCeronFerreiradeCastroisaStaffSoftwareEngineerattheIBMLinuxTechnologyCenter.HegraduatedfromtheStateUniversityofCampinas
(UNICAMP)in2004.HereceivedtheStateEngineeringInstituteprizeandtheEngineeringCouncilCertificationofHonorwhenhegraduated.He'sgiven
speechesinopensourceconferencesinBrazilandothercountries.
Close[x]

developerWorks:Signin
IBMID:
NeedanIBMID?
ForgotyourIBMID?
Password:
Forgotyourpassword?

www.ibm.com/developerworks/linux/library/l-glpk1/

10/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

Changeyourpassword
Keepmesignedin.
ByclickingSubmit,youagreetothedeveloperWorkstermsofuse.
Submit

Cancel

ThefirsttimeyousignintodeveloperWorks,aprofileiscreatedforyou.SelectinformationinyourdeveloperWorksprofileisdisplayedtothepublic,but
youmayedittheinformationatanytime.Yourfirstname,lastname(unlessyouchoosetohidethem),anddisplaynamewillaccompanythecontentthatyou
post.
Allinformationsubmittedissecure.
Close[x]

Chooseyourdisplayname
ThefirsttimeyousignintodeveloperWorks,aprofileiscreatedforyou,soyouneedtochooseadisplayname.Yourdisplaynameaccompaniesthecontentyou
postondeveloperWorks.
Pleasechooseadisplaynamebetween331characters.YourdisplaynamemustbeuniqueinthedeveloperWorkscommunityandshouldnotbeyouremail
addressforprivacyreasons.
Displayname:

(Mustbebetween331characters.)

ByclickingSubmit,youagreetothedeveloperWorkstermsofuse.
Submit

Cancel

Allinformationsubmittedissecure.
Averagerating(226votes)
1star

1star

2stars

2stars

3stars

3stars

4stars

4stars

5stars

5stars

Submit

Addcomment:
Signinorregistertoleaveacomment.
Note:HTMLelementsarenotsupportedwithincomments.

Notifymewhenacommentisadded1000charactersleft

Post

Totalcomments(5)

www.ibm.com/developerworks/linux/library/l-glpk1/

11/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

@FJ2Fwouldcertainlybeaviablesolution,albeitnotanopenone.Therecanbecompellingreasonswhyonemightwanttostartwithanopenproduct.Thereare
alsogoodbusinessjustificationsforusingacommercialone.Ialwaysrecommendthatpeopleexploreallsidesofatechnologyandchooseonethatfitsthem.The
greatthingabouttheopenoptionisthatitmakestechnologyavailabletoeveryonewhowantstolearnaboutit,withnotrialperiod.
(editor)
Postedbycmw.osdudeon19June2012
Reportabuse
youmaywanttotryCPLEXStudiowithOPL(IBMproduct)...itdoesallwhatyoutalkabout...andabitmore...:)
PostedbyFJ2Fon18June2012
Reportabuse
JoseDelaCruz,thanksforthepostandforalertingustothebracketproblem.Wefixedthedisplayissue,butpleaseletusknowifthereareanyothererrors.(The
syntaxhighlightingwasintroducedautomaticallybyoursoftware.)
TomYoung
developerWorks
Postedbytomyoungon01April2010
Reportabuse
ATTENTION:theexampleabovemissessomesquarebrackets.Isupposethattheyareawaytoindicatetheeditoritshoudaddalink.So,inthedeclarationsof
ia,jaandardon'tforgettoputthemissingsquarebrakets.
Regards.
PostedbyJoseDelaCruzon31March2010
Reportabuse
<preclass="jivepre"><codeclass="jivecodejivejava"><fontcolor="darkgreen">//Thiswouldbethecprogramthatsolvestheproblemusingtheapi.</font>

#include<stdio.h>
#include<stdlib.h>
#include<glpk.h>

<fontcolor="navy"><b>int</b></font>main(<fontcolor="navy"><b>void</b></font>)
<fontcolor="navy">{</font>glp_problp
<fontcolor="navy"><b>int</b></font>ia[1+1000],ja[1+1000]
<fontcolor="navy"><b>double</b></font>ar[1+1000],z,x1,x2
lp=glp_create_prob()
glp_set_prob_name(lp,<fontcolor="red">"Carpinteria"</font>)
glp_set_obj_dir(lp,GLP_MAX)
glp_add_rows(lp,3)
glp_set_row_name(lp,1,<fontcolor="red">"f"</font>)
glp_set_row_bnds(lp,1,GLP_UP,0.0,100.0)
glp_set_row_name(lp,2,<fontcolor="red">"c"</font>)
glp_set_row_bnds(lp,2,GLP_UP,0.0,80.0)
glp_set_row_name(lp,3,<fontcolor="red">"r"</font>)
glp_set_row_bnds(lp,3,GLP_UP,0.0,40.0)
glp_add_cols(lp,2)
glp_set_col_name(lp,1,<fontcolor="red">"x1"</font>)
glp_set_col_bnds(lp,1,GLP_LO,0.0,0.0)
glp_set_obj_coef(lp,1,3.0)
glp_set_col_name(lp,2,<fontcolor="red">"x2"</font>)
glp_set_col_bnds(lp,2,GLP_LO,0.0,0.0)
glp_set_obj_coef(lp,2,2.0)

ia[1]=1,ja[1]=1,ar[1]=2.0<fontcolor="darkgreen">/*a[1,1]=2*/</font>
ia[2]=1,ja[2]=2,ar[2]=1.0<fontcolor="darkgreen">/*a[1,2]=1*/</font>
ia[3]=2,ja[3]=1,ar[3]=1.0<fontcolor="darkgreen">/*a[2,1]=1*/</font>

www.ibm.com/developerworks/linux/library/l-glpk1/

12/13

4/17/13

The GNU Linear Programming Kit, Part 1: Introduction to linear optimization

ia[4]=2,ja[4]=2,ar[4]=1.0<fontcolor="darkgreen">/*a[2,2]=1*/</font>
ia[5]=3,ja[5]=1,ar[5]=1.0<fontcolor="darkgreen">/*a[3,1]=1*/</font>
ia[6]=3,ja[6]=2,ar[6]=0.0<fontcolor="darkgreen">/*a[3,2]=0*/</font>

glp_load_matrix(lp,6,ia,ja,ar)

glp_simplex(lp,NULL)
z=glp_get_obj_val(lp)
x1=glp_get_col_prim(lp,1)
x2=glp_get_col_prim(lp,2)

printf(<fontcolor="red">"
z=%gx1=%gx2=%g
"</font>,
z,x1,x2)
glp_delete_prob(lp)
<fontcolor="navy"><b>return</b></font>0
<fontcolor="navy">}</font>
</code>
Editedby:adminonApr1,201010:59AM
PostedbyJoseDelaCruzon31March2010
Reportabuse
Printthispage

About

Sharethispage

Feeds

FollowdeveloperWorks

Reportabuse

Faculty

Help

Termsofuse

Students

Contactus

IBMprivacy

BusinessPartners

Submitcontent

IBMaccessibility

www.ibm.com/developerworks/linux/library/l-glpk1/

13/13

S-ar putea să vă placă și