·

Cursos Gerais ·

Pesquisa Operacional 2

Send your question to AI and receive an answer instantly

Ask Question

Preview text

CMPL ColiopCoin Mathematical Programming Language Version 112 March 2018 Manual M Steglich T Schleiff CMPL v112 Manual 1 Table of contents 1 About CMPL6 2 CMPL Language reference manual7 21 CMPL elements7 211 General structure of a CMPL model7 212 Keywords and other syntactic elements8 213 Objects9 2131 Parameters9 2132 Variables11 2133 Indices and sets13 2134 Line names15 214 CMPL header16 22 Parameter Expressions19 221 Overview19 222 Array functions19 223 Set operations and functions20 224 Mathematical functions22 225 Type casts24 226 String operations24 23 Input and output operations26 231 Error and user messages26 232 cmplData files27 233 Readcsv and readstdin31 234 Include32 24 Statements32 241 parameters and variables section33 242 objectives and constraints section33 25 Control structure34 251 Overview34 252 Control header35 2521 Iteration headers35 2522 Condition headers35 2523 Local assignments36 253 Alternative bodies37 254 Control statements38 255 Specific control structures39 2551 For loop39 2552 Ifthen clause40 2553 Switch clause40 2554 While loop41 256 Set and sum control structure as expression42 26 MatrixVector notations43 27 Automatic model reformulations46 CMPL v112 Manual 2 271 Overview46 272 Matrix reductions46 273 Equivalent transformations of Variable Products47 2731 Variable Products with at least one binary variable47 2732 Variable Product with at least one integer variable47 28 Examples49 281 Selected decision problems49 2811 The diet problem49 2812 Production mix51 2813 Production mix including thresholds and stepwise fixed costs54 2814 The knapsack problem56 2815 Transportation problem using 1tuple sets59 2816 Transportation problem using multidimensional sets 2tuple sets62 2817 Quadratic assignment problem64 2818 Quadratic assignment problem using the solutionPool option66 2819 Generic travelling salesman problem68 282 Other selected examples69 2821 Solving the knapsack problem69 2822 Finding the maximum of a concave function using the bisection method72 3 CMPL software package73 31 CMPL software package in a glance73 32 Installation73 33 CMPL73 331 Running CMPL73 332 Usage of the CMPL command line tool74 333 Syntax checks76 334 Using CMPL with several solvers77 3341 CBC77 3342 GLPK78 3343 Gurobi78 3344 SCIP79 3345 CPLEX80 3346 Other solvers81 34 Coliop82 35 CMPLServer85 351 Single server mode86 352 Grid mode89 353 Reliability and failover93 36 pyCMPL97 37 jCMPL97 38 Input and output file formats98 381 Overview98 382 CMPL and CmplData99 383 Free MPS99 CMPL v112 Manual 3 384 CmplInstance100 385 ASCII or CSV result files103 386 CmplSolutions104 387 CmplMessages107 388 CmplInfo109 4 CMPLs APIs110 41 Creating Python and Java applications with a local CMPL installation110 411 pyCMPL112 412 jCMPL115 42 Creating Python and Java applications using CMPLServer119 421 pyCMPL120 422 jCMPL121 43 pyCMPL reference manual122 431 CmplSets122 432 CmplParameters124 433 Cmpl126 4331 Establishing models126 4332 Manipulating models128 4333 Solving models129 4334 Reading solutions133 4335 Reading CMPL messages140 434 CmplExceptions141 44 jCMPL reference manual141 441 CmplSets141 442 CmplParameters144 443 Cmpl147 4431 Establishing models147 4432 Manipulating models148 4433 Solving models150 4434 Reading solutions154 4435 Reading CMPL messages159 444 CmplExceptions160 45 Examples161 451 The diet problem161 4511 Problem description and CMPL model161 4512 pyCMPL161 4513 jCmpl163 452 Transportation problem164 4521 Problem description and CMPL model164 4522 pyCMPL165 4523 jCMPL167 453 The shortest path problem169 4531 Problem description and CMPL model169 4532 pyCMPL171 CMPL v112 Manual 4 4533 jCMPL172 454 Solving randomized shortest path problems in parallel173 4541 Problem description173 4542 pyCMPL173 4543 jCMPL175 455 Column generation for a cutting stock problem178 4551 Problem description and CMPL model178 4552 jCMPL179 4553 jCMPL183 5 Authors and Contact189 6 Appendix190 61 Selected CBC parameters190 62 Selected GLPK parameters203 CMPL v112 Manual 5 1 About CMPL CMPL ColiopCoin Mathematical Programming Language is a mathematical programming language and a system for mathematical programming and optimisation of linear optimisation problems The CMPL syntax is similar in formulation to the original mathematical model but also includes syntactic ele ments from modern programming languages CMPL is intended to combine the clarity of mathematical mod els with the flexibility of programming languages CMPL executes CBC GLPK Gurobi SCIP or CPLEX directly to solve the generated model instance Because it is also possible to transform the mathematical problem into MPS FreeMPS or OSiL files alternative solvers can be used CMPL is an open source project licensed under GPL It is written in C and is available for most of the rel evant operating systems Windows OS X and Linux The CMPL distribution contains Coliop which is an simple IDE Integrated Development Environment for CMPL Coliop is an open source project licensed under GPL It is written in C and is as an integral part of the CMPL distribution The CMPL package also contains pyCMPL jCMPL and CMPLServer pyCMPL is the CMPL application programming interface API for Python and an interactive shell and jCMPL is CMPLs Java API The main idea of this APIs is to define sets and parameters within the user ap plication to start and control the solving process and to read the solutions into the application if the prob lem is feasible All variables objective functions and constraints are defined in CMPL These functionalities can be used with a local CMPL installation or a CMPLServer CMPLServer is an XMLRPCbased web service for distributed and grid optimisation that can be used with CMPL pyCMPL and jCMPL It is reasonable to solve large models remotely on the CMPLServer that is in stalled on a high performance system CMPL provides four XMLbased file formats for the communication between a CMPLServer and its clients CmplInstance CmplSolutions CmplMessages CmplInfo pyCMPL jCMPL and CMPLServer are licensed under LGPLv3 CMPL Coliop pyCMPL jCMPL and CMPLServer are COINOR projects initiated by the Technical University of Applied Sciences Wildau CMPL v112 Manual 6 2 CMPL Language reference manual 21 CMPL elements 211 General structure of a CMPL model The structure of a CMPL model follows the standard model of linear programming LP which is defined by a linear objective function and linear constraints Apart from the variable decision vector x all other compon ents are constant cTxmax st Axb x0 A CMPL model consists of four sections the parameters section the variables section the object ives section and the constraints section which can be inserted several times and mixed in a different order Each sector can contain one or more lines with userdefined expressions parameters definition of the parameters variables definition of the variables objectives definition of the objectives constraints definition of the constraints A typical LP problem is the production mix problem The aim is to find an optimal quantity for the products depending on given capacities The objective function is defined by the profit contributions per unit c and the variable quantity of the products x The constraints consist of the use of the capacities and the ranges for the decision variables The use of the capacities is given by the product of the coefficient matrix A and the vector of the decision variables x and restricted by the vector of the available capacities b The simple example 1x12x 23x3max st 56x177x 2105x 315 98x142x2111x320 0xn n113 can be formulated in CMPL as follows parameters c 1 2 3 b 15 20 A 56 77 105 CMPL v112 Manual 7 98 42 111 variables x1countc real objectives cT x max constraints A x b x 0 212 Keywords and other syntactic elements Keywords parameters variables objectives constraints section markers real integer binary types of variable real integer binary string set types only used for type casts max min objective senses set in len defset key words for sets max min count format type functions for parameter expressions sqrt exp ln lg ld srand rand sin cos tan acos asin atan sinh cosh tanh abs ceil floor round mathematical functions that can be used for para meter expressions include include of a CMPL file readcsv readstdin data import from a CSV file or from user input error echo error and user message sum summation continue break default repeat key words for control structures Arithmetic operators signs for parameters or additionsubtraction to the power of multiplication and division div mod integer division and remainder on division assignment operator Condition operators conditions for constraints whileloops and ifthen clauses additional conditions in whileloops and ifthen clauses CMPL v112 Manual 8 logical operations and or not element operator for checking whether an index is an element of a set Other syntactic elements arithmetical bracketing in constant expressions lists for initialising vectors of constants parameters for constant functions increment in an algorithmic set indexing of vectors range specification in variable definitions control structures algorithmic set eg range for indices or loop coun ters range specification in variable definitions element separation in an initialisation list for constant vectors and enumeration sets separation of function parameters separation of indices separation of loop heads in a loop mark indicating beginning of sections definition of variables definition of parameter type separation of loop header from loop body separation of line names separation of alternative blocks in a control struc ture mark indicating end of a statement every state ment is to be closed by a semicolon comment up to end of line comment between and 213 Objects 2131 Parameters A parameters section consists of parameter definitions and assignments to parameters A parameter can only be defined within the parameters section using an assignment or through using a cmplData file see 232 cmplData files and a corresponding CMPL header option Note that a parameter can be used as a constant in a linear optimisation model as coefficients in objectives and constraints Otherwise parameters can be used like variables in programming languages Parameters are CMPL v112 Manual 9 usable in expressions for instance in the calculation and definition of other parameters A user can assign a value to a parameter and can then subsequently change the value with a new assignment A parameter is identified by name and if necessary by indices A parameter can be a scalar or an array of parameter values eg vector matrix or another multidimensional construct A parameter is defined by an assignment with the assignment operator Usage name scalarExpression nameindex scalarExpression nameset arrayExpression name Name of the parameter index Indexing expression that defines a position in an array of parameters Described in 2133 Indices and sets scalarExpression A scalar parameter or a single part of an array of parameters is assigned a single integer or real number a single string the scalar result of a math ematical function set Optional set expression list of indices for the definition of the dimen sion of the array If more than one set is used then the sets have to be separated by com mas Described in 2133 Indices and sets arrayExpression A nonscalar expression consists of a list of scalarExpressions or arrayExpression The elements of the list are separated by commas and imbedded in brackets The elements of the list can also be sets But it is not possible to mix set and nonset expressions If an array contains only one element then it is necessary to include an additional comma behind the element Otherwise the expression is inter preted as an arithmetical bracket Examples k 10 parameter k with value 10 k15 05 1 2 33 55 k 05 1 2 33 55 vector of parameters with 5 elements A 16 454 definition of a vector with two integer values a116 and a245 CMPL v112 Manual 10 a 56 77 105 98 42 111 dense matrix with 2 rows and 3 columns b 22 definition of the vector b with only one element b 22 causes an error array dimensions dont match since 22 is not interpreted as an array but as an assignment of a scalar expression products set bike1 bike2 machineHoursproducts 54 10 defines a vector for machine hours based on the set products myString this is a string string parameter q 3 parameter q with value 3 g1q 1 2 3 usage of q for the definition of the parameter g x 112 y 112 z 112 cubexyz 1234 5678 definition of a parameter cube that is based on the sets xy and z a set 11122232 ba 10 20 30 40 definition of a sparse matrix b that is based on the 2 tuple set a If a name is used for a parameter the name cannot be used for a variable A special kind of parameter is local parameters which can only be defined within the head of a control struc ture A local parameter is only valid in the body of the control structure and can be used like any other para meter Only scalar parameters are permitted as local parameters Local parameters are mainly used as loop counters that are to be iterated over a set 2132 Variables The variables section is intended to declare the variables of a decision model which are necessary for the definition of objectives and constraints in the decision model A model variable is identified by name and if necessary by an index A type must be specified A model variable can be a scalar or a part of a vector a matrix or another array of variables A variable cannot be assigned a value Usage variables name type lowerBoundupperBound nameindex type lowerBoundupperBound nameset type lowerBoundupperBound CMPL v112 Manual 11 name name of model variable type type of model variable Possible types are real integer binary lowerBoundupperBound optional parameter for limits of model variable lowerBound and upperBound must be a real or integer expres sion For the type binary it is not possible to specify bounds index Indexing expression that defines a position in an array of variables Described in 2133 Indices and sets set Optional set expression list of indices for the definition of the di mension of the array If more than one set is used then the sets have to be separated by commas Described in 2133 Indices and sets Examples x real x is a real model variable with no ranges x real0100 x is a real model variable 0 x100 x15 integer1020 vector with 5 elements 10xn20n115 x151515 real0 a threedimensional array of real model variables with 125 elements identified by indices xi j k0i j k 115 parameters prod set bike1 bike2 variables xprod real0 defines a vector of nonnegative real model variables based on the set prod y binary x is a binary model variable y 01 parameters aset11122232 variables xa real0 defines a sparse matrix of nonnegative real model vari ables based on the set a of 2tupels Different indices may cause model variables to have different types eg the following is permissible vari ables x1 real x2 integer If a name is used for a model variable definition different usages of this name with indices can only refer to model variables and not to parameters CMPL v112 Manual 12 2133 Indices and sets Sets are used for the definitions of arrays of parameters or model variables and for iterations in loops In dices are necessary to identify an element of an array like a vector or matrix of parameters or variables An index is always an ntuple pair of n entries where n is the count of dimensions of an array Entries are single integers or strings If n1 then the entries have to be separated by commas Usage entry1 entry2 entryn nTuple A set is a collection of indices Sets can be defined by an enumeration of elements or by algorithms within the parameters section A set can be stored in a scalar parameter or in an element of an array of paramet ers A set can also be defined by using a cmplData file and a corresponding CMPL header option Usage of set definitions startNumberindecrementorendNumber algorithmic 1tuple set startNumberendNumber algorithmic 1tuple set integer algorithmic 1tuple set string algorithmic 1tuple set setentry1 entry2 entryn enumeration 1tuple set setntuple1 ntuple2 ntuplen enumeration n1tuple set startNumberindecrementorendNumber 1tuple set of integers based on an algorithm The set starts at the startNumber is changed by an in crementer or decrementer at every iteration and ends at the endNumber startNumberendNumber 1tuple set of integers based on an algorithm The set starts at the startNumber is changed by the number one at every iteration and ends at the endNum ber startNumber and endNumber are optional elements startNumber infinite 1tuple set with all integers greater than or equal to startNumber endNumber infinite 1tuple set with all integers less than or equal to endNumber infinite 1tuple set with all integers and strings integer infinite 1tuple set with all integers CMPL v112 Manual 13 string infinite 1tuple set with all strings setentry1 entry2 entryndefinition of a 1tuple enumeration set An enumeration 1tuple set consists of one or more in teger expressions or string expressions separated by com mas and embedded in brackets and is described by the key word set setntuple1ntuple2 definition of an ntuple enumeration set with n1 An enumeration n1tuple set consists of one or more tuples separated by commas and embedded in brackets and is described by the key word set Examples s s is assigned an infinite 1tuple set of all integers and strings s6 s is assigned s456 s6 s is assigned s678 s06 s016 s is assigned s01 6 s1024 s is assigned s10864 prod set bike1 bike2 enumeration 1tuple set of strings a set 1 a 3 b 5 c xa102030405060 enumeration 1tuple set of strings and integers vector x identified by the set a is assigned an integer vector echo x1 echo xa i in a echo xi The following user messages are displayed 10 20 10 20 30 40 50 60 a12 a is assigned a 2tuple of integers bp1p2 b is assigned a 2tuple of strings routes set111214 2223243133 routes is assigned a 2tuple set of integers croutes3 2 6 5 2 3 2 4 The parameter array is defined over routes and is as signed 3 2 6 5 2 3 2 4 ij in routes echo ij cij The following user messages are displayed 11 3 12 2 14 6 22 5 23 2 24 3 31 2 33 4 CMPL v112 Manual 14 2134 Line names Line names are useful in huge models to provide a better overview of the model In CMPL a line name can be defined by characters numbers and the underscore character followed by a colon Names that are used for parameters or model variables cannot be used for a line name Within a control structure a line name can include the current value of local parameters This is especially useful for local parameters which are used as a loop counter Usage lineName lineNamek lineName1 lineName2 loopName controlStructure lineName Defines a line name for a single row of the model If more than one row is to be generated by CMPL then the line names are extended by numbers in natural order k k is replaced by the value of the local parameter k 1 1 is replaced by the number of the current line of the matrix 2 In an implicit loop 2 is replaced by the specific value of the free in dex loopNamecontrolStructure Defines a line name subject to the following control structure The val ues of loop counters in the control structure are appended automatic ally Examples parameters A1213 123456 b12 100100 c13 201010 variables x13 real0 objectives profit cT x max generates a line profit constraints restriction A x b generates 2 lines restriction1 restriction2 CMPL v112 Manual 15 i112 restrictioni Axb generates 2 lines restriction1 restriction2 restriction i113 Axb generates 2 lines restriction1 restriction2 parameters productssetP1 P2 P3 machinessetM1M2 Amachinesproducts 123 456 bmachines 100100 cproducts 201010 variables xproducts real0 objectives profit cT x max constraints capa2 A x b generates 3 lines profit capaM1 capaM2 214 CMPL header A CMPL header is intended to define CMPL options solver options and display options for the specific CMPL model An additional intention of the CMPL header is to specify external data files which are to be connected to the CMPL model The elements of the CMPL header are not part of the CMPL model and are processed before the CMPL model is interpreted Usage CMPL header for CMPL options solver options and display options arg optionName optionValue CMPL options opt solverName solverOption solverOptionValue Solver options display varcon name name1 Display options display nonZeros Display option display solutionPool Display option optionName optionValue All CMPL command line arguments excluding a new defini tion of the input file Please see subchapter 332 solverName In this version are only solver options for cbc glpk and gurobi supported solverOption solverOptionValue Please see to the solver specific parameters subchapter 6 Appendix varcon name name1 Sets variable names or constraint names that are to be CMPL v112 Manual 16 displayed in one of the solution reports Different names are to be separated by spaces If name is combined with the asterix then all variables or constraints with names that start with name are selec ted nonZeros Only variables and constraints with nonzero activities are shown in the solution report solutionPool Gurobi and Cplex are able to generate and store multiple solutions to a mixed integer programming MIP problem With the display option solutionPool feasible integer solutions found during a MIP optimisation can be shown in the solution report It is recommended to control the be haviour of the solution pool by setting the particular Gur obi or Cplex solver options Examples arg solver glpk GLPK is used as the solver arg solutionAscii CMPL writes the optimisation results in an ASCII file arg solver cbc arg cmplUrl http19495441878008 CBC is to be executed on a CMPLServer located at 1949544187 opt glpk nopresol If GLPK is used then the presolver is switched off display var x Only the variable x is to be displayed in the solution re port display con x y All constraints with names that start with x or y are shown in the solution report If an external cmplData file is to be read into the CMPL model then a user can specify the file name and the needed parameters and sets within the CMPL header All definitions of the parameters and sets can be mixed with another The syntax of a cmplData is described in subchapter 232 cmplData files Usage CMPL header for defining external data data filename set1 setrank set2 setrank data filename param1 param2 data filename paramarray1set paramarray2set filename file name of the cmplData file If the file name contains white spaces the name can be enclosed in double quotes If filename is not specified a generic name CMPL v112 Manual 17 modelnamecdat will be used set1 setrankset2 setrank specifies a set with the name set1 and the rank rank The rank defines the number n of the entries in the ntuples that are contained in the set For 1tuple sets is the definition of the rank optional For more than one set the sets are to be separated by commas param1 param2 specifies a scalar parameter If more than one parameters are to be specified then the parameters are to be separated by commas paramarray1setparamarray2set specifies a parameter array and the set over which the array is defined For more than one parameter array the entries are to be separated by commas The easiest form to specify external data is data In this case a generic filename modelnamecdat will be used and all sets and parameters that are defined in modelnamecdat will be read Examples data myProblemcdat n set an reads the 1tuple set n and the vector a which is defined over the set n from the file myProblemcdat data myProblemcdat reads all parameters and sets that are defined in the file myProblemcdat data n set1 an reads assuming a CMPL model name myproblem2cmpl the 1tuple set n and the vector a which is defined over n from myProblem2cdat data Assuming a CMPL model name myproblem2cmpl all sets and parameters are to be read from myProb lem2cdat data routes set2 costsroutes Assuming a CMPL model name myproblemcmpl the 2 tuple set routes and the matrix costs defined over routes are to be read from myProblemcdat CMPL v112 Manual 18 22 Parameter Expressions 221 Overview Parameter expressions are rules for computing a value during the runtime of a CMPL programme Therefore a parameter expression generally cannot include a model variable Exceptions to this include spe cial functions whose value depends solely on the definition of a certain model variable Parameter expres sions are a part of an assignment to a parameter or are usable within the echo function Assignments to a parameter are only permitted within the parameters section or within a control structure An expression can be a single number or string a function a set or a tupel Therefore only real integer binary string set or tupel expressions are possible in CMPL A parameter expression can contain the normal arithmetic opera tions 222 Array functions With the following functions a user may identify specific characteristics of an array or a single parameter or model variable Usage maxexpressionsreturns the numerically largest of a list of values minexpressionsreturns the numerically smallest of a list of values countparametervariableparameterArrayvariableArray returns the count of elements or 0 if the parameter or the variable does not exist expressions can be a list of numerical expressions separated by commas or can be a multi dimensional array of parameters Examples a 125 echo max a returns user message 5 echo min a returns user message 1 echo count a returns user message 3 echo count a1 echo count a5 echo count a returns user message 1 returns user message 0 returns user message 3 b1234 2345 echo countb1 echo countb1 echo countb echo countb135 user messages 4 4 elements in the first row 2 2 elements in the first column 8 4 x 2 elements in the entire matrix 0 parameter does not exist CMPL v112 Manual 19 a set 11122232 ba 10 20 30 40 echo count countba echo min minba echo max maxba user messages count 4 min 10 max 40 223 Set operations and functions Set operations and functions can be used to manipulate sets to create sets or to analyse the characteristics of a set Usage set controlHeader bodyExpressions condition set only for 1tupel sets set1 set2 union set only for 1tupel sets set1 set2 intersection set lenset count of the elements of the set returns an integer defsetarray returns the set of the first free index of the array only useful for dense arrays index set returns 1 if the index is an element of the set returns 0 otherwise set tuppelPattern Set pattern matching Returns an ntuple set consisting of unique elements of the set set which match tuplePattern in the order of their first appearance setcontrolHeaderbodyExpressions Constructs a set consisting of the bodyexpressions that satisfy the conditions in the controlHeader set1 set2 union of set1 and set2 set1 set2 intersection of set1 and set2 array array of parameters or model variables with at least one free index set tuppelPattern Returns an ntuple set consisting of unique elements of the set set which match tuplePattern in order of their first appearance CMPL v112 Manual 20 A tuplePattern have to be formulated in the form of a tuple and has to have the same rank as the original set The following entries are allowed and to be separated by commas all elements at the position of the indexing entry ignore all elements at the position of the indexing entry string or integer A string or integer fixes the indexing entry at its specific position The fixed indexing entry will not be re turned by the set pattern matching expression It is also possible to use a parameter which is assigned a string or integer string or integer Fixes also the indexing entry at the specific position but returns the fixed indexing entry too Can also be understood as an intersection of two sets fol lowed by a rank reduction controlled by or Examples s1 set abcd s2 set aecf s3 s1 s2 s4 s1 s2 s3 is assigned abcdef s4 is assigned a c s5 seti in 110 i mod 2 0 i s5 is assigned 246810 s6 seti in s1 i s2 i s6 is assigned b d a set 11122232 b set 11442237 c a b c is assigned the set 1 1 2 2 a set 1 a 3 b 5 c echo length of the set lena returns the user message length of the set 6 A 12345 1234567 row defsetA col defsetA1 row is assigned the set 12 col is assigned the set 15 CMPL v112 Manual 21 a set 1 a 3 b 5 c echo a a echo 5 a echo bb a returns the user message 1 returns the user message 1 returns the user message 0 a set 11122232 echo lena echo 11 a echo 17 a returns the user message 4 returns the user message 1 returns the user message 0 a set 11122232 b 12 12 echo a b returns the user message set1 1 1 2 2 2 a set 11122232 b 2 echo a b returns the user message set1 2 2 2 3 2 bset1112142223 243133 echo b echo b echo b 1 echo b 1 displays the user messages 13 set 1 2 4 3 set1 1 1 2 1 4 set 1 2 4 cset111122225322 echo c 1 p2 echo c p echo c p echo c 1 displays the user messages set1 1 2 2 set1 2 2 5 3 2 set1 2 2 2 2 5 3 2 2 12 224 Mathematical functions In CMPL there are the following mathematical functions which can be used in expressions Excluding div and mod all these functions return a real value Usage p div q integer division p mod q remainder on division sqrt x sqrt function exp x exp function ln x natural logarithm lg x common logarithm ld x logarithm to the basis 2 CMPL v112 Manual 22 srand x Initialisation of a pseudorandom number generator using the argument x Returns the value of the argument x rand x returns an integer random number in the range 0 rand x sin x sine measured in radians cos x cosine measured in radians tan x tangent measured in radians acos x arc cosine measured in radians asin x arc sine measured in radians atan x arc tangent measured in radians sinh x hyperbolic sine cosh x hyperbolic cosine tanh x hyperbolic tangent abs x absolute value ceil x smallest integer value greater than or equal to a given value floor x largest integer value less than or equal to a given value round x simple round p q integer expression x real or integer expression Examples c1 sqrt 36 c2 exp10 c3 ln10 c4 lg10000 c5 ld8 c6 rand10 c7 sin25 c8 cos77 c9 tan101 c10 acos01 c11 asin04 c12 atan11 c13 sinh10 c14 cosh3 c15 tanh15 c16 abs1255 c17 ceil1255 c18 floor1255 c19 round124 c20 35 div 4 c21 35 mod 4 value is 6000000 22026465795 2302585 4000000 3000000 7000000 random number 0598472 0153374 0800789 1470629 0411517 0832981 11013232875 10067662 1000000 12550000 13000000 13000000 12000000 8 3 CMPL v112 Manual 23 225 Type casts It is useful in some situations to change the type of an expression into another type A set expression can only be converted to a string A string can only be converted to a numerical type if it contains a valid numer ical string Every expression can be converted to a string Usage typeexpression type cast type Possible types are real integer binary string expression expression Examples returns the user messages a 6666 echo integera echo binarya a0 echo binarya a 66666 echo stringa 7 1 0 6666600 b 100 echo realb echo binaryb b 0 echo binaryb b 100 echo stringb 100000000 1 0 100 c 1 echo realc echo integerc echo stringc 1000000 1 1 e 1888 echo reale echo integere echo binarye e echo binarye 1888000 1 1 0 226 String operations Especially for displaying strings or numbers with the echo function there are string operations to concatenate and format strings CMPL v112 Manual 24 Usage expression expression concat strings if one expression has the type string format formatString expression converts a number into a string using a format string len stringExpression length of a string type expression returns the type of the expression as a string expression expression which is converted to string Cannot be a set expression Such an expression must be converted to a string expression by a type cast formatString a string expression containing format parameters CMPL uses the format parameters of the programming language C For fur ther information please consult a C manual Usage format parameters flagswidthprecisionspecifier specifier d integer f real s string flags leftjustify Forces the result to be preceded by a plus or minus sign or even for positive numbers By default only negative numbers are preceded with a sign width number Minimum number of characters to be printed If the value to be printed is shorter than this number the result is padded with blank spaces The value is not truncated even if the result is larger The width is not specified in the format string but as an additional integer value argument preceding the argument that has to be formatted CMPL v112 Manual 25 precision number For integer specifiers d precision specifies the minimum number of digits to be written If the value to be written is shorter than this number the result is padded with leading zeros The value is not truncated even if the result is longer A precision of 0 means that no character is written for the value 0 For f this is the number of digits to be printed after the decimal point For s this is the maximum number of characters to be printed By default all characters are printed until the ending null character is encountered When no precision is specified the default is 1 If the period is specified without an explicit value for precision 0 is assumed The precision is not specified in the format string but as an additional integer value argument preceding the argument that has to be formatted Examples a6677777 echo typea a to string format102f a returns the user message real 66777770 to string 6678 If you would like to display an entire set concatenating with a string then you have to use a string cast of your set Example s set 7 qwe 6 fe 5 8 echo set is strings returns the user message set is set 7 qwe 6 fe 5 8 23 Input and output operations The CMPL input and output operations can be separated into message function a function that reads the ex ternal data and the include statement that reads external CMPL code 231 Error and user messages Both kinds of message functions display a string as a message In contrast to the echo function an error message terminates the CMPL programme after displaying the message Usage error expression error message terminates the CMPL programme echo expression user message expression A message that is to be displayed If the expression is not a string it will be auto matically converted to string CMPL v112 Manual 26 Examples a0 error negative value If a is negative an error message is displayed and the CMPL programme will be terminated echo constant definitions finished A user message is displayed i113 echo value i The following user messages are displayed value 1 value 2 value 3 232 cmplData files A cmplData file is a plain text file that contains the definition of parameters and sets with their values in a specific syntax The parameters and sets can be read into a CMPL model by using the CMPL header argu ment data Usage name numberOrString scalar parameter name setrank setExpression set definition name set default indices listOfNumbersOrStrings parameter array text comments Excluding comments each cmplData definition starts with name numberOrString a scalar parameter name is assigned a single string or num ber name setrank setExpression definition of an ntuple set A set definition starts with the name followed by the keyword set For ntuple sets with n1 the rank of the set is to be specified enclosed by square brackets For enumeration sets the entries of the sets are separated by white spaces and imbedded in angle brackets It is also possible to define algorithmic sets in normal CMPL syntax name set default indices listOfNumbersOrStrings definition of a parameter array The specification of a parameter array starts with the name followed by one or more sets over which the array is defined If more than one set is used then the sets have to be separated by commas CMPL v112 Manual 27 The set or sets have to be defined before the parameter definition If the data entries are specified by their indices keyword indices then a default value can be defined The data entries can be strings or numbers and have to be separated by white spaces and imbedded in angle brackets If the data entries are specified by their indices then each data entry has to start with the indices followed by the value and separated by white spaces If not so then the order of the elements are given by the natural order of the set or sets Examples a 10 Defines a scalar parameter a and assigns the number 10 s set 06 s set 06 s is assigned s01 6 s set 1024 s is assigned s10864 prod set bike1 bike2 prod set bike 1 bike 2 1tuple enumeration set of strings a set 1 a 3 b 5 c xa 10 20 30 40 50 60 1tuple enumeration set of strings and integers vector x identified by the set a is assigned an in teger vector data a set xa parameters echo x1 echo xa i in a echo xi reads the set a and the vector x into a CMPL model The following user messages are displayed 10 20 10 20 30 40 50 60 n set 13 m set 13 anm 0 indices 1 1 1 2 2 1 3 3 1 defines a 3x3 identity matrix x set 12 y set 12 z set 12 definition of a data cube with the dimension xyz CMPL v112 Manual 28 cubexyz 1 2 3 4 5 6 7 8 x y z value 1 1 1 1 1 1 2 2 1 2 1 3 1 2 2 4 2 1 1 5 2 1 2 6 2 2 1 7 2 2 2 8 data x set y set z set cubexyz parameters i in x j in y k in z echo ijkcubeijk reads the sets xyz and the cube into a CMPL model The following user messages are displayed 1111 1122 1213 1224 2115 2126 2217 2228 cubexyz 0 indices 1 1 1 1 2 2 2 1 defines the following data cube x y z value 1 1 1 1 1 1 2 0 1 2 1 0 1 2 2 0 2 1 1 0 2 1 2 0 2 2 1 0 2 2 2 1 x set3 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 cubex 1 2 3 4 5 6 7 8 cube defined over a 3tuple set x y z value 1 1 1 1 1 1 2 2 1 2 1 3 1 2 2 4 2 1 1 5 2 1 2 6 2 2 1 7 2 2 2 8 CMPL v112 Manual 29 data x set3 cubex parameters i in x echo i cubei reads the 3tuple set x and cube The following user messages are displayed 1 1 11 1 1 22 1 2 13 1 2 24 2 1 15 2 1 26 2 2 17 2 2 28 x set3 1 1 1 1 1 2 1 2 1 1 2 2 2 1 1 2 1 2 2 2 1 2 2 2 cubex 0 indices 1 1 1 1 2 2 2 1 data cube defined over x routes set2 p1 c1 p1 c2 p1 c4 p2 c2 p2 c3 p2 c4 p3 c1 p3 c3 croutes 3 2 6 5 2 3 2 4 defines a 2tuple set routes and a matrix c that is defined over routes data routes set2 croutes parameters i in routes echo i ci reads the 2tuple set routes and the matrix c into a CMPL model The following user messages are displayed p1 c1 3 p1 c2 2 p1 c4 6 p2 c2 5 p2 c3 2 p2 c4 3 p3 c1 2 p3 c3 4 CMPL v112 Manual 30 x y z value 1 1 1 1 1 1 2 0 1 2 1 0 1 2 2 0 2 1 1 0 2 1 2 0 2 2 1 0 2 2 2 1 233 Readcsv and readstdin CMPL has two additional functions that enable a user to read external data The function readstdin is de signed to read a users numerical input and assign it to a parameter The function readcsv reads numerical data from a CSV file and assigns it to a vector or matrix of parameters For a vector with a length n to be read into a CMPL model the data in the CSV file can be organized as one row with n elements or n rows with one element But in CMPL this vector is always a column vector Usage readstdinmessage returns a user numerical input readcsvfileName reads numerical data from a csv file for assigning these data to an array message string expression for the message that is to be displayed fileName string expression for the file name of the CSV file relative to the directory in which the current CMPL file resides In CMPL CSV files that use a comma or semicolon to separate values are permit ted Example a readstdingive me a number reads a value from stdin to be used as value for a Only recommended when using CMPL as a command line interpreter The following example uses three CSV files 1 2 3 ccsv 5677105 9842111 acsv 1520 bcsv parameters c readcsvccsv b readcsvbcsv A readcsvacsv variables xdefsetc real0 objectives cT xmax constraints A x b Using readcsv CMPL generates the following model 1x 12x23x 3max st 56x177x2105x 315 98x142x2111x320 x j0 j113 CMPL v112 Manual 31 234 Include Using the include directive it is possible to read external CMPL code in a CMPL programme The CMPL code in the external CMPL file can be used by several CMPL programmes This makes sense for sharing basic data in a couple of CMPL programmes or for the multiple use of specific CMPL statements in several CMPL programmes The include directive can stand in any position in a CMPL file The content of the included file is inserted at this position before parsing the CMPL code Because include is not a statement it is not closed with a semicolon Usage include fileName include external CMPL code fileName file name of the CMPL file relative to the directory in which the current CMPL file resides Note that fileName can only be a literal string value It cannot be a string ex pression or a string parameter The following CMPL file constdefgen is used for the definition of a couple of parameters c 1 2 3 b 15 20 A 56 77 105 9842111 constdefgen parameters include constdefcmpl variables xdefsetc real0 objectives cT x max constraints A x b Using the include statement CMPL generates the following model 1x1 2x2 3x3 max st 56x1 77x2 105x 315 98x1 42x 2 111x320 x j0 j113 24 Statements As mentioned earlier every CMPL programme consists of at least one of the following sections paramet ers variables objectives and constraints Each section can be inserted several times and mixed in a different order Every section can contain special statements Every statement finishes with a semicolon CMPL v112 Manual 32 241 parameters and variables section Statements in the parameters section are assignments to parameters These assignments define paramet ers or reassign a new value to already defined parameters Statements in the variables sections are definitions of model variables All the syntactic and semantic requirements are described in the chapters above 242 objectives and constraints section In the objectives and constraints sections a user has to define the content of the decision model in linear terms In general an objective function of a linear optimisation model has the form c1x1c2x 2cnxn max or min with the objective function coefficient c j and model variables x j Constraints in general have the form k11x1k 12x 2k 1nx n b1 k 21x1k 22x 2k2nxn b2 k m1x1km2x2k mnxn bm with constraint coefficients k ij and model variables x j An objective or constraint definition in CMPL must use exactly this form or a sum loop that expresses this form A coefficient can be an arbitrary numerical expression but the model variables cannot stand in expres sions that are different from the general form formulated The rule that model variables cannot stand in bracketed expressions serves to enforce this Please note it is not permissible to put model variables in brackets The example a and b are parameters x and y model variables ax ay bx by can be written alternatively with parameters in brackets as a bx a by but not with model variables in brackets as ax y bx y For the definition of the objective sense in the objectives section the syntactic elements max or min are used A line name is permitted and the definition of the objective function has to have a linear form CMPL v112 Manual 33 Usage of an objective function objectives lineName linearTerm maxmin lineName optional element description of objective linearTerm definition of linear objective function The definition of a constraint has to consist of a linear definition of the use of the constraint and one or two relative comparisons Line names are permitted Usage of a constraint constraints lineName linearTerm linearTerm linearTerm lineName optional element description of objective linearTerm linear definition of the lefthand side or the righthand side of a constraint 25 Control structure 251 Overview A control structure is imbedded in and defined by a header followed by a body separated off by General usage of a control structure controlNamesumset controlHeader controlBody A control structure can be started with an optional name for the control structure In the objectives and in the constraints section this name is also used as the line name It is possible to define different kinds of control structures based on different headers control statements and special syntactical elements Thus the control structure can used for for loops while loops ifthenelse clauses and switch clauses Control structures can be used in all sections A control structure can be used for the definition of statements In this case the control body contains one or more statements which are permissible in this section CMPL v112 Manual 34 It is also possible to use control structures for sum and set as expressions Then the body contains a single expression A control structure as an expression cannot have a name because this place is taken by the keyword sum or set Moreover a control structure as an expression cannot use control statements because the body is an expression and not a statement 252 Control header A control header consists of one or more control headers Where there is more than one header the head ers must be separated by commas Control headers can be divided into iteration headers condition head ers local assignments and empty headers 2521 Iteration headers Iteration headers define how many repeats are to be executed in the control body Iteration headers are based on sets Usage localParam in set iteration over a set localParam name of the local parameter set The defined local parameter iterates over the elements of the set and the body is executed for every element in the set Examples s1 set abcd k in s1 k is iterated over all elements of the set s1 s2 1110 k in s2 k is iterated over the set k 1210 s3 26 k s3 k is iterated over the set k 236 a set 11122232 k in a k is iterated over the 2tuple set a a set 11122232 ij in a 2tuple index ij is iterated over the 2tuple set a 2522 Condition headers A condition returns 1True or 0False subject to the result of a comparison or the properties of a para meter or a set If the condition returns 1True the body is executed once or else the body is skipped CMPL v112 Manual 35 Comparison operators for parameters equality inequality less than greater than equal to or less than equal to or greater than Comparison operators for sets equality tests whether the iteration order of two sets is equal inequality tests whether the iteration order of two sets is not equal subset or not equal only for 1tuple sets greater than only for 1tuple sets subset or equal only for 1tuple sets equal to or greater than only for 1tuple sets Logical operators AND OR NOT If a real or integer parameter is assigned 0 the condition returns 0 false Alternatively if the parameter is assigned 1 the condition returns 1 true Examples i1 j2 ij ij i j2 i j2 condition is false condition is true condition is true condition is false i is false because i is not 0 2523 Local assignments A local assignment as control header is useful if a user wishes to make several calculations in a local envir onment Assigning expression to a parameter within the constraints section is generally not allowed with the exception of a local assignment within a control structure The body will be executed once CMPL v112 Manual 36 Usage localParam expression assignment to a local parameter localParam Defines a local parameter with this name expression Expression which is assigned to the local parameter Examples constraints k1 k is assigned 1 and used as local parameter within the control structure 253 Alternative bodies If a control header consists of at least one condition it is possible to define alternative bodies Structures like that make sense eg if a user wishes to combine a for loop with an ifthen clause The first defined body after the headers is the main body of the control structure Subsequent bodies must be separated by the syntactic element Alternative bodies are only executed if the main body is skipped Usage controlHeader mainBody condition1 alternativeBody1 default alternativeDefaultBody controlHeader header of the control structure including at least one condition The alternative bodies belong to last header of control header This header cannot be an assignment of a local parameter because in this case the main body is never skipped mainBody main body of control structure condition1 Will be evaluated if alternative body is executed alternativeBody1 The first alternative body with a condition that evaluates to true is ex ecuted The remaining alternative bodies are skipped without checking the conditions alternativeDefaultBody If no condition evaluates to true then the alternative default body is ex ecuted If the control structure has no alternative default body then no body is executed CMPL v112 Manual 37 254 Control statements It is possible to change or interrupt the execution of a control structure using the keywords continue break and repeat A continue stops the execution of the specified loop jumps to the loop header and executes the next iteration A break only interrupts the execution of the specified loop The keyword re peat starts the execution again with the referenced header Every control statement references one control header If no reference is given it references the innermost header Possible references are the name of the local parameter which is defined in this head or the name of the control structure The name of the control structure belongs to the first head in this control structure Usage continue reference break reference repeat reference reference a reference to a control header specified by a name or a local parameter break reference The execution of the body of the referenced head is cancelled Remaining statements are skipped If the referenced header contains iteration over a set the execution for the remaining elements of the set is skipped continue reference The execution of the body of the referenced head is cancelled Remaining statements are skipped If the referenced header contains iteration over a set the execution is contin ued with the next element of the set For other kinds of headers continue is equivalent to break repeat reference The execution of the body of the referenced header is cancelled Remaining statements are skipped The execution starts again with the referenced header The expression in this header is to be evaluated again If the header contains iteration over a set the execution starts with the first element If this header is an assignment to a local parameter the assignment is executed again If the header is a condi tion the expression is to be checked prior to execution or skipping the body CMPL v112 Manual 38 255 Specific control structures 2551 For loop A for loop is imbedded in and defined by at least one iteration header followed by a loop body separ ated off by The loop body contains userdefined instructions which are repeatedly carried out The num ber of repeats is based on the iteration header definition Usage iterationHeader iterationHeader1 controlBody iterationHeader iterationHeader1 defined iteration headers controlBody CMPL statements that are executed in every iteration Examples i in 113 loop counter i with a start value of 1 an increment of 1 and an end condition of 3 i in 13 alternative definition of a loop counter loop counter i with a start value of 1 and an end condition of 3 The in crement is automatically defined as 1 products set p1 p2 p3 hoursproducts205510 i in products echo hours of product i hoursi for loop using the set products returns user messages hours of product p1 20 hours of product p2 55 hours of product p3 10 i in 112 j in 224 Aij i j defines A12 3 A14 5 A22 4 and A24 6 a set11122232 ba 10 20 30 40 k in a echo k bk k is iterated over the 2tuple set a The following user messages are displayed 1 110 1 220 2 230 3 240 Several loop heads can be combined The above example can thus be abbreviated to i in 112 j in 224 Aij i j defines A12 3 A14 5 A22 4 and A24 6 CMPL v112 Manual 39 i in 115 j in 11i Aij i j definition of a triangular matrix 2552 Ifthen clause An ifthen consists of one condition as control header and userdefined expressions which are executed if the if condition or conditions are fulfilled Using an alternative default body the ifthen clause can be exten ded to an ifthenelse clause Usage condition thenBody default elseBody condition If the evaluated condition is true the code within the body is executed thenBody This body is executed if the condition is true elseBody This body is executed if the condition is false Examples i 115 j 115 i j Aij 1 i j Aij 0 definition of the identity matrix with combined loops and two ifthen clauses i 115 j 115 i j Aij 1 default Aij 0 same example but with one ifthenelse clause i10 i10 echo i less than 10 default echo i greater than 9 example of an ifthenelse clause returns user message i greater than 9 sum i j 1 default 2 conditional expression evaluates to 1 if i j oth erwise to 2 2553 Switch clause Using more than one alternative body the ifthen clause can be extended to a switch clause Usage condition1 body1 condition2 body2 default defaultBody CMPL v112 Manual 40 If the first condition returns TRUE only body1 will be executed Otherwise the next condition condi tion1 will be verified body2 is executed if all of the previous conditions are not fulfilled If no condition returns true then the defaultBody is executed Example i2 i1 echo i equals 1 i2 echo i equals 2 i3 echo i equals 3 default echo any other value example of a switch clause returns user message i equals 2 2554 While loop A while loop is imbedded in and defined by a condition header followed by a loop body separated off by and finished by the keyword repeat The loop body contains userdefined instructions which are re peatedly carried out until the condition in the loop header is false Usage condition statements repeat condition If the evaluated condition is true the code within the body is executed This re peats until the condition becomes false statements one or more userdefined CMPL instructions To prevent an infinite loop the statements in the control body must have an im pact on the condition Examples i2 i4 Ai i i i1 repeat while loop with a global parameter Can only be used in the parameters section because the assignment to a global parameter is not permitted in other sections defines A2 2 A3 3 and A4 4 a 1 a 5 echo a a a 1 repeat while loop using a local parameter returns user messages 1 2 3 4 a1 xx echo a a a 1 Alternative formulation The outer control structure defines the local parameter a This control structure is used as a loop with a defined name and an empty header The name is necessary be CMPL v112 Manual 41 a4 break xx repeat cause it is needed as reference for the break statement in the inner control structure Without this reference the break statement would refer to the condition a4 256 Set and sum control structure as expression Starting with the keyword sum or the keyword set a control structure returns an expression Only expres sions are permitted in the body of the control structure Control statements are not allowed because the body cannot contain a statement It is possible to define alternative bodies Usage sum controlHeader bodyExpressions set controlHeader bodyExpressions controlHeader header of the control structure The header of a sum or a set control structure is usually an iteration header but all kinds of control header can be used bodyExpressions userdefined expressions A sum expression repeatedly summarises the userdefined expressions in the bodyExpressions If the body is never executed it evaluates to 0 A set expression returns a set subject to the controlHeader and the bodyExpressions The element type included in bodyExpressions must be integer or string Please note that the set expression only works for 1tuple sets Examples x13 2 4 6 a sumi 113 xi a is assigned 12 products set p1 p2 p3 hoursproducts205510 totalHours sumi in products hoursi totalHours is assigned 85 x1312123456 b sumi 113 j 112 xij sum with more than one control header b is assigned 21 sset d sumi in s i default 1 sums up all elements in the set s Since s is an empty set d is assigned to the alternative default value 1 a set 11122232 ba 10 20 30 40 c sum k in a bk calculates a sum over all elements in b which is defined over the 2tuple set a c is assigned 100 CMPL v112 Manual 42 e seti 110 i2 e is assigned the set 1 4 9 16 25 36 49 64 81 100 f seti 1100 roundsqrti2 i i f is assigned the set 1 4 9 16 25 36 49 64 81 100 The sum expression can also be used in linear terms for the definition of objectives and constraints In this case the body of the control structure can contain model variables Examples parameters a1213 123456 b12 100100 c13 201010 variables x13 real0 objectives sumj13 cj xjmax objective definition using a sum 20x1 10x2 10x3 max constraints i12 sumj13 aij xj bi constraints definition using a sum 1x1 2x 2 3x3100 4x1 5x2 6x3100 26 MatrixVector notations CMPL allows users to define objectives and constraints in a matrixvector notation eg matrix vector multi plication CMPL generates all required rows and columns automatically by implicit loops Implicit loops are formed by matrices and vectors which are defined by the use of free indices A free index is an index which is not specified by a position in an array It can be specified by an entire set or without any specification But the separating commas between indices must in any case be specified A multidimensional array with one free index is always treated as a column vector regardless of where the free index stands A column vector can be transposed to a row vector with T A multidimensional array with two free indices is al ways treated as a matrix The first free index is the row the second the column Implicit loops are only pos sible in the objectives section and the constraints section Please note that matrixvector notations only works for arrays which are defined over 1tuple sets Usage vectorset column vector CMPL v112 Manual 43 vectorsetT transpose of column vector row vector matrixindex set column vector matrixset index also column vector matrixindex setT transpose of column vector row vector matrixset indexT transpose of column vector row vector matrixset1 set2 matrix vector matrix name of a vector or matrix index a certain index value set optional specification of a set for the free index Examples x vector with free index across the entire defined area x25 vector with free index in the range 2 5 A matrix with two free indices A1 matrix with one fixed and one free index this is a column vector A1 matrix with one fixed and one free index this is also a column vector The most important ways to define objectives and constraints with implicit loops are vectorvector multiplica tion and matrixvector multiplication A vectorvector multiplication defines a row of the model eg an ob jective or one constraint A matrixvector multiplication can be used for the formulation of more than one row of the model Usage of multiplication using implicit loops paramVectorsetT varVectorset vectorvector multiplication varVectorsetT paramVectorset vectorvector multiplication paramMatrixset1set2 varVectorset2 matrixvector multiplication varVectorset1T paramMatrixset1set2 matrixvector multiplication paramVector name of a vector of parameters varVector name of a vector of model variables paramMatrix name of a matrix of parameters T syntactic element for transposing a vector Examples CMPL v112 Manual 44 parameters a1213 123 456 b12 100100 c13 201010 variables x13 real0 objectives cT x max objective definition using implicit loops 20x110x 210x 3max constraints a x b constraint definition using implicit loops 1x12x 23x3100 4x 15x26x 3100 Aside from vectorvector multiplication and matrixvector multiplication vector subtractions or additions are also useful for the definition of constraints The addition or subtraction of a variable vector adds new co lumns to the constraints The addition or subtraction of a constant vector changes the right side of the con straints Usage of additions or subtractions using implicit loops linearTerms varVectorset variable vector addition linearTerms varVectorset variable vector subtraction linearTerms paramVectorset parameter vector addition linearTerms paramVectorset parameter vector subtraction linearTerms other linear terms in an objective or constraint Examples parameters a1213 123 456 b12 100100 d12 1010 c13 201010 variables x13 real0 objectives cT x max constraints a x d b constraints definition using implicit loops 1x1 2x 2 3x390 4x 1 5x2 6x390 equivalent to a x b d CMPL v112 Manual 45 0 x13y13z2 b13 implicit loops for a column vector 0 x1 y1 z2 b1 0 x2 y2 z2 b2 0 x3 y3 z2 b3 equivalent formulation parameters a1213 123 456 b12 100100 d12 1010 c13 201010 variables x13 real0 z12 real0 objectives cT x max constraints a x z b constraints definition using implicit loops 1x1 2x 2 3x3 z1 90 4x 1 5x2 6x3 z2 90 27 Automatic model reformulations 271 Overview CMPL includes two types of automatic code generation which release the user from additional modelling work CMPL automatically optimizes the generated model by means of matrix reductions The second type of automatic code reformulations is the equivalent transformation of variable products 272 Matrix reductions Matrix reductions are subject to constraints of a specific form a If a constraint contains only one variable or only one of the variables with a coefficient not equal to 0 then the constraint is taken as a lower or upper bound For the following summation x is a variable vector sumi112 i1 xi 10 no matrix line is generated rather x2 has an upper bound of 10 b If there is a constraint in the coefficients of all variables proportional to another constraint only the more strongly limiting constraint is retained Only the second of the two constraints x is a variable vector CMPL v112 Manual 46 2x1 3x2 20 10x1 15x2 50 is used in generating a model line Matrix reductions are switched off by default but can be enabled by the command line argument gn 273 Equivalent transformations of Variable Products A product of variables cannot be a part of an LP or MIP model because such a variable product is a nonlin ear term But if one factor of the product is an integer variable then it is possible to formulate an equivalent transformation using a set of specific linear inequations cf RoggeSteglich 2007 The automatic genera tion of an equivalent transformation of a variable product is a unique characteristic of CMPL 2731 Variable Products with at least one binary variable A product of variables with at least one binary variable can be transformed equivalently in a system of linear inequations as follows Rogge and Steglich 2007 p 25ff wuv uuu u real or integer v01 is equivalent to u real or integer v01 and uvwuv u1vuwu1v CMPL is able to perform these transformations automatically For the following given variables variables x binary y realYUYO each occurrence of the term xy in the CMPL model description is replaced by an implicit newlydefined variable xy and the following additional statements are generated automatically constraints minYU 0 xy maxYO 0 YU 0 xy YUx 0 YO 0 xy YOx 0 y xy YUx YU y xy YOx YO 2732 Variable Product with at least one integer variable It is also possible to formulate an equivalent system of linear inequation for products of variables with at least one integer variable Rogge and Steglich 2007 p 28ff CMPL v112 Manual 47 wuv uuu u real or integer if u integer then vvuu vvv v integer is equivalent to u real or integer and vv j0 d 2 jy j vv with dld vv11 wuv j0 d 2 jw j uy jw juy j u1 y juw ju1y j y j01 j01d CMPL is able to perform these transformations automatically as described above For the following given variables variables x integerXUXO y realYUYO each occurrence of the term xy in the CMPL model description is replaced by an implicit newlydefined variable xy and the following additional statements are generated automatically here d stands for the number of binary positions needed for XOXU1 variables x1d binary xy1d real constraints minXUYUXUYOXOYUXOYO xy maxXUYUXUYOXOYUXOYO x XU sumi11d 2i1xi xy XUy sumi11d 2i1xyi i 11d minYU 0 xyi maxYO 0 YU 0 xyi YUxi 0 YO 0 xyi YOxi 0 y xyi YUxi YU y xyi YOxi YO CMPL v112 Manual 48 28 Examples 281 Selected decision problems 2811 The diet problem The goal of the diet problem is to find the cheapest combination of foods that will satisfy all the daily nutri tional requirements of a person for a week The following data is given example cf FourerGayKernigham 2003 p 27ff food cost per package provision of daily vitamin requirements in percentages A B1 B2 C BEEF 319 60 20 10 15 CHK 259 8 2 20 520 FISH 229 8 10 15 10 HAM 289 40 40 35 10 MCH 189 15 35 15 15 MTL 199 70 30 15 15 SPG 199 25 50 25 15 TUR 249 60 20 15 10 The decision is to be made for one week Therefore the combination of foods has to provide at least 700 of daily vitamin requirements To promote variety the weekly food plan must contain between 2 and 10 packages of each food The mathematical model can be formulated as follows 319xBEEF 259xCHK 229x FISH289xHAM189x MCH199x MTL199 xSPG249xTURmin st 60x BEEF8xCHK8xFISH40xHAM 15x MCH70x MTL25 xSPG60xTUR700 20x BEEF0xCHK 10xFISH 40xHAM35x MCH30x MTL50 xSPG20xTUR700 10x BEEF20xCHK15xFISH 35xHAM 15x MCH15xMTL25 xSPG15xTUR700 15x BEEF20xCHK 10xFISH 10x HAM15x MCH15x MTL15 x SPG10xTUR700 x j23 10 jBEEF CHK DISH HAM MCH MTL SPG TUR The CMPL model dietcmpl can be formulated as follows parameters NUTR setAB1 B2 C FOOD setBEEF CHK FISH HAM MCH MTL SPG TUR cost per package costsFOOD 319 259 229 289 189 199 199 249 CMPL v112 Manual 49 provision of the daily requirements for vitamins in percentages vitaminNUTR FOOD 60 8 8 40 15 70 25 60 20 0 10 40 35 30 50 20 10 20 15 35 15 15 25 15 15 20 10 10 15 15 15 10 weekly vitamin requirements vitMinNUTR 700700700700 variables xFOOD integer210 objectives cost costsT xmin constraints capacity restriction 2 vitamin x vitMin An alternative formulation is based on the cmplData file dietdatacdat that is formulated as follows NUTR set A B1 B2 C FOOD set BEEF CHK FISH HAM MCH MTL SPG TUR cost per package costsFOOD 319 259 229 289 189 199 199 249 provision of the daily requirements for vitamins in percentages vitaminNUTRFOOD 60 8 8 40 15 70 25 60 20 0 10 40 35 30 50 20 10 20 15 35 15 15 25 15 15 20 10 10 15 15 15 10 weekly vitamin requirements vitMinNUTR 700 700 700 700 Assuming that the corresponding CMPL file dietdatacmpl is in the same working directory the model can be formulated as follows data dietdatacdat FOOD set NUTR set costsFOOD vitaminNUTRFOOD vit MinNUTR variables xFOOD integer210 CMPL v112 Manual 50 objectives cost costsT xmin constraints capacity restriction 2 vitamin x vitMin Solving this CMPL model through using the command cmpl dietdatacmpl leads to the same solution as for the first formulation Problem dietcmpl Nr of variables 8 Nr of constraints 4 Objective name cost Solver name CBC Objective status optimal Objective value 10114 min Variables Name Type Activity Lower bound Upper bound Marginal xBEEF I 2 2 10 xCHK I 8 2 10 xFISH I 2 2 10 xHAM I 2 2 10 xMCH I 10 2 10 xMTL I 10 2 10 xSPG I 10 2 10 xTUR I 2 2 10 Constraints Name Type Activity Lower bound Upper bound Marginal A G 1500 700 Infinity B1 G 1330 700 Infinity B2 G 860 700 Infinity C G 700 700 Infinity 2812 Production mix This model calculates the production mix that maximizes profit subject to available resources It will identify the mix number of each product to produce and any remaining resource The example involves three products which are to be produced with two machines The following data is given CMPL v112 Manual 51 P1 P2 P3 upper bounds h upper bound of a product units 250 240 250 selling price per unit unit 500 600 450 direct costs per unit unit 425 520 400 profit contribution per unit unit 75 80 50 machine hours required per unit machine 1 hunit 8 15 12 1000 machine 2 hunit 15 10 8 1000 The mathematical model can be formulated as follows 75x 180x250x3max st 8x115x212x 31000 15x 110x28x 31000 x 101 250 x 201 240 x 301 250 The CMPL model productionmixcmpl is formulated as follows arg solver glpk parameters products 13 machines 12 priceproducts 500 600 450 costsproducts 425 520 400 machine hours required per unit amachinesproducts 8 15 12 15 10 8 upper bounds of the machines bmachines 1000 1000 profit contribution per unit j in products cj pricejcostsj upper bound of the products xMaxproducts 250 240 250 variables xproducts integer CMPL v112 Manual 52 objectives profit cT x max constraints res a x b 0xxMax The model can be formulated alternatively by using the cmplData prodmixdatacdat file products set 13 machines set 12 priceproducts 500 600 450 costsproducts 425 520 400 machine hours required per unit amachinesproducts 8 15 12 15 10 8 upper bounds of the machines bmachines 1000 1000 lower and upper bound of the products xMaxproducts 250 240 250 xMinproducts 45 45 45 fixed setup costs FCproducts 500 400 500 The parameter arrays xMin and FC are not necessary for the given problem and therefore not specified within the data options in the following CMPL file prodmixdatacdat arg solver glpk data products set machines set priceproducts costsproducts data amachinesproducts bmachines xMaxproducts parameters profit contribution per unit j in products cj pricejcostsj variables xproducts integer objectives profit cT x max constraints res a x b 0xxMax CMPL v112 Manual 53 The CMPL command cmpl productionmixdatacmpl leads to the following Solution Problem productionmixcmpl Nr of variables 3 Nr of constraints 2 Objective name profit Solver name GLPK Objective status optimal Objective value 6395 max Variables Name Type Activity Lower bound Upper bound Marginal x1 I 33 0 250 x2 I 49 0 240 x3 I 0 0 250 Constraints Name Type Activity Lower bound Upper bound Marginal res1 L 999 Infinity 1000 res2 L 985 Infinity 1000 2813 Production mix including thresholds and stepwise fixed costs This model calculates the production mix that maximizes profit subject to available resources When a product is produced there are fixed setup costs There is also a threshold for each product The quantity of a product is zero or greater than the threshold The example involves three products which are to be produced with two machines The following data is given P1 P2 P3 upper bounds h production minimum of a product units 45 45 45 upper bound of a product units 250 240 250 selling price per unit unit 500 600 450 direct costs per unit unit 425 520 400 profit contribution per unit unit 75 80 50 setup costs 500 400 500 machine hours required per unit machine 1 hunit 8 15 12 1000 machine 2 hunit 15 10 8 1000 The mathematical model can be formulated as follows CMPL v112 Manual 54 75x 180x250x3500y1400y2500y3 max st 8x115x212x 31000 15x 110x28x 31000 45y1x1250y1 45y2x2240y2 45y3x 3250y3 x 101 250 x 201 240 x 301 250 y j01 j113 The CMPL model productionmixfixedcostscmpl is formulated as follows data productionmixdatacdat parameters profit contribution per unit j in products cj pricejcostsj variables j in products xj integer0xMaxj yproducts binary objectives profit cT x FCT y max constraints res a x b bounds j in products xMinj yj xj xMaxj yj CMPL command cmpl productionmixfixedcostscmpl Solution Problem productionmixfixedcostscmpl Nr of variables 6 Nr of constraints 8 Objective name profit Solver name CBC Objective status optimal Objective value 4880 max CMPL v112 Manual 55 Variables Name Type Activity Lower bound Upper bound Marginal x1 I 0 0 250 x2 I 66 0 240 x3 I 0 0 250 y1 B 0 0 1 y2 B 1 0 1 y3 B 0 0 1 Constraints Name Type Activity Lower bound Upper bound Marginal res1 L 990 Infinity 1000 res2 L 660 Infinity 1000 bounds11 L 0 Infinity 0 bounds12 L 0 Infinity 0 bounds21 L 21 Infinity 0 bounds22 L 174 Infinity 0 bounds31 L 0 Infinity 0 bounds32 L 0 Infinity 0 2814 The knapsack problem Given a set of items with specified weights and values the problem is to find a combination of items that fills a knapsack container room to maximize the value of the knapsack subject to its restricted capacity or to minimize the weight of items in the knapsack subject to a predefined minimum value In this example there are 10 boxes which can be sold on the market at a defined price box number price box weight pounds 1 100 10 2 80 5 3 50 8 4 150 11 5 55 12 6 20 4 7 40 6 8 50 9 9 200 10 10 100 11 1 What is the optimal combination of boxes if you are seeking to maximize the total sales and are able to carry a maximum of 60 pounds 2 What is the optimal combination of boxes if you are seeking to minimize the weight of the transported boxes bearing in mind that the minimum total sales must be at least 600 CMPL v112 Manual 56 Model 1 maximize the total sales The mathematical model can be formulated as follows 100x180x 250x3150x 455x520x640x750x 8200x9100x10max st 10x15x28x311x 412x 54x66x 79x810x 911x1060 x j01 j1110 The basic data is saved in the CMPL file knapsackdatacdat boxes set 1110 weight of the boxes wboxes 10 5 8 11 12 4 6 9 10 11 price per box pboxes 100 80 50 150 55 20 40 50 200 100 max capacity maxWeight 60 min sales minSales 600 A simple CMPL model knapsackmaxbasiccmpl can be formulated as follows data knapsackdatacdat boxes set wboxes pboxes maxWeight minSales display nonZeros variables xboxes binary objectives sales pT x max constraints weight wT x maxWeight CMPL command cmpl knapsackmaxbasiccmpl Solution Problem knapsackmaxbasiccmpl Nr of variables 10 Nr of constraints 1 Objective name sales Solver name CBC Objective status optimal Objective value 700 max CMPL v112 Manual 57 Nonzero variables Name Type Activity Lower bound Upper bound Marginal x1 B 1 0 1 x2 B 1 0 1 x4 B 1 0 1 x6 B 1 0 1 x8 B 1 0 1 x9 B 1 0 1 x10 B 1 0 1 Nonzero constraints Name Type Activity Lower bound Upper bound Marginal weight L 60 Infinity 60 Model 2 minimize the weight The mathematical model can be formulated as follows 10x15x28x311x 412x 54x66x 79x810x 911x10 min st 100x180x 250x3150x 455x520x640x750x 8200x9100x10600 x j01 j1110 A simple CMPL model knapsackminbasiccmpl can be formulated as follows data knapsackdatacdat display nonZeros variables xboxes binary objectives weight wT x min constraints sales pT x minSales CMPL command cmpl knapsackminbasiccmpl Solution Problem knapsackminbasiccmpl Nr of variables 10 Nr of constraints 1 Objective name weight Solver name CBC Objective status optimal Objective value 47 min Nonzero variables Name Type Activity Lower bound Upper bound Marginal CMPL v112 Manual 58 x1 B 1 0 1 x2 B 1 0 1 x4 B 1 0 1 x9 B 1 0 1 x10 B 1 0 1 Nonzero constraints Name Type Activity Lower bound Upper bound Marginal sales G 630 600 Infinity 2815 Transportation problem using 1tuple sets A transportation problem is a special kind of linear programming problem which seeks to minimize the total shipping costs of transporting goods from several supply locations origins or sources to several demand locations destinations The following example is taken from Anderson etal 2011 p 261ff This problem involves the transporta tion of a product from three plants to four distribution centres Foster Generators operates plants in Cleve land Ohio Bedford Indiana and York Pennsylvania The supplies are defined by the production capacities over the next threemonth planning period for one particular type of generator The company distributes its generators through four regional distribution centres located in Boston Chicago St Louis and Lexington It is to decide how much of its products should be shipped from each plant to each distribution centre The objective is to minimize the transportation costs The problem can be formulated in the form of the general linear programme below CMPL v112 Manual 59 Plants Centers 3 York 2 Bedford 1 Cleveland 1 Boston 3 St Louis 2 Chicago 4 Lexington 5000 6000 2500 6000 4000 2000 1500 3 2 5 2 3 2 4 6 7 7 5 5 i 1 m j1 n cijxij min st j 1 n x ijsi i11m i 1 m x ijd j j11n xij0 i11m j11n xij number of units shipped from plant i to center j cij cost per unit of shipping from plant i to center j si supply in units at plant i d j demand in units at desitination j The CMPL model transportationcmpl can be formulated as follows display nonZeros parameters plants 113 centres 114 splants 500060002500 dcentres 6000400020001500 cplantscentres 3276 75232545 variables xplantscentres real0 objectives costs sumi in plants j in centres cij xij min constraints supplies i in plants sumj in centres xij si demands j in centres sumi in plants xij dj or by using an additional cmplData file transportationdatacdat plants set 13 centres set 14 splants 5000 6000 2500 dcentres 6000 4000 2000 1500 cplants centres 3 2 7 6 7 5 2 3 2 5 4 5 and the corresponding CMPL model CMPL v112 Manual 60 data transportationdatacdat display nonZeros variables xplantscentres real0 objectives costs sumi in plants j in centres cij xij min constraints supplies i in plants sumj in centres xij si demands j in centres sumi in plants xij dj CMPL command cmpl transportationcmpl Solution Problem transportationcmpl Nr of variables 12 Nr of constraints 7 Objective name costs Solver name CBC Objective status optimal Objective value 39500 min Nonzero variables Name Type Activity Lower bound Upper bound Marginal x11 C 3500 0 Infinity 0 x12 C 1500 0 Infinity 0 x22 C 2500 0 Infinity 0 x23 C 2000 0 Infinity 0 x24 C 1500 0 Infinity 0 x31 C 2500 0 Infinity 0 Nonzero constraints Name Type Activity Lower bound Upper bound Marginal supplies1 E 5000 5000 5000 1 supplies2 E 6000 6000 6000 4 supplies3 E 2500 2500 2500 demands1 E 6000 6000 6000 2 demands2 E 4000 4000 4000 1 demands3 E 2000 2000 2000 2 demands4 E 1500 1500 1500 1 CMPL v112 Manual 61 2816 Transportation problem using multidimensional sets 2tuple sets In the case that not all of the connections are possible for technological or commercial reasons eg as in the picture below then an alternative model to the model above has to be formulated Additionally is as sumed that the total demand is greater than the supplies The mathematical model is based on the 2tuple set routes that contains only the valid connections between the plants and the centres i jroutes cijx ij min st k jroutes ki x kjsi i11m i lroutes l j xild j j11n xij0 i jroutes Die sets and parameters are specified in transportationtupledatacdat routes set2 1 1 1 2 1 4 CMPL v112 Manual 62 Plants Centers 3 York 2 Bedford 1 Cleveland 1 Boston 3 St Louis 2 Chicago 4 Lexington 5000 6000 2500 6000 4000 2000 2500 3 2 5 2 3 2 4 6 2 2 2 3 2 4 3 1 3 3 plants set 113 centres set 14 splants 5000 6000 2500 dcentres 6000 4000 2000 2500 croutes 3 2 6 5 2 3 2 4 that is connected to the CMPL model transportationtupledatacmpl data plants set centres set1 routes set2 data croutes splants dcentres display nonZeros variables xroutes real0 objectives costs sum ij in routes cijxij min constraints supplies i in plants sumj in routes i xij si demands j in centres sumi in routes j xij dj Solution Problem transportationtupledatacmpl Nr of variables 8 Nr of constraints 7 Objective name costs Solver name CBC Objective status optimal Objective value 36500 min Nonzero variables Name Type Activity Lower bound Upper bound Marginal x11 C 2500 0 Infinity 0 x12 C 2500 0 Infinity 0 x22 C 1500 0 Infinity 0 x23 C 2000 0 Infinity 0 x24 C 2500 0 Infinity 0 x31 C 2500 0 Infinity 0 Nonzero constraints Name Type Activity Lower bound Upper bound Marginal supplies1 E 5000 5000 5000 3 supplies2 E 6000 6000 6000 6 supplies3 E 2500 2500 2500 2 demands1 L 5000 Infinity 6000 demands2 L 4000 Infinity 4000 1 demands3 L 2000 Infinity 2000 4 demands4 L 2500 Infinity 2500 3 CMPL v112 Manual 63 2817 Quadratic assignment problem Assignment problems are special types of linear programming problems which assign assignees to tasks or locations The goal of this quadratic assignment problem is to find the cheapest assignments of n machines to n locations The transport costs are influenced by the distance d jk between location j and location k and the quantity t hi between machine h and machine i which is to be transported The assignment of a machine h to a location j can be formulated with the Boolean variables x hj 1 if machine h is assigned to location j 0 if not The general model can be formulated as follows h1 n i1 ih n j1 n k1 k j n thid jkxhjxik min st j1 n x hj1 h11n h1 n x hj1 j11n xhj01 h11n j11n Because of the product x hjx ik in the objective function the model is not a linear model But it is possible to use a set of inequations to make an equivalent transformation of such multiplications of variables This transformation is implemented in CMPL and the set of inequations will be generated automatically Consider the following case There are 5 machines and 5 locations in the given factory The quantities of goods which are to be transported between the machines are indicated in the figure below As shown in the picture below the machines are not fully connected Therefor it makes sense to formulate the objective function with a sum over a 2tuple set with the name routes for the valid combinations between the machines h iroutes n j1 n k1 k j n thid jkxhjxik min The distances between the locations are given in the following table CMPL v112 Manual 64 fromto 1 2 3 4 5 1 M 1 2 3 4 2 2 M 1 2 3 3 3 1 M 1 2 4 2 3 1 M 1 5 5 3 2 1 M The CMPL model quadraticassignmentcmpl can be formulated as follows display nonZeros display var x display ignoreCons parameters n5 d 0 1 2 3 4 2 0 1 2 3 3 1 0 1 2 2 3 1 0 1 5 3 1 1 0 routes set 12 13 15 23 34 35 45 troutes 103201552035 variables x1n1n binary dummy variables to store the products xhj xik hi in routes j11n k11n kj whjik real01 objectives costs sum hi in routes j11n k11n kj thidjkwhjik min constraints hi in routes j11n k11n kj whjikxhjxik sos1 h11n sum j11n xhj 1 sos2 j11n sum h11n xhj 1 CMPL command cmpl quadraticassignmentcmpl Solution Problem quadraticassignmentcmpl Nr of variables 305 Nr of constraints 570 Objective name costs Solver name CBC Display variables nonzero variables x Display constraints ignore all constraints CMPL v112 Manual 65 Objective status optimal Objective value 134 min Variables Name Type Activity Lower bound Upper bound Marginal x14 B 1 0 1 x21 B 1 0 1 x32 B 1 0 1 x45 B 1 0 1 x53 B 1 0 1 The optimal assignments of machines to locations are given in the the table below locations 1 2 3 4 5 machines 1 x 2 x 3 x 4 x 5 x 2818 Quadratic assignment problem using the solutionPool option It is for several reasons interesting to catch the feasible integer solutions found during a MIP optimisation Gurobi and Cplex are able to generate and store multiple solutions to a mixed integer programming MIP problem With the display option solutionPool these feasible integer solutions can be shown in the solu tion report It is recommended to control the behaviour of the solution pool by setting the particular Gurobi or Cplex solver options If the CMPL model for quadratic assignment problem above is extended by the following CMPL header entries then all feasible integer solutions found by Cplex arg solver cplex display solutionPool Solution Problem quadraticassignmentcmpl Nr of variables 305 Nr of constraints 570 Objective name costs Nr of solutions 5 Solver name CPLEX Display variables nonzero variables x Display constraints ignore all constraints Solution nr 1 Objective status integer optimal solution Objective value 134 min CMPL v112 Manual 66 Variables Name Type Activity Lower bound Upper bound Marginal x14 B 1 0 1 x21 B 1 0 1 x32 B 1 0 1 x45 B 1 0 1 x53 B 1 0 1 Solution nr 2 Objective status integer feasible solution Objective value 134 min Variables Name Type Activity Lower bound Upper bound Marginal x14 B 1 0 1 x21 B 1 0 1 x32 B 1 0 1 x45 B 1 0 1 x53 B 1 0 1 Solution nr 3 Objective status integer feasible solution Objective value 188 min Variables Name Type Activity Lower bound Upper bound Marginal x11 B 1 0 1 x23 B 1 0 1 x32 B 1 0 1 x45 B 1 0 1 x54 B 1 0 1 Solution nr 4 Objective status integer feasible solution Objective value 177 min Variables Name Type Activity Lower bound Upper bound Marginal x11 B 1 0 1 x24 B 1 0 1 x35 B 1 0 1 x43 B 1 0 1 x52 B 1 0 1 Solution nr 5 Objective status integer feasible solution Objective value 191 min Variables Name Type Activity Lower bound Upper bound Marginal x11 B 1 0 1 x22 B 1 0 1 x33 B 1 0 1 x44 B 1 0 1 x55 B 1 0 1 CMPL v112 Manual 67 2819 Generic travelling salesman problem The travelling salesman problem is well known and often described In the following CMPL model the xy coordinates of the cities are defined by random numbers and the distances are calculated by the euclidian distance of the xy coordinates The CMPL model tspcmpl can be formulated as follows arg solver cbc arg ignoreZeros display var x parameters seedsrand100 M10000 nrOfCities10 cities1nrOfCities i in cities xpirand100 ypirand100 i in cities j in cities ij distijM default distij sqrt xpixpj2 ypiypj2 distji distijrand10rand10 variables xcitiescities binary ucities real0 objectives distance sumi in cities j in cities distij xij min constraints sosi j in cities sumi in cities xij1 sosj i in cities sumj in cities xij1 noSubs i2nrOfCities j2nrOfCities ij ui uj nrOfCities xij nrOfCities1 CMPL command cmpl tspcmpl CMPL v112 Manual 68 Solution Problem tspcmpl Nr of variables 109 Nr of constraints 92 Objective name distance Solver name CBC Objective status optimal Objective value 321319 min Nonzero variables x Name Type Activity Lower bound Upper bound Marginal x14 B 1 0 1 x21 B 1 0 1 x36 B 1 0 1 x410 B 1 0 1 x58 B 1 0 1 x69 B 1 0 1 x72 B 1 0 1 x87 B 1 0 1 x95 B 1 0 1 x103 B 1 0 1 The tour is optimal as follows 141036958721 282 Other selected examples CMPL can be used as a presolver or simple solver In this way it is possible to find a preliminary solution of a problem as a basis for the model which is to be generated 2821 Solving the knapsack problem The knapsack problem is a very simple problem that does not necessarily have to be solved by an MIP solver CMPL can be used as a simple solver for knapsack problems to approximate the optimal solution The idea of the following models is to evaluate each item using the relation between the value per item and weight per item The knapsack will be filled with the items sorted in descending order until the capacity limit or the minimum value is reached Using the data from the examples in section 2814 a CMPL model to maximize the total sales relative to capacity can be formulated as follows Model 1 maximize the total sales knapsackmaxpresolvedcmpl include knapsackdatacmpl calculating the relative value of each box j in boxes valj pjwj sumSales0 sumWeight0 initial solution x0000000000 CMPL v112 Manual 69 i in boxes maxValmaxval j in boxes maxValvalj sumWeightwj maxWeight xj1 sumSalessumSales pj sumWeightsumWeight wj valj0 break j echo Solution found echo Optimal total sales sumSales echo Total weight sumWeight j in boxes echo x j xj CMPL command cmpl knapsackmaxpresolvedcmpl noOutput cd Solution Solution found Optimal total sales 690 Total weight 57 x1 1 x2 1 x3 0 x4 1 x5 0 x6 1 x7 1 x8 0 x9 1 x10 1 This solution is not identical to the optimal solution in section 2814 but good enough as an approximate solution Model 2 minimize the total weight knapsackminpresolvedcmpl include knapsackdatacmpl calculating the relative value of each box j in boxes valj wjpj CMPL v112 Manual 70 M10000 sumSales0 sumWeight0 initial solution x0000000000 sumSales minSales maxValminval j in boxes maxValvalj sumSales minSales xj1 sumSalessumSales pj sumWeightsumWeight wj valjM break j repeat echo Solution found echo Optimal total weight sumWeight echo Total sales sumSales j in boxes echo x j xj CMPL command cmpl knapsackminpresolvedcmpl noOutput cd Solution Optimal total weight 47 Total sales 630 x1 1 x2 1 x3 0 x4 1 x5 0 x6 0 x7 0 x8 0 x9 1 x10 1 This solution is identical to the optimal solution in section 2814 CMPL v112 Manual 71 2822 Finding the maximum of a concave function using the bisection method One of the alternative methods for finding the maximum of a negative convex function is the bisection method Hillier and Liebermann 2010 p 554f A CMPL programme to find the maximum of f x12x3x 42x6 can be formulated as follows bisectioncmpl parameters distance epsilon e002 initial solution xl 0 xo 2 xn xlxo2 xoxl e fd 12 12 xn3 12 xn5 fd 0 xlxn fd 0 xoxn xn xlxo2 fx 12 xn 3 xn4 2 xn6 echo fxn format104ffd xl format64fxl xo format64fxo xn format64fxn fxn format64ffx repeat echo Optimal solution found xxn echo x format23fx echo function value 12 x 3 x4 2 x6 CMPL command cmpl bisectioncmpl noOutput cd Solution fxn 120000 xl 00000 xo 10000 xn 05000 fxn 57812 fxn 101250 xl 05000 xo 10000 xn 07500 fxn 76948 fxn 40898 xl 07500 xo 10000 xn 08750 fxn 78439 fxn 21940 xl 07500 xo 08750 xn 08125 fxn 78672 fxn 13144 xl 08125 xo 08750 xn 08438 fxn 78829 fxn 03397 xl 08125 xo 08438 xn 08281 fxn 78815 fxn 05113 xl 08281 xo 08438 xn 08359 fxn 78839 CMPL v112 Manual 72 Optimal solution found x 0836 function value 7883868 3 CMPL software package 31 CMPL software package in a glance CMPL ColiopCoin Mathematical Programming Language is a mathematical programming language and a system for mathematical programming and optimisation of linear optimisation problems CMPL executes CBC GLPK Gurobi SCIP or CPLEX directly to solve the generated model instance Because it is also possible to transform the mathematical problem into MPS FreeMPS or OSiL files alternative solvers can be used The CMPL distribution contains Coliop which is an simple IDE Integrated Development Environment for CMPL and also pyCMPL jCMPL and CMPLServer pyCMPL is the CMPL application programming interface API for Python and an interactive shell and jCMPL is CMPLs Java API The main idea of this APIs is to define sets and parameters within the user ap plication to start and control the solving process and to read the solutions into the application if the prob lem is feasible All variables objective functions and constraints are defined in CMPL These functionalities can be used with a local CMPL installation or a CMPLServer CMPLServer is an XMLRPCbased web service for distributed and grid optimisation that can be used with CMPL pyCMPL and jCMPL It is reasonable to solve large models remotely on the CMPLServer that is in stalled on a high performance system CMPL provides four XMLbased file formats for the communication between a CMPLServer and its clients CmplInstance CmplSolutions CmplMessages CmplInfo 32 Installation An installation is not necessary You only have to download the ZIP file for your operating system from httpwwwcolioporg and to unzip it The CMPL package works out of the box in any folder Installation Prerequisites Python 27 Under Linux and OS X you have only to ensure that Python 27 is installed Usually by default Under Windows pyCMPL should work out of the box because the CMPL binary package contains pypy as Python environment 33 CMPL 331 Running CMPL To run CMPL it is necessary to start the cmpl script in the CMPL folder This script sets the CMPL environ ment PATH environment variables and library dependencies and starts the CMPL binary A CMPL model can be solved with the command cmpl problemnamecmpl Is it also possible to execute cmplShell CMPL v112 Manual 73 script in the CMPL folder that also sets the CMPL environment and starts a command line window in which CMPL can be executed 332 Usage of the CMPL command line tool The CMPL command line tool can be used in two modes Using the solver mode an LP or MIP can be formu lated solved and analysed In this mode OSSolverService GLPK or Gurobi is invoked In the model mode it is possible to transform the mathematical problem into MPS FreeMPS or OSiL files that can be used by cer tain alternative LP or MIP solvers cmpl cmplFile options Usage cmpl cmplFilecmpl options Model mode i cmplFile input file m File exports model in MPS format in a file or stdout fm File exports model in FreeMPS format in a file or stdout x File exports model in OSiL XML format in a file or stdout syntax checks the syntax of the CMPL model wo generating of a MPS or OSiL file noOutput no generating of an MPS or OSiL file Solver mode solver solver name of the solver you want to use possible options glpk glpsol cbc scip gurobi cplex default cbc cmplUrl url Url of a CmplServer Without other arguments the problem are solved on the CmplServer synchronous mode send Sends a problem to a CmplServer which have to be specified with cmplUrl asynchronous mode knock Obtains the status of a problem at the CmplServer asynchronous mode cancel Cancels the problem at the CmplServer asynchronous mode retrieve Retrieves the results of the problem from the CmplServer asynchronous mode maxServerTries x maximum number of tries of failed CmplServer calls maxQueuingTime x maximum time in x seconds that a problem waits in a CmplServer queue solution File optimisation results in CmplSolution XML format solutionCsv File optimisation results in CSV format CMPL v112 Manual 74 solutionAscii File optimisation results in ASCII format obj objName name of the objective function objSense maxmin objective sense maxDecimals x maximal number of decimals in the solution report max 12 zeroPrecision x precision of zero values in the solution report default 1e9 ignoreZeros display only variables and constraints with nonzero values in the solution report dontRemoveTmpFiles dont remove temporary files mpsosilosrlgsol alias alias uses an alias name for the cmpl model General options data cmplDataFile reads a cmplData file e File output for error messages and warnings e simple output to stderr default e File output in CmplMessage XML format to file matrix File writes the generated matrix in a file or on stdout l File output for replacements for products of variables s File short statistic info p File output for protocol silent suppresses CMPL and solver messages integerRelaxation all integer variables are changed to continuous variables gn matrix reductions gf generated constraints for products of variables are included at the original position of the product cd warning at multiple parameter definition ci x mode for integer expressions 0 3 default 1 If the result of an integer operation is outside the range of a long integer then the type of result will change from integer to real This flag defines the integer range check behaviour ci 0 no range check ci 1 default range check with a type change if necessary ci 2 range check with error message if necessary ci 3 each numerical operation returns a real result f format format option for MPS or OSiL files C style default f h get this help v version CMPL v112 Manual 75 Examples solver mode cmpl testcmpl solves the problem testcmpl locally with the de fault solver and displays a standard solution report cmpl testcmpl solver glpk testcmpl solves the problem testcmpl locally using GLPK and displays a standard solution report cmpl testcmpl cmplUrl http19495441878080 solves the problem testcmpl remotely with the defined CMPLServer and displays a standard solution report cmpl testcmpl solutionCsv solves the problem testcmpl locally with the de fault solver writes the solution in the CSVfile testcsv and displays a standard solution report cmpl UserstestDocuments ProjectsProject 1testcmpl If the file name or the path contains blanks then one can enclose the entire file name in double quotes Examples model mode cmpl testcmpl m testmps reads the file testcmpl and generates the MPS file testmps cmpl testcmpl fm testmps reads the file testcmpl and generates the Free MPSfile testmps cmpl testcmpl x testosil reads the file testcmpl and generates the OSiL file testosil 333 Syntax checks Syntax checks can be carried out with or without data If the parameters and sets are specified within the parameter section it is only necessary to use the com mand line argument syntax or the CMPL header option arg syntax The following CMPL model testcmpl arg syntax parameters n 12 m 13 cm 1 2 3 bn 15 20 Amn 56 77 105 98 42 111 variables xm real0 objectives profit cT x max constraints machine A x b causes the error message CMPL v112 Manual 76 CMPL model syntax check running error compiler file testcmpl line 7 syntax error unexpected SYMBOLUNDEF expecting error compiler file testcmpl line 13 syntax error unexpected SYMBOLUNDEF CMPL syntax check has finished with 2 errors because the statement bn 15 20 in line 6 has to be closed by a semicolon If a user wants to execute a syntax check without data then a CMPL header entry data has to be defined including a complete specification of the sets and parameters that are necessary for the model Please note the CMPL header option arg syntax has to be specified before the data entry The following CMPL model arg syntax data datafilecdat n set m set cm bn Amn variables xm real0 objectives profit cT x max constraints machine A x b causes the error message CMPL model syntax check running error compiler file cmpl line 5 syntax error unexpected SECTOBJ expecting CMPL syntax check has finished with 1 errors because the statement xm real0 in line 4 has to be closed by a semicolon 334 Using CMPL with several solvers There are two ways to interact with several solvers It is recommended to use one of the solvers which are directly supported and executed by CMPL The CMPL installation routine installs CBC and GLPK where CBC is the default solver If you have installed Gurobi CPLEX or SCIP then you can also use these solvers dir ectly Because CMPL transforms a CMPL model into an MPS a FreeMPS or an OSiL file the generated model instance can be solved by using most of the free or commercial solvers 3341 CBC Cbc Coinor branch and cut is an opensource mixed integer programming solver written in C It can be used as a callable library or standalone solver The CMPL distribution contains the CBC binary For more in formation please visit httpsprojectscoinororgCbc Since CBC is the default solver CBC doesnt need not to be specified cmpl problemcmpl Solves the problem locally with CBC It is possible to use most of the CBC solver options within the CMPL header Please see Appendix 61 for a list of useful CBC parameters CMPL v112 Manual 77 Usage of CBC parameters within the CMPL header opt cbc solverOption solverOptionValue 3342 GLPK The GLPK GNU Linear Programming Kit package is intended for solving largescale linear programming LP mixed integer programming MIP and other related problems The GLPK package includes the pro gram glpsol which is a standalone LPMIP solver This program can be invoked from the command line to read LPMIP problem data in any format supported by GLPK solve the problem and write the problem solution obtained to an output text file GLPK 2014 p 166 For more information please visit the GLPK project website httpwwwgnuorgsoftwareglpk The CMPL package contains GLPK and it can be used by the following command cmpl problemcmpl solver glpk or by the CMPL header flag arg solver glpk GLPK 558 arg solver glpsol GLPK 558 Most of the GLPK solver options can be used by defining solver options within the CMPL header Please see Appendix 62 for a list of useful GLPK parameters Usage of GLPK parameters within the CMPL header opt glpk solverOption solverOptionValue 3343 Gurobi The Gurobi Optimizer is a stateoftheart solver for linear programming LP quadratic programming QP and mixedinteger programming MIP including MILP and MIQP It was designed from the ground up to ex ploit modern multicore processors For solving LP and QP models the Gurobi Optimizer includes highper formance implementations of the primal simplex method the dual simplex method and a parallel barrier solver For MILP and MIQP models the Gurobi Optimizer incorporates the latest methods including cutting planes and powerful solution heuristics wwwgurobicom If Gurobi is installed on the same computer as CMPL then Gurobi can be executed directly only by using the command CMPL v112 Manual 78 cmpl problemcmpl solver gurobi or by the CMPL header flag arg solver gurobi All Gurobi parameters excluding NodefileDir LogFile and ResultFile described in the Gurobi manual can be used in the CMPL header Usage of Gurobi parameters within the CMPL header opt gurobi solverOption solverOptionValue 3344 SCIP SCIP is a project of the KonradZuseZentrum für Informationstechnik Berlin ZIB SCIP is a framework for Constraint Integer Programming oriented towards the needs of Mathematical Programming experts who want to have total control of the solution process and access detailed information down to the guts of the solver SCIP can also be used as a pure MIP solver or as a framework for branchcutandprice SCIP is im plemented as C callable library and provides C wrapper classes for user plugins It can also be used as a standalone program to solve mixed integer programs httpscipzibdewhatisshtmlAchterberg 2009 SCIP can be used only for mixed integer programming MIP problems If SCIP is chosen as solver and the problem is an LP then CBC is executed as solver If SCIP is installed on the same computer as CMPL then SCIP can be connected to CMPL by changing the entry ScipFileName in the file cmplhomebincmplopt Examples ScipFileName ApplicationsScipscip The binary scip is located in the folder Applica tionsScip ScipFileName Program FilesScipscipexe Example for a Windows system Please keep in mind to use a slash as a path separator If this entry is correct then you can execute SCIP directly by using the command cmpl problemcmpl solver scip or by the CMPL header flag CMPL v112 Manual 79 arg solver scip All SCIP parameters described in the SCIP Doxygen Documentation can be used in the CMPL header Please see httpscipzibdedochtmlPARAMETERSshtml Usage SCIP parameters within the CMPL header opt scip solverOption solverOptionValue Please keep in mind that in contrast to the SCIP Doxygen Documentation you do not have to use as as signment operator between the solverOption and the solverOptionValue Examples opt scip branchingscorefunc p CMPL solver parameter description for the parameter branching score function which is described in the SCIP Doxygen Documentation as follows branching score function sum product type char range sp default p branchingscorefunc p opt scip lpcheckfeas TRUE should LP solutions be checked resolving LP when numerical troubles occur type bool range TRUEFALSE default TRUE lpcheckfeas TRUE opt scip lpfastmip 1 which FASTMIP setting of LP solver should be used 0 off 1 low type int range 01 default 1 lpfastmip 1 3345 CPLEX CPLEX is a part of the IBM ILOG CPLEX Optimization Studio and includes simplex barrier and mixed integer optimizers IBM ILOG CPLEX Optimization Studio provides the fastest way to build efficient optimization models and stateoftheart applications for the full range of planning and scheduling problems With its in tegrated development environment descriptive modelling language and builtin tools it supports the entire model development process IBM ILOG CPLEX Optimization Studio manual If CPLEX is installed on the same computer as CMPL then CPLEX can be connected to CMPL by changing the entry CplexFileName in the file cmplhomebincmplopt CMPL v112 Manual 80 Example CplexFileName ApplicationsIBMILOG CPLEXStudio125cplexbin x8664darwincplex The cplex binary is located in the specified folder Please note that for Windows installations you also have to use slashes as a path separators instead of the usual backslashes If this entry is correct then you can execute CPLEX directly by using the command cmpl problemcmpl solver cplex or by the CMPL header flag arg solver cplex All CPLEX parameters described in the CPLEX manual Parameters of CPLEX Parameters Reference Manual can be used in the CMPL header Usage CPLEX parameters within the CMPL header opt cplex solverOption solverOptionValue You have to use the parameters for the Interactive Optimizer The names of subparameters of hierarchical parameters are to be separated by slashes Examples opt cplex threads 2 Sets the default number of parallel threads that will be in voked opt cplex miplimitsaggforcut 4 Limits the number of constraints that can be aggregated for generating flow cover and mixed integer rounding MIR cuts to 4 opt cplex simplextolerancesoptimality 1e8 Sets the reducedcost tolerance for optimality to 1e8 3346 Other solvers Since CMPL transforms a CMPL model into an MPS a FreeMPS or an OSiL file the model can be solved us ing most free or commercial solvers To create MPS FreeMPS or OSiL files please use the following com mands CMPL v112 Manual 81 cmpl problemnamecmpl m problemnamemps MPS export cmpl problemnamecmpl fm problemnamemps FreeMPS export cmpl problemnamecmpl x problemnameosil OSiL export 34 Coliop Coliop is an IDE Integrated Development Environment for CMPL intended to solve linear programming LP problems and mixed integer programming MIP problems Coliop is an open source project licensed under GPL It is written in C and is as an integral part of the CMPL distribution available for most of the relev ant operating systems OS X Linux and Windows Coliop can be executed by clicking the Coliop symbol in the CMPL folder It is either a symbolic link to the Coliop binary OS X or a script which starts Coliop Windows and Linux The first working step is to create or to open a CMPL model If the CMPL model imports an CmplData file by using the Cmpl header entry data or the import of another CMPL file by using the CMPL function include then a list of the involved files are shown right of the CMPL model A user can switch between the files by clicking on the file names in this list If a file does not exists then CMPL suggests to create the file CMPL v112 Manual 82 The model can be solved by clicking the button Solve in the toolbar or by choosing the menu entry Ac tion Solve If the model is feasible and a solution is found the solution appears in the tab Solution It is possible to obtain the output of the invoked solver and CMPLs output in the tab Output CMPL v112 Manual 83 If a syntax error occurs then a user can analyse it by clicking on the error message in the CMPL message list below the CMPL model The position in the CMPL model that occurs the error is shown automatically CMPL v112 Manual 84 35 CMPLServer The CMPLServer is an XMLRPCbased web service for distributed and grid optimisation XMLRPC provides XML based procedures for Remote Procedure Calls RPC which are transmitted between a client and a server via HTTP St Laurent et al 2001 p 1 XMLRPC has been chosen since this it is less resource con suming than other protocols like SOAP or REST due to its simpler functionalities A CMPLServer can be used in a single server mode or in a grid mode Both modes can be understood as distributed systems in which hardware and software components located at networks computers communicate and coordinate their actions only by passing messages Coulouris et al 2012 p 17 Distributed optimisation is in this meaning interpretable as a distributed system that can be used for solving optimisation problems cf Kshemkalyani Singhal 2008 p 1 Fourer etal 2010 CMPL provides four XMLbased file formats for the communication between a CMPLServer and its clients in both modes CmplInstance CmplSolutions CmplMessages CmplInfo A CmplInstance file contains an optimisation problem formulated in CMPL the corresponding sets and parameters in the Cm plData file format as well all CMPL and solver options that belong to the CMPL model If the model is feas ible and a solution is found then a CmplSolutions file contains the solutions and the status of the in voked solver If the model is not feasible then only the solvers status and the solver messages are given in the solution file The CmplMessages file is intended to provide the CMPL status and if existing the CMPL messages A CmplInfo file is an XML file that contains if requested several statistics and the generated matrix of the CMPL model In the single server mode only one CMPLServer that can be accessed synchronously or asynchronously by the clients exists in the network A model can be solved synchronously by executing the CMPL binary with the command line argument cmplUrl url or by running a pyCMPL or jCMPL programme by using the methods Cmplconnecturl for connecting the server and Cmplsolve for solving the model re motely1 The client sends the model to the CMPLServer and then waits for the results If the model is feas ible and an optimal solution is found the solutions can be received If the model contains syntax or other errors or if the model is not feasible the CMPL and solver messages can be obtained Whereby in the syn chronous mode the client has to wait after sending the problem for the results and Messages in one process a model can also be solved asynchronously with pyCMPL and jCMPL by using the methods Cmplsend 1 Please take a look at the pyCMPL and jCMPL descriptions in chapter 4 CMPL v112 Manual 85 Cmplknock and Cmplretrievein several steps After sending the model to the CMPLServer via Cmplsendthe server status can be obtained with Cmplknock If the CMPLServer is finished the solution the CMPL and the solver states and messages can be received by Cmplretrieve It is reas onable to use the single server mode if a large model is formulated on a thin client in order to solve it re motely on the CMPLServer that is installed on a high performance system All these distributed optimisation procedures require a onetoone connection between a CMPLServer and the client The grid mode extends this approach by coupling CMPLServers from several locations and at least one coordinating CMPLGridScheduler to one virtual CMPLServer as a grid computing system that can be defined as a system that coordinates distributed resources using standard open generalpurpose protocols and interfaces to deliver nontrivial qualities of service Forster Kesselmann 2003 pos 722 For the cli ent there does not appear any difference whether there is a connection to a single CMPLServer or to a CM PLGrid The clients model is to be connected with the same functionalities as for a single CMPLServer to a CMPLGridScheduler which is responsible for the load balancing within the CMPLGrid and the assignment of the model to one of the connected CMPLServers After this step the client is automatically connected to the chosen CMPLServer and the model can be solved synchronously or asynchronously A CMPLGrid should be used for handling a huge amount of large scale optimisation problems An example can be a simulation in which each agent has to solve its own optimisation problem at several times An additional example for such a CMPLGrid application is an optimisation web portal that provides a huge amount of optimisation problems Both modes can be controlled by the cmplServer script that can be started in the CmplShell cmplServer command port showLog command start starts as single CMPLServer startInGrid starts CMPLServer and connects to CMPLGrid startScheduler starts as CMPLGridScheduler stop stops CMPLServer or CMPLGridScheduler status returns the status of the CMPLServer or CMPLGridScheduler port defines CMPLServers or CMPLGridSchedulers port showLog shows the CMPLServer or CMPLGridScheduler log file 351 Single server mode The first step to establish the single server mode is to start the CMPLServer by typing the command cmplServer start port Optionally a port can be specified as second argument The behaviour of a CMPLServer can be influenced by editing the file cmplServeropt that is located on Mac OS X in ApplicationsCmplcmplServeron Linux in usrshareCmplcmplServer and on Windows in cprogram files x86Cmpl cmplServer The example below shows the default values in this file CMPL v112 Manual 86 cmplServerPort 8008 maxProblems 4 maxInactivityTime 43200 serviceIntervall 30 solvers cbc glpk The default port of the CMPLServer can be specified with the parameter port The parameter maxProb lems defines how many problems can be carried out simultaneously If more problems than maxProblems are connected with the CMPLServer the supernumerary problems are assigned to the problem waiting queue and automatically started if a running problem is finished or cancelled If a problem is longer inactive than defined by the parameter maxInactivityTime it is cancelled and deleted automatically by the CM PLServer This procedure as well as the problem waiting queue handling are performed by a service thread that works perpetual after a couple of seconds defined by the parameter serviceIntervall With the parameter solvers it can be specified which solvers in the set of the installed solvers can be provided by the CMPLServer A running CMPLServer can be accessed by the CMPL binary or via CMPLs Python and Java APIs that contain CMPLServer clients One can execute a CMPL model remotely on a CMPLServer by using the command line argument cmplUrl cmpl problemcmpl cmplUrl httpipadressorDomainport This command executes the problem on the CMPLServer synchronously That means CMPL waits right after sending the problem for the results and messages in one process It is also possible to run a Cmpl Problem asynchronously on a CMPLServer In a first step the problem is sent to the server by coupling the cmplUrl argument with the send command line argument cmpl problemcmpl cmplUrl httpipadressorDomainport send Afterwards the status of the problem can be obtained by using the command line argument knock cmpl problemcmpl knock The results can be retrieved by using the command line argument retrieve after finishing the problem on the CMPLServer CMPL v112 Manual 87 cmpl problemcmpl retrieve It is also possible to cancel the problem on the CmplServer if necessary by using the command line argu ment cancel cmpl problemcmpl cancel The status of a problem which is sent to a CMPLServer but not retrieved is saved automatically in a dump file in the temp folder Therefore the computer could be switched off after sending the problem and later switched on to retrieve it In pyCMPL and jCMPL a CMPLServer can be connected by using the method Cmplconnect Executing a model can be done synchronously by executing the method Cmplsolve or asynchronously by using the methods Cmplsend Cmplknock and Cmplretrieve These main functionalities are illus trated in the following picture In the first step the client connects the CMPLServer hands over its problem name and the solver with which the problem is to be solved Then the client receives the status of the CMPLServer and if the status is CM PLSERVEROK also the jobId is also sent The status is CMPLSERVERERROR if the demanded solver is not supported or a CMPLServer occurs The synchronous method Cmplsolve is a bundle of the asynchronous methods Cmplsend Cm plknock and Cmplretrieve Cmplsend sends a CmplInstance XML string that contains all relevant information about a CMPL model including the jobId the CMPL and the solver options as well as the model itself and its data files to the CMPLServer If the number of running problems including the model sent is greater than maxProblems the model is moved to the problem waiting queue and the CMPLServer returns the status CMPL v112 Manual 88 CMPLSERVERBUSY If not the CMPLServer starts the solving process automatically if the CmplInstance string is completely received and the model and data files are written to the hard disc In this case the status is set to PROBLEMRUNNING A CMPLServer uses the home path of the user who is running it and saves all relevant data in HOMECm plServer Mac and Linux or HOMEPATHCmplServer Windows The activities of the server can be obtained in the file CmplServerlog Each problem is stored in an own folder specified by the jobId which is deleted automatically after disconnecting the problem In the next step the client asks the CMPLServer whether solving the problem is finished or not via Cm plknock whereby the jobId identifies the problem and the CMPLServer returns the current status The client has to knock until the status is PROBLEMRUNNING or CMPLSERVERERROR If the status is CM PLSERVERBUSY the problem is put into the problem waiting queue until an empty solving slot is available or the maximum queuing time defined with the CMPL option maxQueuingTime or by default 300 seconds is reached The procedure then stops automatically If the status is equal to PROBLEMRUNNING the solution the CMPL and the solver messages and if reques ted some statistics can be received by using Cmplretrieve The client sends its jobId and then re trieves the CmplSolution CmplMesages and CmplInfo XML strings If Cmplknock returns CMPLSERVERERROR the process is stopped The CMPLServer can be stopped by typing the command cmplServer stop port 352 Grid mode A CMPLGrid consists at least of one CMPLGridScheduler and usually a couple of CMPLServers that are con nected to at least one scheduler A CMPLGridScheduler is the gateway to the CMPLGrid for the clients and has to coordinate the traffic in the grid that means it is responsible for the load balancing within the CM PLGrid and the assignment of the models to the connected CMPLServers After receiving a model from a CM PLGridScheduler a CMPLServer has to communicate directly with the client to receive the model to solve it and to send if the problem is feasible the solutions the CMPL and solver messages and if requested some information to the client After these steps the client is disconnected automatically and the CMPLServ ers is waiting for the next problem from a CMPLGridScheduler The first step to start a CMPLGrid is to execute one or more CMPLGridScheduler by typing the command cmplServer startScheduler port As for the CMPLServers the parameter of a CMPLGridScheduler can be edited in the file cmplServeropt CMPL v112 Manual 89 The relevant parameters in cmplServeropt for a CMPLGridScheduler with there default values are shown below cmplServerPort 8008 maxServerTries 3 schedulerServiceIntervall 01 The default port of the CMPLGridScheduler can be specified by the parameter port If one wants to run a CMPLServer on the same computer as the CMPLGridScheduler then the server needs to be started with a dif ferent port via command line argument Since the CMPLGridScheduler has to call functions provided by con nected CMPLServers and additionally has to ensure a high availability and failover the CMPLGridScheduler repeats failed CMPLServer calls whereby the number of tries are specified by the parameter maxServer Tries There is also a service thread that works permanently after a couple of seconds defined by the parameter serviceIntervall Because this service thread is among others responsible for the problem waiting queue handling on the CMPLGridScheduler it makes sense to choose very short service intervals After running one or more CMPLGridSchedulers the involved CMPLServers can be started by typing the com mand cmplServer startInGrid port In addition to the described parameters in cmplServeropt the following parameters are necessary for running a CMPLServer in a CMPLGrid CMPL v112 Manual 90 maxServerTries 3 performanceIndex 1 cmplGridScheduler http1001528008 4 A CMPLServer in a CMPLGrid also has to call functions provided by a CMPLGridScheduler Due to maximum availability and failover the maximum number of tries of failed CMPLGridScheduler calls are to be specified with the parameter maxServerTries Assuming heterogeneous hardware for the CMPLServers in a CM PLGrid it is necessary for a reasonable load balancing to identify several performance levels of the invoked CMPLServers This can be done by the parameter performanceIndex that influences the load balancing function directly The involved operators of the CMPLServers and the CMPLGridSchedulers should specify standardised performance classes used within the entire CMPLGrid with the simple rule the higher the per formance class the higher the performanceIndex The parameter cmplGridScheduler is intended to specify the CMPLGridScheduler to which the CMPLServer is to be connected The first argument is the URL of the scheduler The second parameter defines the maximum number of problems that the CMPLServer provides to this CMPLGridScheduler If a CMPLServer should be connected to more than one scheduler one entry per CMPLGridScheduler is required In the following example the CMPLServer will be connected to two CMPLGridSchedulers with maximally two problems per scheduler cmplGridScheduler http1001528008 2 cmplGridScheduler http1001538008 2 While connecting the CMPLGridScheduler the CMPLServer sends its port the maximum number of provided problems and its performance index It receives the status of the CMPLGridScheduler and a serverId Pos sible states for connecting a CMPLServer are CMPLGRIDSCHEDULEROK or CMPLGRIDSCHEDULER ER ROR Now a client can connect the CMPLGrid in the same way as a client connects a single CMPLServer either by using the CMPL binary cmpl problemcmpl cmplUrl httpipadressorDomainport or in pyCmpl and jCMPL programmes through the method Cmplconnect The client sends automatically the name of the problem and the name of the solver with which the problem should be solved to the CMPLGridScheduler CMPL v112 Manual 91 If the name of the solver is unknown or this solver is not available in the CMPLGrid the CMPLGridScheduler returns CMPLSERVERERROR In case the problem waiting queue is not empty the problem is then as signed to the problem waiting queue and the status is CMPLGRIDSCHEDULERBUSY Otherwise the CMPLGridScheduler returns the status CMPLGRIDSCHEDULEROK the serverUrl of the CMPLServer on which the problem will be solved and the jobId of the problem This CMPLServer is determ ined on the basis of the load balancing function that is shown in the picture below Per server that is provid ing the solver the current capacity factor is to be calculated by the relationship between the current empty problems of this server and the maximum number of provided problems The number of empty problems is controlled by the CMPLGridScheduler with a lower bound of zero and an upper bound equal to the maximum number of provided problems This parameter is decreased if the CMPLServer is taking over a problem and it is increased when the CMPLServer has finished the problem or the problem is cancelled The idea is to send problems tendentiously to those CMPLServer with the highest empty capacity To include the different per formance levels of the invoked CMPLServers in the load balancing decision the current capacity factor is to be multiplied by the performance index The result is the load balancing factor and the CMPLServer with the highest load balancing factor is assigned to the client to solve the problem This CMPLServer then gets the jobId of the CMPL problem by the CMPLGridServer in order to take over all relevant processes to solve this problem Afterwards the client is automatically connected to this CMPLServer The problem waiting queue handling is organised by the CMPLGrid Scheduler service thread that assigns the waiting problems automatically to CMPLServers by using the same functionalities as described above The waiting clients either ask automatically in the synchronous mode or manually in the asynchronous mode both through Cmplknock until the received status is not equal to CMPLGRIDSCHEDULERBUSY The next steps to solve the problem synchronously or asynchronously on the CMPLServer are similar to the procedures in the single server mode as shown in the following figure CMPL v112 Manual 92 The methods Cmplsend Cmplknock and Cmplretrieve are used to send the problem to the CMPLServer to knock for the current status to retrieve the solution and the CMPL and the solver mes sages and if requested some statistics The main differences to the single server mode are that the CM PLServer calls the CMPLServerGrid to add an empty problem slot after finishing solving the problem and that the client is disconnected automatically from the CMPLServer after retrieving the solution messages and statistics The CmplGridScheduler and the CmplServers can be stopped by typing the command cmplServer stop port 353 Reliability and failover A distributed optimisation system or a grid optimisation system is usually implemented in a heterogeneous environment The network notes can be installed on different hardware as well as on different operating sys tems This fact could cause some disturbances within the optimisation network that should be either avoided or reduced in their negative impact of the optimisation processes Beside ensuring a good performance maximum reliability and failover are therefore important targets of the CMPLServer and the CMPLGrid implementations They are ensured by a the problem queue handling on the CMPLGridScheduler and the CMPLServer b multiple executions of failed server calls and c reconnections of problems to the CMPLGridScheduler if an assigned CMPLServer fails CMPL v112 Manual 93 a Problem queue handling If a problem is connected to a CMPLServer or a CMPLGridScheduler and the number of running problems in cluding the model sent is greater than maxProblems it neither makes sense to cancel the problem nor to interrupt the solving process Especially in case of an iterating solving process with a couple of depending problems it is the better way to refer the supernumerary problems automatically to the problem waiting queue For the single server mode the problem queue handling is organised by the CMPLServer whilst in the grid mode the CMPLGridSchedulers are responsible for it In both modes a problem stored in the problem wait ing queue has to wait until an empty solving slot is available or the maximum queuing time is reached In the single server mode the number of problems that can be executed simultaneously on the particular CMPLServer are defined by the parameter maxproblems in cmplServeropt With this parameter it should be avoided to overwhelm the server and to avoid the superproportional effort for managing a huge amount of parallel problems The first empty solving slot that appears when a running problem is finished or cancelled is taking over a waiting problem by using the FIFO approach The number of simultaneously running problems in a CMPLGrid is defined by the sum over all connected CM PLServer of the maximum number of problems provided by the servers This parameter is to be defined per CMPLServer in cmplServeropt as second argument in the entry cmplGridScheduler url maxProblems The CMPLGridScheduler counts the number of running problems per CMPLServer in rela tion to its maximum number of provided problems If it is not possible to find a connected CMPLServer with an empty solving slot then the problem is put to the problem waiting queue In contrast to the single server mode the problem which has been waiting longest is not executed by the first appearing free CMPLServer but it is organised by the described load balancing function over the set of CMPLServers that stated an empty solving slot during two iterations of the CMPLGridScheduler service thread The clients maximum queuing time in seconds can be specified with the CMPL command line argument maxQueuingTime sec This argument can also be set as CMPL header entry arg maxQueuing Time sec or in pyCMPL and jCMPL with the method CmplsetOptionarg maxQueuingTime sec The default value is 300 seconds b Multiple executions of failed server calls To avoid that a single execution of a server method which fails due to network problems like socket errors or others cancels the entire process all failed server calls can be executed again several times The max imum number of executions of failed server calls can be specified for the clients by the CMPL command line argument maxServerTries tries It can also be used in a CMPL header entry arg max ServerTries tries or in pyCMPL and jCMPL by using CmplsetOptionarg maxServer Tries tries The default value is 10 The number of maximum executions of failed server calls in the communication between the CMPLGridScheduler and CMPLServers is defined in cmplServeropt with the entry maxServerTries tries CMPL v112 Manual 94 An exemplary and simplified implementation of this behaviour is shown in the pseudo code listing below 1 2 3 4 5 6 7 8 9 10 11 12 13 serverTries0 while True do try callServerMethod except serverTries1 if serverTriesmaxServerTries then statusCMPLSERVERERROR raise CmplExceptioncalling CmplServer function failed end if end try break end while In a first step the variable serverTries is assigned zero The call of the server method line 4 is imbed ded in an infinite loop lines 213 and in a tryexceptblock for the exception handling lines 311 If no exception occurs then the loop is finished by the break command in line 12 Otherwise serverTries is in cremented by 1 If the maximum number is not exceeded line 7 the server method is called again line 4 If serverTries is greater than maxServerTries then the class variable Cmplstatus is set to CMPL SERVERERROR and a CmplException is raised that have to be handled in the code in which the listing below is imbedded lines 79 c Reconnections of failed problems to the CMPLGridScheduler Multiple server calls are mainly intended to prevent network problems But it could be also possible that other problems caused by CMPLServers connected to a CMPLGridScheduler eg a failed execution of a solver file handling problems at a CMPLServer or the unpredictable shutdown of a CMPLServer occur The idea to handle such problems is that if the assigned CMPLServer fails the particular problem is then recon nected to the CMPLGridScheduler and is taken over by another CMPLServer automatically The following pseudo code listing describes a simplified implementation of Cmplsolve only for the grid mode to illustrate this approach 1 2 3 4 5 6 7 8 9 10 11 serverTries0 while True do try if statusCMPLSERVERERROR then CmplGridSchedulerconnect end if if statusCMPLGRIDSCHEDULERBUSY then while statusCMPLGRIDSCHEDULEROK do CmplGridSchedulerknock if waitingTimemaxQueuingTime then CMPL v112 Manual 95 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 raise CmplExceptionmax queuing time is exceeded end if end while end if connectedToServerTrue CmplServersend while statusPROBLEMFINISHED do CmplServerknock end while CmplServerretrieve break except CmplException serverTries1 if statusCMPLERROR and connectedToServerTrue then CmplGridSchedulercmplServerFailed end if if serverTriesmaxServerTries or statusCMPLGRIDSCHEDULERBUSY then ExceptionHandling exit end if end try end while As in the listing of the multiple server calls the variable serverTries is assigned zero line 1 The entire method is also imbedded in an infinite loop lines 237 and the exception handling is organised as tryex ceptblock lines 336 Before Cmplsolve is called the client has to execute Cmplconnect successfully Therefore the class variable Cmplstatus has to be unequal to CMPLSERVERERROR and an additional Cmplcon nect is not necessary in the first run of Cmplsolvelines 46It is possible that the entire CM PLGrid is busy the status equals CMPLGRIDSCHEDULERBUSY and the problem is moved to the CM PLGridScheduler problem waiting queue line 8 In this case the problem has to wait for the next empty solving slot via Cmplknockline 10 until the CMPLGridScheduler returns the status CMPLGRIDSCHE DULEROK line 9 or the waiting time exceeds the maximum queuing time and a CmplException is raised lines 1113 After this loop the problem is automatically connected to a CMPLServer within the CMPLGrid The class vari able CmplconnectedToServer is assigned True line 16 and the problem is sent to this server through Cmplsend line 18 The problem then has to wait until the problem status is PROBLEMFIN ISHED lines 2022 As soon as the problem is finished the solutions the CMPL and the solver messages as well as if requested some statistics can be retrieved via Cmplretrieve line 24 If no CmplEx CMPL v112 Manual 96 ception or another exception appeared during this procedures the infinite loop is left by the break com mand in line 25 Otherwise the CmplException or other exceptions have to be handled in the except block in the lines 27 36 The first step is to increase the number of failed server call tries line 28 If while executing Cmpl connect Cmplsend Cmplknock or Cmplretrieve an exception is raised and the prob lem is connected to a CMPLServer then the client calls the CMPLGridScheduler method cmplServer Failed in order to report that this CMPLServer failed and to set the status of this server to inactive on the CMPLGridScheduler line 30 This CMPLServer is then excluded from the CMPLGridScheduler load balan cing until CMPLGridSchedulers service thread recognises that this CMPLServer is able to take over problems again If the number of failed server calls exceeds the maximum number of tries or the status is CMPLGRIDSCHEDULERBUSY because the maximum queuing time is exceeded line 32 the entire pro cedure stops by doing the necessary exception handling and by exiting the programme lines 3334 Otherwise the problem has to pass the loop again That means that the problem is reconnected to the CM PLGrid via CMPLGridSchedulerconnect lines 46 and the solving process starts again 36 pyCMPL pyCMPL is the CMPL API for Python and an interactive shell The main idea of this API is to define sets and parameters within the user application to start and control the solving process and to read the solutions into the application if the problem is feasible All variables objective functions and constraints are defined in CMPL These functionalities can be used with a local CMPL installation or a CMPLServer To execute a pyCmpl it is necessary to start the cmplShell script in the CMPL folder that sets the CMPL environment PATH environment variables and library dependencies and starts a command line window in which thy pyCmpl script can be executed with the command pyCmpl problemnamepy 37 jCMPL jCMPL is the CMPL API for Java The main idea of this API is similar to pyCMPL to define sets and paramet ers within the user application to start and control the solving process and to read the solutions into the application if the problem is feasible All variables objective functions and constraints are defined in CMPL These functionalities can be used with a local CMPL installation or a CMPLServer To use the jCMPL functionalities a Java programme has to import jCMPL by import jCMPL and to link your application against jCmpljar and the following jar files that you can find in the CMPL application folder in jCmplLibs commonslang3 wscommonsutil xmplrpcclient xmlrpccom mons Additionally it is necessary to specify an environment variable CMPLBINARY that contains the full path to the CMPL binary This can be done by executing the cmplShell script in the Cmpl folder and to run the Java program in this environment CMPL v112 Manual 97 38 Input and output file formats 381 Overview As shown in the picture below CMPL uses several ASCII files for the communication with the user the solv ers and a CMPLServer CMPL input file for CMPL syntax as described above CmplData data file format for CMPL syntax as described above FreeMPS output file for the generated model in FreeMPS format CmplInstance XML file that contains all relevant information about a CMPL model sent to a CMPLServer Result files solutions of a CMPL model can be obtained in the form of an ASCII CSV or CmplSolutions file CmplSolutions solutions can be solved in CMPLs XML based solution file format CmplMessages XML file that contains the status and messages of a CMPL model CmplInfo XML file that contains if requested several statistics and the generated matrix of the CMPL model To describe the several file types it is necessary to distinguish between the local and the remote mode In the local mode a CMPL model and if existing the corresponding CmplData files are parsed and translated into a FreeMPS file If no syntax or other error occur If there are some errors in the CMPL model the CMPL messages are shown automatically or can be saved in a CmplMessages file The FreeMPS file is to gether with solver specific parameter handed over to the chosen solver that is executed directly by CMPL If the problem is feasible and an optimal solution is found CMPL reads the solution in form of the solver spe cific result format A CMPL user can now obtain the standard solution report or can save the solutions as CMPL v112 Manual 98 CMPL CMPL CmplData User results stdio ASCII CmplSolutons CSV CmplMessages matrix statstcs CBC GLPK SCIP Gurobi Cplex CMPLServer FreeMPS solver specifc parameter interfaces solver specifc result formats CmplInstance CmplSolutons CmplMessages CmplInfo CBC GLPK SCIP Gurobi Cplex FreeMPS solver specifc parameter interfaces solver specifc result formats ASCII or CSV file or as CmplSolutions file It is also possible to obtain the generated matrix and some statist ics on the screen or in a plain text file A user can also process his or her CMPL model remotely on a CMPLServer In the first step CMPL writes automatically all model relevant information CMPL and CmplData files CMPL and solver options in a Cm plInstance file and sends it to the connected CMPLServer After solving the model CMPL receives three XML based file formats CmplSolutions CmplMessages CmplInfo and the user can obtain if a optimal solution is found the standard solution report or can save the solutions and also can get the generated matrix and some statistics If the CMPL model contains errors then the user can retrieve the CMPL messages 382 CMPL and CmplData A CMPL file is an ASCII file that includes the userdefined CMPL code with a syntax as described in this manual The example 15x1 18x 2 22x3 max st 5x1 10x2 15x3175 10x1 5x2 10x3200 0 xn n113 can be formulated with the CmplData file testcdat n set 12 m set 13 cm 15 18 22 bn 175 200 Anm 5 10 15 10 5 10 and the CMPL file testcmpl data testcdat arg solver glpk variables xm real0 objectives profit cT x max constraints res A x b 383 Free MPS The FreeMPSformat is internally used for the communication between CMPL and all local installed solvers The FreeMPS format is an improved version of the MPS format There is no standard for this format but it is widely accepted The structure of a FreeMPS file is the same as an MPS file But most of the restricted MPS CMPL v112 Manual 99 format requirements are eliminated eg there are no requirements for the position or length of a field For more information please visit the project website of the lpsolve project httplpsolvesourceforgenet The FreeMPS file for the given CMP example is generated as follows CMPL FreeMPS Export NAME testcmpl ROWS N profit L res1 L res2 COLUMNS x1 profit 15 res1 5 x1 res2 10 x2 profit 18 res1 10 x2 res2 5 x3 profit 22 res1 15 x3 res2 10 RHS RHS res1 175 res2 200 RANGES BOUNDS PL BOUND x1 PL BOUND x2 PL BOUND x3 ENDATA 384 CmplInstance CmplInstance is an XMLbased format that contains all relevant information about a CMPL model CMPL and CmplData files CMPL and solver options to be sent to a CMPLServer A CmplInstance file consists of three major sections The general section contains the name of the problem and the jobId that is received automatically during connecting the CMPLServer The options section consists of the CMPL and solver options that a user has specified on the command line The prob lemFiles section is indented to store the CMPL file and all corresponding CmplData files All CmplData files no matter whether they are specified within the CMPL model or as command line argument are auto matically included in the CmplInstance file To avoid some misinterpretation of some special characters while reading the CmplInstance on the CMPLServer the content of the CMPL model and the CmplData files are automatically unescaped by CMPL The XSD XML Schema Definition of CmplInstance is defined as follows xml version10 encodingUTF8 xsschema elementFormDefaultqualified xmlnsxshttpwwww3org2001XMLSchema xselement nameCmplInstance xscomplexType xssequence CMPL v112 Manual 100 xselement refgeneral minOccurs1 maxOccurs1 xselement refoptions minOccurs0 maxOccurs1 xselement refproblemFiles minOccurs1 maxOccurs1 xssequence xsattribute nameversion typexsdecimal userequired xscomplexType xselement xselement namegeneral xscomplexType xssequence xselement namename typexsstring minOccurs1 maxOccurs1 xselement namejobId typexsstring minOccurs1 maxOccurs1 xssequence xscomplexType xselement xselement nameoptions xscomplexType xssequence xselement nameopt typexsstring minOccurs0 maxOccursunbounded xssequence xscomplexType xselement xselement nameproblemFiles xscomplexType xssequence xselement reffile minOccurs1 maxOccursunbounded xssequence xscomplexType xselement xselement namefile xscomplexType xssimpleContent xsextension basexsstring xsattribute namename typexsstring userequired xsattribute nametype typefileType userequired xsextension xssimpleContent xscomplexType xselement xssimpleType namefileType xsrestriction basexsstring xsenumeration valuecmplMain xsenumeration valuecmplData xsrestriction CMPL v112 Manual 101 xssimpleType xsschema For the given example the CmplInstance file testcinst is created automatically by CMPL through by us ing the command line arguments matrix testmat s teststat and the model is executed remotely on a CMPLServer xml version 10 encodingUTF8 standaloneyes CmplInstance version10 general nametestcmplname jobId1001220140105170523496795jobId general options opt arg matrix testmatopt optarg s teststatopt options problemFiles file nametestcmpl typecmplMain data testcdat arg solver glpk arg cmplUrl http100128008 variables xm real0 objectives profit cT x gt max constraints res A x lt b file file nametestcdat typecmplData n set lt12gt m set lt13gt cm lt 15 18 22 gt bn lt 175 200 gt Anm lt 5 10 15 10 5 10 gt file problemFiles CmplInstance CMPL v112 Manual 102 385 ASCII or CSV result files If the problem is feasible and an optimal solution is found a user can obtain this optimal solution in the form of an ASCI or CSV file by using the command line arguments solutionAscii file or solu tionCsv file This files can additionally contain all integer feasible solutions if Cplex or Gurobi are used and the the CMPL header option display solutionPool is defined The ASCII result file testsol for the given CMPL example is generated as follows Problem testcmpl Nr of variables 3 Nr of constraints 2 Objective name profit Solver name GLPK Display variables all Display constraints all Objective status optimal Objective value 405 max Variables Name Type Activity Lower bound Upper bound Marginal x1 C 15 0 Infinity 0 x2 C 10 0 Infinity 0 x3 C 0 0 Infinity 7 Constraints Name Type Activity Lower bound Upper bound Marginal res1 L 175 Infinity 175 14 res2 L 200 Infinity 200 08 The corresponding CSV result file testcsv is generated as follows CMPL csv export Problemtestcmpl Nr of variables3 Nr of constraints2 Objective nameprofit Objective sensemax SolverGLPK Display variablesall Display constraintsall Objective statusoptimal Objective value405 Variables NameTypeActivityLowerBoundUpperBoundMarginal x1C150Infinity0 x2C100Infinity0 x3C00Infinity7 CMPL v112 Manual 103 Constraints NameTypeActivityLowerBoundUpperBoundMarginal res1L175Infinity17514 res2L200Infinity20008 386 CmplSolutions CmplSolutions is an XMLbased format for representing the general status and the solutions if the problem is feasible and one or more solutions are found A user can save it by using the command line argument solution File It is also internally used for receiving solutions from a CMPLServer As shown in the corresponding XSD below A CmplSolutions file contains a general block for general in formation about the solved problem and a solutions block for the results of all solutions found includ ing the variables and constraints xml version10 encodingUTF8 xsschema xmlnsxshttpwwww3org2001XMLSchema elementFormDefaultqualified xselement nameCmplSolutions xscomplexType xssequence xselement refgeneral minOccurs1 maxOccurs1 xselement refsolution minOccurs0 maxOccursunbounded xssequence xsattribute nameversion userequired typexsdecimal xscomplexType xselement xselement namegeneral xscomplexType xssequence xselement nameinstanceName typexsstring minOccurs1 maxOccurs1 xselement namenrOfVariables typexsnonNegativeInteger minOccurs1 maxOccurs1 xselement namenrOfConstraints typexsnonNegativeInteger minOccurs1 maxOccurs1 xselement nameobjectiveName typexsstring minOccurs1 maxOccurs1 xselement nameobjectiveSense typexsstring minOccurs1 maxOccurs1 xselement namenrOfSolutions typexsnonNegativeInteger minOccurs1 maxOccurs1 xselement namesolverName typexsstring minOccurs1 maxOccurs1 xselement namevariablesDisplayOptions typexsstring minOccurs1 maxOccurs1 xselement nameconstraintsDisplayOptions typexsstring minOccurs1 maxOccurs1 xssequence xscomplexType xselement xselement namesolution xscomplexType xssequence xselement refvariables minOccurs1 maxOccurs1 CMPL v112 Manual 104 xselement reflinearConstraints minOccurs1 maxOccurs1 xssequence xsattribute nameidx userequired typexsnonNegativeInteger xsattribute namestatus userequired typexsstring xsattribute namevalue userequired typexsdecimal xscomplexType xselement xselement namevariables xscomplexType xssequence xselement minOccurs1 maxOccursunbounded refvariable xssequence xscomplexType xselement xselement namelinearConstraints xscomplexType xssequence xselement minOccurs1 maxOccursunbounded refconstraint xssequence xscomplexType xselement xselement namevariable xscomplexType xsattribute nameidx userequired typexsnonNegativeInteger xsattribute namename userequired typexsstring xsattribute nametype userequired typevarType xsattribute nameactivity userequired typexsdouble xsattribute namelowerBound userequired typexsdouble xsattribute nameupperBound userequired typexsdouble xsattribute namemarginal userequired typexsdouble xscomplexType xselement xselement nameconstraint xscomplexType xsattribute nameidx userequired typexsnonNegativeInteger xsattribute namename userequired typexsstring xsattribute nametype userequired typeconType xsattribute nameactivity userequired typexsdouble xsattribute namelowerBound userequired typexsdouble xsattribute nameupperBound userequired typexsdouble xsattribute namemarginal userequired typexsdouble xscomplexType xselement xssimpleType namevarType CMPL v112 Manual 105 xsrestriction basexsstring xsenumeration valueC xsenumeration valueI xsenumeration valueB xsrestriction xssimpleType xssimpleType nameconType xsrestriction basexsstring xsenumeration valueL xsenumeration valueE xsenumeration valueG xsrestriction xssimpleType xsschema The CmplSolutions file testcsol for the given CMPL example is generated as follows xml version 11 encodingUTF8 standaloneyes CmplSolutions version10 general instanceNametestcmplinstanceName nrOfVariables3nrOfVariables nrOfConstraints2nrOfConstraints objectiveNameprofitobjectiveName objectiveSensemaxobjectiveSense nrOfSolutions1nrOfSolutions solverNameGLPKsolverName variablesDisplayOptionsallvariablesDisplayOptions constraintsDisplayOptionsallconstraintsDisplayOptions general solution idx0 statusoptimal value405 variables variable idx0 namex1 typeC activity15 lowerBound0 upperBoundInfinity marginal0 variable idx1 namex2 typeC activity10 lowerBound0 upperBoundInfinity marginal0 variable idx2 namex3 typeC activity0 lowerBound0 upperBoundInfinity marginal7 variables linearConstraints constraint idx0 nameres1 typeL activity175 lowerBoundINF upperBound175 marginal14 constraint idx1 nameres2 typeL activity200 lowerBoundINF upperBound200 marginal08 linearConstraints CMPL v112 Manual 106 solution CmplSolutions 387 CmplMessages CmplMessages is an XMLbased format for representing the general status andor errors of the transforma tion of a CMPL model in one of the described output files CmplMessages is intended for communication with other software that uses CMPL for modelling linear optimisation problems and can be obtained by the com mand line argument e file It is also internally used for receiving CMPL messages from a CMPLServer An CmplMessages file consists of two major sections The general section describes the general status and the name of the model and a general message after the transformation The messages section con sists of one or more messages about specific lines in the CMPL model The XSD is defined as follows xml version10 encodingUTF8 xsschema xmlnsxshttpwwww3org2001XMLSchema elementFormDefaultqualified xselement nameCmplMessages xscomplexType xssequence xselement refgeneral minOccurs1 maxOccurs1 xselement refmessages minOccurs0 maxOccursunbounded xssequence xsattribute nameversion userequired typexsdecimal xscomplexType xselement xselement namegeneral xscomplexType xssequence xselement namegeneralStatus typexsstring minOccurs1 maxOccurs1 xselement nameinstanceName typexsstring minOccurs1 maxOccurs1 xselement namemessage typexsstring minOccurs0 maxOccurs1 xssequence xscomplexType xselement xselement namemessages xscomplexType xssequence xselement refmessage minOccurs0 maxOccursunbounded xssequence xsattribute namenumberOfMessages userequired typexsnonNegativeInteger xscomplexType xselement CMPL v112 Manual 107 xselement namemessage xscomplexType xsattribute nametype typemsgType userequired xsattribute namefile typexsstring userequired xsattribute nameline typexsnonNegativeInteger userequired xsattribute namedescription typexsstring userequired xscomplexType xselement xssimpleType namemsgType xsrestriction basexsstring xsenumeration valueerror xsenumeration valuewarning xsrestriction xssimpleType xsschema After excecuting the given CMPL model CMPL will fnish without errors The general status is repres ented in the following CmplMesages file testcmsg xml version10 encodingUTF8 CmplMessages version11 general generalStatusnormalgeneralStatus instanceNametestcmplinstanceName messagecmpl finished normalmessage general CmplMessages If a wrong symbol name for the matrix A eg a is used in line 11 CMPL would be finish with er rors represented in CmplMesages file testcmsg xml version10 encodingUTF8 CmplMessages version11 general generalStatuserrorgeneralStatus instanceNametestcmplinstanceName messagecmpl finished with errorsmessage general messages numberOfMessages1 message type error filetestcmpl line11 descriptionsyntax error unexpected SYMBOLUNDEF messages CmplMessages CMPL v112 Manual 108 388 CmplInfo CmplInfo is a simple XML file that contains as shown in the XSD below if requested several statistics and the generated matrix of the CMPL model xml version10 encodingUTF8 xsschema xmlnsxshttpwwww3org2001XMLSchema elementFormDefaultqualified xselement nameCmplInfo xscomplexType xssequence xselement refgeneral minOccurs1 maxOccurs1 xselement refstatistics minOccurs0 maxOccurs1 xselement refmatrix minOccurs0 maxOccurs1 xssequence xsattribute nameversion userequired typexsdecimal xscomplexType xselement xselement namegeneral xscomplexType xssequence xselement nameinstancename typexsstring minOccurs1 maxOccurs1 xssequence xscomplexType xselement xselement namestatistics xscomplexType xssimpleContent xsextension basexsstring xsattribute namefile userequired typexsstring xsextension xssimpleContent xscomplexType xselement xselement namematrix xscomplexType xssimpleContent xsextension basexsstring xsattribute namefile userequired typexsstring xsextension xssimpleContent xscomplexType xselement xsschema CMPL v112 Manual 109 For the example the CmplInstance file testcinfo is created automatically by CMPL by using the com mand line arguments matrix testmat s teststat and the model is executed remotely on a CMPLServer xml version10 encodingUTF8 CmplInfo version10 general instancenametestcmplinstancename general statistics fileteststat File UsersmikeCmplServer1001220140105170523496795testcmpl 3 Columns variables 3 Rows constraints objective function 6 100 of 6 coefficients of the constraints are nonzero statistics matrix filetestmat Variable name x1 x2 x3 Variable type C C C profit max 15 18 22 Subject to RHS res1 L 5 10 15 175 res2 L 10 5 10 200 Lower Bound 0 0 0 Upper Bound matrix CmplInfo 4 CMPLs APIs CMPL provides two APIs pyCMPL for Python and jCMPL for Java The main idea of this APIs is to define sets and parameters within the user application to start and control the solving process and to read the solutions into the application if the problem is feasible All variables objective functions and constraints are defined in CMPL These functionalities can be used with a local CMPL installation or a CMPLServer The structure and the classes including the methods and attributes are mostly identical or very similar in both APIs The main difference are the attributes of a class that can be obtained in pyCmpl by ro attributes and in jCMPL by getter methods 41 Creating Python and Java applications with a local CMPL installation pyCMPL and jCMPL contain a couple of classes to connect a Python or Java application with CMPL as shown in the figure below CMPL v112 Manual 110 The classes CmplSet and CmplParameter are intended to define sets and parameters that can be used with several Cmpl objects With the Cmpl class it is possible to define a CMPL model to commit sets and parameters to this model to start and control the solving process and to read the CMPL and solver mes sages and to have access to the solutions via CmplMessages and CmplSolutions objects To illustrate the formulation of a pyCmpl script and the corresponding java programme an example taken from HillierLiebermann 2010 p 334f is used Consider a simple assignment problem that deals with the assignment of three machines to four possible locations There is no work flow between the machines The total material handling costs are to be minimised The hourly material handling costs per machine and loca tion are given in the following table Locations 1 2 3 4 Machines 1 13 16 12 11 2 15 13 20 3 5 7 10 6 CMPL v112 Manual 111 CMPL supported solvers CBC GLPK SCIP Gurobi Cplex pyCMPL jCMPL Application CmplSet CmplParameter Cmpl CmplSolution CmplMessages CmplExceptions CmplInfo model data Cmpl model Statstcs and generated matrix CmplMessages CmplSolutons CmplInfo CMPL model CmplData fles CMPL optons solver optons CMPL messages solutons solver messages The mathematical model i j A cijxij min st k j A ki xkj1 i11m i l A l j xil1 j11n xij01 i jA with Parameters A set of the possible combination of machines and locations m number of machines n number of locations cij hourly material handling costs of machine i at location j Variables xij assignment variable of machine i at location j can be formulated in CMPL as follows data machines set locations set A set2 cA variables xA binary objectives costs sum ij in A cijxij min constraints sosm i in machines sum j in A i xij 1 sosl j in locations sum i in A j xij 1 The interface for the sets and parameters provided by a pyCmpl script or jCMPL programme is the CMPL header entry data 411 pyCMPL The first step to formulate this problem as a pyCmpl script after importing the pyCmpl package is to create a Cmpl object where the argument of the constructor is the name of the CMPL file usrbinpython from pyCmpl import m Cmplassignmentcmpl As in the data entry two 1tuple sets machines and locations and one 2tuple set A are necessary for the CMPL model To create a CmplSet a name and for ntuple sets with n1 the rank are needed as argu CMPL v112 Manual 112 ments for the constructor The name has to be identical to the corresponding name in the CMPL header entry data The set data is specified by the CmplSet method setValues This is an overloaded method with different arguments for several types of sets locations CmplSetlocations locationssetValues14 machines CmplSetmachines machinessetValues13 combinations CmplSetA 2 combinationssetValues 11121314 212324 31323334 As shown in the listing above the set locations is assigned 124 and the set machines consists of 123 because the first argument of setValues for this kind of sets is the starting value and the second argument is the end value while the increment is by default equal to one The values of the 2tuple set combinations are defined in the form of a list that consists of lists of valid combinations of machines and locations For the definition of a CMPL parameter a user has to create a CmplParameter object where the first argu ment of the constructor is the name of the parameter If the parameter is an array it is also necessary to specify the set or sets through which the parameter array is defined Therefore it is necessary to commit the CmplSet combinations beside the name c to create the CmplParameter array c c CmplParameterccombinations csetValues1316121115132057106 CmplSet objects and CmplParameter objects can be used in several CMPL models and have to be com mitted to a Cmpl model by the Cmpl methods setSets and setParameters After this step the problem can be solved by using the Cmpl method solve msetSetsmachineslocationscombinations msetParametersc msolve After solving the model the status of CMPL and the invoked solver can be analysed through the Cmpl attrib utes solutionsolverStatus and solutioncmplStatus print Objective value msolutionvalue print Objective status msolutionstatus If the problem is feasible and a solution is found it is possible to read the names the types the activities the lower and upper bounds and the marginal values of the variables and the constraints into the Python ap plication The Cmpl attributes solutionvariables and solutionconstraints contain a list of variable and constraint objects CMPL v112 Manual 113 print Variables for v in msolutionvariables print vname vtype vactivityvlowerBoundvupperBound print Constraints for c in msolutionconstraints print cname ctype cactivityclowerBoundcupperBound pyCmpl provides its own exception handling through the class CmplException that can be used in a try and except block try except CmplException e print emsg The entire pyCmpl script assignmentpy shows as follows usrbinpython from pyCmpl import try m Cmplassignmentcmpl locations CmplSetlocations locationssetValues14 machines CmplSetmachines machinessetValues13 combinations CmplSetA 2 combinationssetValues 11121314 21232431323334 c CmplParameterccombinations csetValues1316121115132057106 msetSetsmachineslocationscombinations msetParametersc msolve print Objective value msolutionvalue print Objective status msolutionstatus print Variables for v in msolutionvariables print vname vtype vactivity vlowerBound vupperBound CMPL v112 Manual 114 print Constraints for c in msolutionconstraints print cname ctype cactivity clowerBound cupperBound except CmplException e print emsg and can be executed by typing the command pyCmpl assignmentpy under Linux and Mac in the terminal or under Windows in the CmplShell and prints the following solution to stdOut Objective value 290 Objective status optimal Variables x11 B 00 00 10 x12 B 00 00 10 x13 B 00 00 10 x14 B 10 00 10 x21 B 00 00 10 x23 B 10 00 10 x24 B 00 00 10 x31 B 10 00 10 x32 B 00 00 10 x33 B 00 00 10 x34 B 00 00 10 Constraints sosm1 E 10 10 10 sosm2 E 10 10 10 sosm3 E 10 10 10 sosl1 L 10 inf 10 sosl2 L 00 inf 10 sosl3 L 10 inf 10 sosl4 L 10 inf 10 412 jCMPL To use the jCMPL functionalities a Java programme has to import jCMPL by import jCMPL and to link your application against jCmpljar and the following jar files that you can find in the CMPL applicatiopn folder in jCmplLibs commonslang3 wscommonsutil xmplrpcclient xmlrpccom mons CMPL v112 Manual 115 The first step to formulate this problem as a jCmpl programme after importing the jCmpl package is to cre ate a Cmpl object where the argument of the constructor is the name of the CMPL file Since jCMPL provides it own exception handling the main method has to throw CmplExeptions import jCMPL public class Assignment public static void mainString args throws CmplException try Cmpl m new Cmplassignmentcmpl As in pyCMPL to create a CmplSet a name and for ntuple sets with n1 the rank are needed as arguments for the constructor whereby the name has to be identical to the corresponding name in the CMPL header entry data The set data is specified by the CmplSetsetValues This is an overloaded method with different arguments for several types of sets CmplSet locations new CmplSetlocations locationssetValues1 4 CmplSet machines new CmplSetmachines machinessetValues1 3 CmplSet combinations new CmplSetA 2 int combiVals 1 1 1 2 1 3 1 4 2 1 2 3 2 4 3 1 3 2 3 3 3 4 combinationssetValuescombiVals In the listing above the set locations is assigned 124 and the set machines consists of 123 The first argument of setValues for this algorithmic sets is the starting value and the second argument is the end value while the increment is by default equal to one The values of the 2tuple set com binations are defined in the form of a matrix of integers that consists all valid combinations of machines and locations To create a CMPL parameter a user has to define a CmplParameter object whereby the first argument of the constructor is the name of the parameter For parameter arrays it is also necessary to specify the set or sets through which the parameter array is defined Therefore it is necessary to commit the CmplSet com binations beside the name c to create the CmplParameter array c CmplParameter costs new CmplParameterc combinations int costVals 13 16 12 11 15 13 20 5 7 10 6 costssetValuescostVals In the next step the sets and parameters have to be committed to a Cmpl model by the Cmpl methods setSets and setParameters and the problem can be solved by using the Cmpl method solve msetSetsmachines locations combinations msetParameterscosts msolve CMPL v112 Manual 116 After solving the model the status of CMPL and the invoked solver can be analysed through the methods CmplsolutionsolverStatusand CmplsolutioncmplStatus SystemoutprintfObjective value f n msolutionvalue SystemoutprintfObjective status s n msolutionstatus If the problem is feasible and a solution is found it is possible to read the names the types the activities the lower and upper bounds and the marginal values of the variables and the constraints into the Python ap plication The methods Cmplsolutionvariables and Cmplsolutionconstraints return a list of variable and constraint objects SystemoutprintlnVariables for CmplSolElement v msolutionvariables Systemoutprintf10s 3s 10d 100f 100fn vname vtype vactivity vlowerBound vupperBound SystemoutprintlnConstraints for CmplSolElement c msolutionconstraints Systemoutprintf10s 3s 100f 100f 100fn cname ctype cactivity clowerBound cupperBound The entire jCmpl programme assignmentjava shows as follows import jCMPL public class Assignment1 public static void mainString args throws CmplException try Cmpl m new Cmplassignmentcmpl CmplSet locations new CmplSetlocations locationssetValues1 4 CmplSet machines new CmplSetmachines machinessetValues1 3 CmplSet combinations new CmplSetA 2 int combiVals 1 1 1 2 1 3 1 42 1 2 3 2 43 1 3 2 3 3 3 4 combinationssetValuescombiVals CmplParameter costs new CmplParameterc combinations int costVals 13 16 12 11 15 13 20 5 7 10 6 costssetValuescostVals msetSetsmachines locations combinations msetParameterscosts CMPL v112 Manual 117 msolve SystemoutprintfObjective value f n msolutionvalue SystemoutprintfObjective status s n msolutionstatus SystemoutprintlnVariables for CmplSolElement v msolutionvariables Systemoutprintf10s 3s 10d 100f 100fn vname vtype vactivity vlowerBound vupperBound SystemoutprintlnConstraints for CmplSolElement c msolutionconstraints Systemoutprintf10s 3s 100f 100f 100fn cname ctype cactivity clowerBound cupperBound catch CmplException e Systemoutprintlne and prints after starting the following solution to stdOut Objective value 29000000 Objective status optimal Variables x11 B 0 0 1 x12 B 0 0 1 x13 B 0 0 1 x14 B 1 0 1 x21 B 0 0 1 x23 B 1 0 1 x24 B 0 0 1 x31 B 1 0 1 x32 B 0 0 1 x33 B 0 0 1 x34 B 0 0 1 Constraints sosm1 E 1 1 1 sosm2 E 1 1 1 sosm3 E 1 1 1 sosl1 L 1 Infinity 1 sosl2 L 0 Infinity 1 sosl3 L 1 Infinity 1 sosl4 L 1 Infinity 1 CMPL v112 Manual 118 42 Creating Python and Java applications using CMPLServer The class Cmpl also provides the functionality to communicate with a CMPLServer or a CMPLGridScheduler whereas it doesnt matter for the client whether it is connected to a single CMPLServer or to a CMPLGrid As shown in the figure below the first step to communicate with a CMPLServer is the Cmplconnect method that returns if connected a jobId After connecting a problem can be solved synchronously or asynchron ously The Cmpl method solve sends a CmplInstance string to the connected CMPLServer and waits for the returning CmplSolutions CmplMessages and if requested CmplInfo XML strings After this syn chronous process a user can access the solutions if the problem is feasible or if not it can be analysed whether the CMPL formulations or the solver is the cause of the problem To execute the solving process asynchronously the Cmpl methods send knock and retrieve have to be used Cmplsend sends a CmplInstance string to the CMPLServer and starts the solving process remotely Cmplknock asks for a CMPL model with a given jobId whether the solving process is finished or not If the problem is finished the CmplSolutions and the CmplMessages strings can be read into the user application with Cmplre trieve CMPL v112 Manual 119 Application CmplSet CmplParameter Cmpl model data Cmpl model solutons messages statstcs matrix CMPLServer XMLRPC connect send knock retrieve solve name jobId CmplInstance CmplSolutons CmplMessages CmplInfo jobId jobId CmplSolutons CmplMessages CmplInfo CmplInstance status status CMPL supported solvers CBC GLPK SCIP Gurobi Cplex CMPL model CmplData fles CmplSolutons CmplMessages model data pyCMPL jCMPL statstcs matrix 421 pyCMPL The first step to create a distributed optimisation application is to start the CMPLServer Assuming that a CMPLServer is running on 1949545708008 the assignment problem can be solved remotely only by in cluding mconnecthttp1949545708008 in the source code before Cmplsolve is executed The pyCmpl script assignmentremotepy shows as follows usrbinpython from pyCmpl import try m Cmplassignmentcmpl locations CmplSetlocations locationssetValues14 machines CmplSetmachines machinessetValues13 combinations CmplSetA 2 combinationssetValues 11121314 21232431323334 c CmplParameterccombinations csetValues1316121115132057106 msetSetsmachineslocationscombinations msetParametersc mconnecthttp1949545708008 msolve print Objective value msolutionvalue print Objective status msolutionstatus print Variables for v in msolutionvariables print vname vtype vactivityvlowerBoundvupperBound print Constraints for c in msolutionconstraints print cname ctype cactivityclowerBoundcupperBound except CmplException e print emsg CMPL v112 Manual 120 422 jCMPL The jCMPL programme assignmentremotejava shows as follows import jCMPL public class Assignment1 public static void mainString args throws CmplException try Cmpl m new Cmplassignmentcmpl CmplSet locations new CmplSetlocations locationssetValues1 4 CmplSet machines new CmplSetmachines machinessetValues1 3 CmplSet combinations new CmplSetA 2 int combiVals 1 1 1 2 1 3 1 42 1 2 3 2 43 1 3 2 3 3 3 4 combinationssetValuescombiVals CmplParameter costs new CmplParameterc combinations int costVals 13 16 12 11 15 13 20 5 7 10 6 costssetValuescostVals msetSetsmachines locations combinations msetParameterscosts mconnecthttp1949545708008 msolve SystemoutprintfObjective value f n msolutionvalue SystemoutprintfObjective status s n msolutionstatus SystemoutprintlnVariables for CmplSolElement v msolutionvariables Systemoutprintf10s 3s 10d 100f 100fn vname vtype vactivity vlowerBound vupperBound SystemoutprintlnConstraints for CmplSolElement c msolutionconstraints Systemoutprintf10s 3s 100f 100f 100fn cname ctype cactivity clowerBound cupperBound CMPL v112 Manual 121 catch CmplException e Systemoutprintlne 43 pyCMPL reference manual 431 CmplSets The class CmplSet is intended to define sets that can be used with several Cmpl objects Methods CmplSetsetNamerank Description Constructor Parameter str setName name of the set Has to be equal to the corresponding name in the CMPL model int rank optional rank n for a ntuple set default 1 Return CmplSet object CmplSetsetValuessetList Description Defines the values of an enumeration set Parameter list setList for a set of ntuples with n1 list of single indexing entries intlongstr for a set of ntuples with n1 list of lists that contain intlongstr tuples Return CmplSetsetValuesstartNumberendNumber Description Defines the values of an algorithmic set startNumber startNumber1 endNumber Parameter int startNumber start value of the set int endNumber end value of the set Return CmplSetsetValuesstartNumberstependNumber Description Defines the values of an algorithmic set startNumber startNumberstep endNumber CMPL v112 Manual 122 Parameter int startNumber start value of the set int step positive value for increment negative value for decrement Int endNumber end value of the set Return Ro attributes CmplSetvalues Description List of the indexing entries of the set Return list of single indexing entries for a set of ntuples with n1 of tuples for a set of ntuples with n1 CmplSetname Description Name of the set Return str name of the CMPL set not the name of the CmplSet object CmplSetrank Description Rank of the set Return int number of n of a ntuple set CmplSetlen Description Length of the set Return int number of indexing entries Examples s CmplSets ssetValues04 print srank print slen print sname print svalues s is assigned s01 4 1 4 s 0 1 2 3 4 s CmplSeta ssetValues1020 print srank print slen print sname print svalues s is assigned s108 0 1 6 s 10 8 6 4 2 0 CMPL v112 Manual 123 s CmplSetFOOD ssetValuesBEEFCHKFISH print srank print slen print sname print svalues s is assigned s BEEF CHK FISH 1 3 FOOD BEEF CHK FISH s CmplSetc3 ssetValues 111 112 121 print srank print slen print sname print svalues s is assigned a 3tuple set of integers 3 3 c 1 1 1 1 1 2 1 2 1 432 CmplParameters The class CmplParameters is intended to define parameters that can be used with several Cmpl objects Methods CmplParameterparamName set1set2 Description Constructor Parameter str paramName name of the parameter Has to be equal to the corresponding name in the CMPL model CmplSet set1set2 optional set or sets through which the parameter array is defined default None Return CmplParameter object CmplParametersetValuesval Description Defines the values of a scalar parameter Parameter intlongfloat str val value of the scalar parameter Return CmplParametersetValuesvalList Description Defines the values of a parameter array Parameter list valList list of intlongfloatstrlist value list of the parameter array CMPL v112 Manual 124 Return Ro attributes CmplParametervalues Description List of the values of a parameter Return list of intlongfloatstrlist value list of the parameter array CmplParametervalue Description Value of a scalar parameter Return intlongfloatstr value of the scalar parameter CmplParametersetList Description List of sets through which the parameter array is defined Return list of CmplSet objects through which the parameter array is defined CmplParametername Description Name of the parameter Return str name of the CMPL parameter not the name of the CmplParameter object CmplParameterrank Description Rank of the parameter Return int rank of the CMPL parameter CmplParameterlen Description Length of the parameter array Return long number of elements in the parameter array Examples p CmplParameterp psetValues2 print pvalues print pvalue print pname print prank print plen p is assigned 2 2 2 p 0 1 s CmplSets ssetValues04 p CmplParameterps psetValues12345 print pvalues p is assigned 12 5 1 2 3 4 5 CMPL v112 Manual 125 print pname print prank print plen p 1 5 products CmplSetproducts productssetValues13 machines CmplSetmachines machinessetValues12 aCmplParameteramachines products asetValues 8151215108 print avalues print aname print arank print alen for e in asetList print evalues a is assigned a 2X3 matrix of integers 8 15 12 15 10 8 a 2 6 1 2 1 2 3 s CmplSets2 ssetValues1122 p CmplParameterps psetValues11 print pvalues print pname print prank print plen s is assigned the indices of a matrix diagonal s is assigned a 2x2 identity matrix 1 1 p 2 2 433 Cmpl With the Cmpl class it is possible to define a CMPL model to commit sets and parameters to this model to start and control the solving process and to read the CMPL and solver messages and to have access to the solutions via CmplMessages and CmplSolutions objects 4331 Establishing models Methods Cmplname Description Constructor Parameter str name filename of the CMPL model Return Cmpl object CMPL v112 Manual 126 CmplsetSetsset1set2 Description Committing CmplSet objects to the Cmpl model Parameter CmplSet set1set2 CmplSet objects Return CmplsetParameterspar1par2 Description Committing CmplParameter objects to the Cmpl model Parameter CmplParameter par1par2 CmplParameter objects Return Examples m Cmplprodmixcmpl products CmplSetproducts productssetValues13 machines CmplSetmachines machinessetValues12 c CmplParametercproducts csetValues758050 b CmplParameterbmachines bsetValues10001000 a CmplParameteramachines products asetValues 8151215108 msetSetsproductsmachines msetParameterscab Commits the sets products machines to the Cmpl object m Commits the parameter cab to the Cmpl ob ject m CMPL v112 Manual 127 4332 Manipulating models Methods CmplsetOptionoption Description Sets a CMPL display or solver option Parameter str option option in CmplHeader syntax Return int option id CmpldelOptionoptId Description Deletes an option Parameter int optId option id Return CmpldelOptions Description Deletes all options Parameter Return CmplsetOutputokleadString Description Turns the output of CMPL and the invoked solver on or off Parameter bool ok TrueFalse str leadString optional Leading string for the output default model name Return CmplsetRefreshTimerTime Description Refresh time for getting the output of CMPL and the invoked solver from a CM PLServer if the model is solved synchronously Parameter float rTime refresh time in seconds default 05 Return Ro attributes CmplrefreshTime Description Returns the refresh time for getting the output of CMPL and the invoked solver from a CMPLServer if the model is solved synchronously Return float Refresh time CMPL v112 Manual 128 Examples m Cmplassignmentcmpl c1msetOptiondisplay nonZeros msetOptionarg solver cplex msetOptiondisplay solutionPool mdelOptionc1 mdelOptions Setting some options Deletes the first option Deletes all options m Cmplassignmentcmpl msetOutputTrue msetOutputTruemy special model The stdOut and stdErr of CMPL and the invoked solver are shown for the Cmpl object m As above but the output starts with the leading string my special model m Cmplassignmentcmpl mconnecthttp1949545708008 msetOutputTrue msetRefreshTime1 The stdOut and stdErr of CMPL and the invoked solver located at the specified CMPLServer will be refreshed every second 4333 Solving models Methods Cmplsolve Description Solves a Cmpl model either with a local installed CMPL or if the model is connected with a CMPLServer remotely Parameter Return status of the model and the solver can be obtained by the at tributes cmplStatus cmplStatusTextsolverStatus and solverStatusText Cmplstart Description Solves a Cmpl model in a separate thread either with a local installed CMPL or if the model is connected with a CMPLServer remotely Parameter Return status of the model and the solver can be obtained by the at tributes cmplStatus cmplStatusTextsolverStatus and solverStatusText CMPL v112 Manual 129 Cmpljoin Description Waits until the solving thread terminates Parameter Return status of the model and the solver can be obtained by the at tributes cmplStatus cmplStatusTextsolverStatus and solverStatusText CmplisAlive Description Return whether the thread is alive Parameter Return bool True or False return whether the thread is alive or not CmplconnectcmplUrl Description Connects a CMPLServer or CMPLGridScheduler under cmplUrl first step of solv ing a model on a CMPLServer remotely Parameter str cmplUrl URL of the CMPLServer or CMPLGridScheduler Return Cmpldisconnect Description Disconnects the connected CMPLServer or CMPLGridScheduler Parameter Return Cmplsend Description Sends the Cmpl model instance to the connected CMPLServer first step of solving a model on a CMPLServer asynchronously after connect Parameter Return status of the model can be obtained by the attributes cmplStatus and cmplStatusText Cmplknock Description Knocks on the door of the connected CMPLServer or CMPLGridScheduler and asks whether the model is finished second step of solving a model on a CMPLServer asynchronously Parameter Return status of the model can be obtained by the attributes cmplStatus and cmplStatusText CMPL v112 Manual 130 Cmplretrieve Description Retrieves the Cmpl solutions if possible from the connected CMPLServer last step of solving a model on a CMPLServer asynchronously Parameter Return status of the model and the solver can be obtained by the at tributes cmplStatus cmplStatusTextsolverStatus and solverStatusText Cmplcancel Description Cancels the Cmpl solving process on the connected CMPLServer Parameter Return status of the model can be obtained by the attributes cmplStatus and cmplStatusText Ro attributes CmplcmplStatus Description Returns the CMPL related status of the Cmpl object Return int CMPLUNKNOWN 0 CMPLOK 1 CMPLWARNINGS 2 CMPLFAILED 3 CMPLSERVEROK 6 CMPLSERVERERROR 7 CMPLSERVERBUSY 8 CMPLSERVERCLEANED 9 CMPLSERVERWARNING 10 PROBLEMRUNNING 11 PROBLEMFINISHED 12 PROBLEMCANCELED 13 PROBLEMNOTRUNNING 14 CMPLGRIDSCHEDULERUNKNOWN 15 CMPLGRIDSCHEDULEROK 16 CMPLGRIDSCHEDULERERROR 17 CMPLGRIDSCHEDULERBUSY 18 CMPLGRIDSCHEDULERSOLVERNOTAVAILABLE 19 CMPLGRIDSCHEDULERWARNING 20 CMPLGRIDSCHEDULERPROBLEMDELETED 21 CMPL v112 Manual 131 CmplcmplStatusText Description Returns the CMPL related status text of the Cmpl object Return str CMPLUNKNOWN CMPLOK CMPLWARNINGS CMPLFAILED CMPLSERVEROK CMPLSERVERERROR CMPLSERVERBUSY CMPLSERVERCLEANED CMPLSERVERWARNING PROBLEMRUNNING PROBLEMFINISHED PROBLEMCANCELED PROBLEMNOTRUNNING CMPLGRIDSCHEDULERUNKNOWN CMPLGRIDSCHEDULEROK CMPLGRIDSCHEDULERERROR CMPLGRIDSCHEDULERBUSY CMPLGRIDSCHEDULERSOLVERNOTAVAILABLE CMPLGRIDSCHEDULERWARNING CMPLGRIDSCHEDULERPROBLEMDELETED CmplsolverStatus Description Returns the solver related status of the Cmpl object Return int SOLVEROK 4 SOLVERFAILED 5 CmplsolverStatusText Description Returns the solver related status text of the Cmpl object Return str SOLVEROK SOLVERFAILED CmpljobId Description Returns the jobId of the Cmpl problem at the connected CMPLServer Return str string of the jobId Cmploutput Description Returns the output of CMPL and the invoked solver Intended to use if an application needs to parse the output Return str string of output of CMPL and the invoked solver CMPL v112 Manual 132 Examples m Cmplassignmentcmpl msolve Solves the Cmpl object m locally m Cmplassignmentcmpl mconnecthttp1949545708008 msolve Solves the Cmpl object m remotely and syn chronously on the specified CMPLServer m Cmplassignmentcmpl mconnecthttp1949545708008 msend mknock mretrieve Solves the Cmpl object m remotely and asyn chronously on the specified CMPLServer models modelsappendCmplm1cmpl modelsappendCmplm2cmpl modelsappendCmplm3cmpl for m in models mstart for m in models mjoin Starts all models in separate threads Waits until the all solving threads are terminated m Cmplassignmentcmpl msolve if msolverstatusSOLVEROK msolutionReport Displays the optimal solution if the solver didnt fail 4334 Reading solutions Methods CmplsolutionReport Description Writes a standard solution report to stdOut Parameter Return CmplsaveSolutionsolFileName Description Saves the solutions as CmplSolutions file Parameter str solFileName optional file name default modelnamecsol Return CMPL v112 Manual 133 CmplsaveSolutionAsciisolFileName Description Saves the solutions as ASCII file Parameter str solFileName optional file name default modelnamesol Return CmplsaveSolutionCsvsolFileName Description Saves the solutions as CSV file Parameter str solFileName optional file name default modelnamecsv Return CmplvarByNamesolIdx Description Enables a direct access to variables by their name Parameter int solIdx optional solution index default 0 Return CmplconByNamesolIdx Description Enables a direct access to constraints by their name Parameter int solIdx optional solution index default 0 Return CmplgetVarByNamename solIdx Description Returns a CmplSolElement object or a list of CmplSolElement objects for the variable or variable array with the specified name Parameter str name int solIdx name of the variable or variable array optional solution index default 0 Return CmplSolElement list of CmplSolElement for a single variable for a variable array CmplgetConByNamesolIdx Description Returns a CmplSolElement object or a list of CmplSolElement objects for the constraint or constraint array with the specified name Parameter str name int solIdx name of the constraint or constraint array optional solution index default 0 Return CmplSolElement list of CmplSolElement for a single constraint for a constraint array CMPL v112 Manual 134 Ro attributes CmplnrOfVariables Description Returns the number of variables of the generated and solved CMPL model Return int number of variables CmplnrOfConstraints Description Returns the number of constraints of the generated and solved CMPL model Return int number of constraints CmplobjectiveName Description Returns the name of the objective function of the generated and solved CMPL model Return str objective name CmplobjectiveSense Description Returns the objective sense of the generated and solved CMPL model Return str objective sense CmplnrOfSolutions Description Returns the number of solutions of the generated and solved CMPL model Return int number of solutions Cmplsolver Description Returns the name of the invoked solver of the generated and solved CMPL model Return str invoked solver CmplsolverMessage Description Returns the message of the invoked solver of the generated and solved CMPL model Return str message of the invoked solver CmplvarDisplayOptions Description Returns a string with the display options for the variables of the generated and solved CMPL model Return str display options for the variables CmplconDisplayOptions Description Returns a string with the display options for the constraints of the generated and solved CMPL model Return str display options for the constraints CMPL v112 Manual 135 Cmplsolution Description Returns the first optimal CmplSolutions object Return CmplSolutions first optimal solution CmplsolutionPool Description Returns a list of CmplSolutions objects Return list of CmplSolu tions objects list of CmplSolution object for solutions found CmplSolutionsstatus Description Returns a string with the status of the current solution provided by the invoked solver Return str solution status CmplSolutionsvalue Description Returns the value of the objective function of the current solution Return float objective function value CmplSolutionsidx Description Returns the index of the current solution Return int index of the current solution CmplSolutionsvariables Description Returns a list of CmplSolElement objects for the variables of the current solution Return list of CmplSol Line objects list of variables CmplSolutionsconstraints Description Returns a list of CmplSolElement objects for the constraints of the current solution Return list of CmplSolElement objects list of constraints CmplSolElementidx Description Index of the variable or constraint Return int index of the variable or constraint CmplSolElementname Description Name of the variable or constraint Return str name of the variable or constraint CMPL v112 Manual 136 CmplSolElementtype Description Type of the variable or constraint Return str type of the variable or constraint CIB for variables LEG for constraints CmplSolElementactivity Description Activity of the variable or constraint Return longfloat activity of the variable or constraint CmplSolElementlowerBound Description Lower bound of the variable or constraint Return float lower bound of the variable or constraint CmplSolElementupperBound Description Upper bound of the variable or constraint Return float upper bound of the variable or constraint CmplSolElementmarginal Description Marginal value shadow prices or reduced costs bound of the variable or constraint Return float marginal value of the variable or constraint Examples m Cmplassignmentcmpl msolve print msolver print msolverMessage print mnrOfVariables print mnrOfConstraints print mvarDisplayOptions print mconDisplayOptions print mobjectiveName print mobjectiveSense print msolutionvalue print msolutionstatus print mnrOfSolutions print msolutionidx Solves the example from subchapter 41 and displays some information about the gener ated and solved model CBC 11 7 all all costs min 290 optimal 1 0 CMPL v112 Manual 137 for v in msolutionvariables print vidxvname vtype vactivityvlowerBound vupperBound for c in msolutionconstraints print cidx cname ctype cactivityclowerBound cupperBound Displays all information about variables and constraints of the optimal solution Variables 0 x11 B 00 00 10 1 x12 B 00 00 10 2 x13 B 00 00 10 3 x14 B 10 00 10 4 x21 B 00 00 10 5 x23 B 10 00 10 6 x24 B 00 00 10 7 x31 B 10 00 10 8 x32 B 00 00 10 9 x33 B 00 00 10 10 x34 B 00 00 10 Constraints 0 sosm1 E 10 10 10 1 sosm2 E 10 10 10 2 sosm3 E 10 10 10 3 sosl1 L 10 inf 10 4 sosl2 L 00 inf 10 5 sosl3 L 10 inf 10 6 sosl4 L 10 inf 10 m Cmplassignmentcmpl msetOptiondisplay nonZeros msetOptionarg solver cplex msetOptiondisplay solutionPool msolve for s in msolutionPool print Solution number sidx1 print Objective value svalue print Objective status sstatus print Variables for v in svariables print vidxvname vtype vactivityvlowerBound vupperBound print Constraints Solves the example from subchapter 41 and displays all information about variables and constraints of all solutions found Solution number 1 Objective value 290 Objective status integer optimal solution Variables 3 x14 B 10 00 10 5 x23 B 10 00 10 7 x31 B 10 00 10 Constraints CMPL v112 Manual 138 for c in sconstraints print cidxcnamectype cactivityclowerBound cupperBound 0 sosm1 E 10 10 10 1 sosm2 E 10 10 10 2 sosm3 E 10 10 10 3 sosl1 L 10 inf 10 5 sosl3 L 10 inf 10 6 sosl4 L 10 inf 10 Solution number 2 Objective value 290 Objective statusinteger feasible solution for s in msolutionPool mvarByNamesidx mconByNamesidx print Variables for c in combinationsvalues print mxcnamemxctype mxcactivity mxclowerBound mxcupperBound print Constraints for i in msosm print msosminame msosmitype msosmiactivity msosmilowerBound msosmiupperBound for j in msosl print msosljname msosljtype msosljactivity msosljlowerBound msosljupperBound As above but with direct access to the vari able and constraint names Enables the direct access to the variable and constraint names of the current solution Iterates the variables xij over the value list of the CmplSet object combinations Iterates over the internal list of the indexing entries of the constraints with the name sosm Iterates over the internal list of the indexing entries of the constraints with the name sosl v modelgetVarByNamex c modelgetConByNameline v is assigned a list of CmplSolution objects for the variable array with the name x c is assigned a list of CmplSolution objects for the constraint array with the name line CMPL v112 Manual 139 for x in v print xname xtype xactivity xlowerBoundxupperBound xmarginal for x in c print xname xtype xactivity xlowerBoundxupperBound xmarginal Iterates over the list of CmplSolution ob jects for the variable array with the name x Iterates over the list of CmplSolution ob jects for the constrains array with the name line 4335 Reading CMPL messages Ro attributes CmplcmplMessages Description Returns a list of CmplMsg objects that contain the CMPL messages Return list of CmplMsg objects list of CMPL messages CmplMsgtype Description Returns the type of the messages Return str message type warningerror CmplMsgfile Description Returns the name of the CMPL file in that the error or warning occurs Return str CMPL file name or CmplData file name CmplMsgline Description Returns the line in the CMPL file in that the error or warning occurs Return str line number CmplMsgdescription Description Returns a description of the error or warning message Return str description of the error or warning Examples model Cmpldietcmpl modelsolve if modelcmplStatusCMPLWARNINGS for m in modelcmplMessages print mtype mfile If some warnings for the CMPL model dietcmpl appear the messages will be shown CMPL v112 Manual 140 mline mdescription 434 CmplExceptions pyCMPL provides its own exception handling If an error occurs either by using pyCmpl classes or in the CMPL model a CmplException is raised by pyCmpl automatically This exception can be handled through using a tryexcept block try do something except CmplException e print emsg 44 jCMPL reference manual To use the jCMPL functionalities a Java programme has to import jCMPL by import jCMPL and to link your application against jCmpljar and the following jar files that you can find in the CMPL applicatiopn folder in jCmplLibs commonslang3 wscommonsutil xmplrpcclient xmlrpccom mons 441 CmplSets The class CmplSet is intended to define sets that can be used with several Cmpl objects Setter methods CmplSetsetNamerank Description Constructor Parameter String setName name of the set Has to be equal to the corresponding name in the CMPL model int rank optional rank n for a ntuple set default 1 Return CmplSet object CmplSetsetValuessetList Description Defines the values of an enumeration set Parameter Object setList for a set of ntuples with n1 ListArray of single index ing entries intIntegerlongLongString for a set of ntuples with n1 2dimensional ListArray that contain intIntegerlongLongString tuples Return CMPL v112 Manual 141 CmplSetsetValuesstartNumberendNumber Description Defines the values of an algorithmic set startNumber startNumber1 endNumber Parameter int startNumber start value of the set int endNumber end value of the set Return CmplSetsetValuesstartNumberstependNumber Description Defines the values of an algorithmic set startNumber startNumberstep endNumber Parameter int startNumber start value of the set int step positive value for increment negative value for decrement int endNumber end value of the set Return Getter methods CmplSetvalues Description List of the indexing entries of the set Return List Array of Object onedimensional List or Array of single intInteger longLongString for a set of ntuples with n1 twodimensional List or Array of intIntegerlong LongString for a set of ntuples with n1 CmplSetname Description Name of the set Return String name of the CMPL set not the name of the CmplSet object CmplSetrank Description Rank of the set Return int number of n of a ntuple set CmplSetlen Description Length of the set Return int number of indexing entries Examples CmplSet s new CmplSets ssetValues04 s is assigned s01 4 CMPL v112 Manual 142 Systemoutprintln srank Systemoutprintln slen Systemoutprintln sname Systemoutprintln svalues 1 5 s 0 1 2 3 4 CmplSet s new CmplSeta ssetValues1020 Systemoutprintln srank Systemoutprintln slen Systemoutprintln sname Systemoutprintln svalues s is assigned s108 0 1 6 a 10 8 6 4 2 0 CmplSet s new CmplSetFOOD Sring sVals BEEFCHKFISH ssetValuessVals Systemoutprintln srank Systemoutprintln slen Systemoutprintln sname for String e String svalues Systemoutprintln e s is assigned s BEEF CHK FISH 1 3 FOOD BEEF CHK FISH CmplSet s new CmplSetFOOD ArrayList nutrLst new ArrayListString nutrLstaddBEEF nutrLstaddCHK nutrLstaddFISH ssetValuesnutrLst Systemoutprintln srank Systemoutprintln slen Systemoutprintln sname Systemoutprintln svalues s is assigned s BEEF CHK FISH 1 3 FOOD BEEF CHK FISH CmplSet s new CmplSetc3 int sVals 111 112 121 ssetValuessVals s is assigned a 3tuple set of integers CMPL v112 Manual 143 Systemoutprintln srank Systemoutprintln slen Systemoutprintln sname for int i0 islen i for int j0 jsrank j Systemoutprint sgetij Systemoutprint 3 3 c 111 112 121 442 CmplParameters The class CmplParameters is intended to define parameters that can be used with several Cmpl objects Setter methods CmplParameterparamNameset1set2 Description Constructor Parameter String paramName name of the parameter Has to be equal to the corresponding name in the CMPL model CmplSet set1set2 optional set or sets through which the parameter array is defined default None Return CmplParameter object CmplParametersetValuesval Description Defines the values of a scalar parameter Parameter intInteger longLongfloat Floatdouble DoubleString val value of the scalar parameter Return CmplParametersetValuesvals Description Defines the values of a parameter array Parameter Object vals one our multidimensional ListArray of intInteger longLongfloatFloatdoubleDoubleString Return CMPL v112 Manual 144 Getter methods CmplParametervalues Description List of the values of a parameter Return Object one our multidimensional ListArray of intIntegerlong LongfloatFloatdoubleDoubleString value list of the parameter array CmplParametervalue Description Value of a scalar parameter Return intIntegerlongLongfloatFloatdoubleDoubleString value of the scalar parameter CmplParametersetList Description List of sets through which the parameter array is defined Return list of CmplSet objects through which the parameter array is defined CmplParametername Description Name of the parameter Return String name of the CMPL parameter not the name of the CmplParameter ob ject CmplParameterrank Description Rank of the parameter Return int rank of the CMPL parameter CmplParameterlen Description Length of the parameter array Return long number of elements in the parameter array Examples CmplParameter p new CmplParameterp psetValues2 Systemoutprintln pvalues Systemoutprintln pvalue Systemoutprintln pname Systemoutprintln prank Systemoutprintln plen p is assigned 2 2 2 p 0 1 CmplSet s new CmplSets ssetValues04 CMPL v112 Manual 145 CmplParameter p new CmplParameterps int pVals 12345 psetValuespVals for int val intpvalues Systemoutprintlnval Systemoutprintln pname Systemoutprintln prank Systemoutprintln plen p is assigned 12 5 1 2 3 4 5 p 1 5 CmplSet products new CmplSetproducts productssetValues13 CmplSet machines new CmplSetmachines machinessetValues12 CmplParameter a new CmplParameteramachinesproducts int aVals 81512 15108 asetValuesaVals for int i0 imachineslen i for int j0 jproductslen j Systemoutprint intavaluesij Systemoutprintln Systemoutprintln aname Systemoutprintln arank Systemoutprintln alen for CmplSet s asetList Systemoutprintln svalues a is assigned a 2X3 matrix of integers 8 15 12 15 10 8 a 2 6 1 2 1 2 3 CmplSet s new CmplSets2 int sVals 11 22 ssetValuessVals CmplParameter p new CmplParameterps int pVals 1 1 psetValuespVals s is assigned the indices of a matrix diagonal s is assigned a 2x2 identity matrix CMPL v112 Manual 146 for int val intpvalues Systemoutprintlnval Systemoutprintln aname Systemoutprintln arank Systemoutprintln alen 1 1 p 2 2 443 Cmpl With the Cmpl class it is possible to define a CMPL model to commit sets and parameters to this model to start and control the solving process and to read the CMPL and solver messages and to have access to the solutions via CmplMessages and CmplSolutions objects 4431 Establishing models Setter methods Cmplname Description Constructor Parameter String name filename of the CMPL model Return Cmpl object CmplsetSetsset1set2 Description Committing CmplSet objects to the Cmpl model Parameter CmplSet set1set2 CmplSet objects Return CmplsetParameterspar1par2 Description Committing CmplParameter objects to the Cmpl model Parameter CmplParameter par1par2 CmplParameter objects Return Examples Cmpl m new Cmplprodmixcmpl CmplSet products new CmplSetproducts productssetValues13 CMPL v112 Manual 147 mplSet machines new CmplSetmachines machinessetValues12 CmplParameter c new CmplParametercproducts int cVals 758050 csetValuescVals CmplParameter b new CmplParameterbmachines int bVals 10001000 bsetValuesbVals CmplParameter a new CmplParameteramachinesproducts int aVals 81512 15108 asetValuesaVals msetSetsproductsmachines msetParameterscab Commits the sets productsmachines to the Cmpl object m Commits the parameter cab to the Cmpl object m 4432 Manipulating models Setter methods CmplsetOptionoption Description Sets a CMPL display or solver option Parameter String option option in CmplHeader syntax Return int option id CmpldelOptionoptId Description Deletes an option Parameter Int optId option id Return CMPL v112 Manual 148 CmpldelOptions Description Deletes all options Parameter Return CmplsetOutputokleadStr Description Turns the output of CMPL and the invoked solver on or off Parameter boolean ok truefalse String leadStr optional Leading string for the output default model name Return CmplsetRefreshTimerTime Description Refresh time for getting the output of CMPL and the invoked solver from a CM PLServer if the model is solved synchronously Parameter long rTime refresh time in milliseconds default 400 Return Getter methods CmplrefreshTime Description Returns the refresh time for getting the output of CMPL and the invoked solver from a CMPLServer if the model is solved synchronously Return long Refresh time in milliseconds Examples Cmpl m new Cmplassignmentcmpl long c1msetOptiondisplay nonZeros msetOptionarg solver cplex msetOptiondisplay solutionPool mdelOptionc1 mdelOptions Setting some options Deletes the first option Deletes all options Cmpl m new Cmplassignmentcmpl msetOutputTrue msetOutputTruemy special model The stdOut and stdErr of CMPL and the invoked solver are shown for the Cmpl object m As above but the output starts with the leading string my special model CMPL v112 Manual 149 Cmpl m new Cmplassignmentcmpl mconnecthttp1949545708008 msetOutputTrue msetRefreshTime500 The stdOut and stdErr of CMPL and the in voked solver located at the specified CMPLServer will be refreshed every 500 millisecond 4433 Solving models Setter Methods Cmplsolve Description Solves a Cmpl model either with a local installed CMPL or if the model is connected with a CMPLServer remotely Parameter Return status of the model and the solver can be obtained by the methods cmplStatus cmplStatusTextsolverStatus and solverStatusText Cmplstart Description Solves a Cmpl model in a separate thread either with a local installed CMPL or if the model is connected with a CMPLServer remotely Parameter Return status of the model and the solver can be obtained by the methods cmplStatus cmplStatusTextsolverStatus and solverStatusText Cmpljoin Description Waits until the solving thread terminates Parameter Return status of the model and the solver can be obtained by the methods cmplStatus cmplStatusTextsolverStatus and solverStatusText CmplisAlive Description Return whether the thread is alive Parameter Return boolean true or false return whether the thread is alive or not CmplconnectcmplUrl Description Connects a CMPLServer or CMPLGridScheduler under cmplUrl first step of solv ing a model on a CMPLServer remotely CMPL v112 Manual 150 Parameter String cmplUrl URL of the CMPLServer or CMPLGridScheduler Return Cmpldisconnect Description Disconnects the connected CMPLServer or CMPLGridScheduler Parameter Return Cmplsend Description Sends the Cmpl model instance to the connected CMPLServer first step of solving a model on a CMPLServer asynchronously after connect Parameter Return status of the model can be obtained by the methods cm plStatus and cmplStatusText Cmplknock Description Knocks on the door of the connected CMPLServer or CMPLGridScheduler and asks whether the model is finished second step of solving a model on a CMPLServer asynchronously Parameter Return status of the model can be obtained by the methods cmplStatus and cmplStatusText Cmplretrieve Description Retrieves the Cmpl solutions if possible from the connected CMPLServer last step of solving a model on a CMPLServer asynchronously Parameter Return status of the model and the solver can be obtained by the methods cmplStatus cmplStatusTextsolverStatus and solverStatusText Cmplcancel Description Cancels the Cmpl solving process on the connected CMPLServer Parameter Return status of the model can be obtained by the methods cmplStatus and cmplStatusText CMPL v112 Manual 151 Getter methods CmplcmplStatus Description Returns the CMPL related status of the Cmpl object Return int CMPLUNKNOWN 0 CMPLOK 1 CMPLWARNINGS 2 CMPLFAILED 3 CMPLSERVEROK 6 CMPLSERVERERROR 7 CMPLSERVERBUSY 8 CMPLSERVERCLEANED 9 CMPLSERVERWARNING 10 PROBLEMRUNNING 11 PROBLEMFINISHED 12 PROBLEMCANCELED 13 PROBLEMNOTRUNNING 14 CMPLGRIDSCHEDULERUNKNOWN 15 CMPLGRIDSCHEDULEROK 16 CMPLGRIDSCHEDULERERROR 17 CMPLGRIDSCHEDULERBUSY 18 CMPLGRIDSCHEDULERSOLVERNOTAVAILABLE 19 CMPLGRIDSCHEDULERWARNING 20 CMPLGRIDSCHEDULERPROBLEMDELETED 21 CmplcmplStatusText Description Returns the CMPL related status text of the Cmpl object Return String CMPLUNKNOWN CMPLOK CMPLWARNINGS CMPLFAILED CMPLSERVEROK CMPLSERVERERROR CMPLSERVERBUSY CMPLSERVERCLEANED CMPLSERVERWARNING PROBLEMRUNNING PROBLEMFINISHED PROBLEMCANCELED PROBLEMNOTRUNNING CMPLGRIDSCHEDULERUNKNOWN CMPLGRIDSCHEDULEROK CMPLGRIDSCHEDULERERROR CMPLGRIDSCHEDULERBUSY CMPLGRIDSCHEDULERSOLVERNOTAVAILABLE CMPL v112 Manual 152 CMPLGRIDSCHEDULERWARNING CMPLGRIDSCHEDULERPROBLEMDELETED CmplsolverStatus Description Returns the solver related status of the Cmpl object Return int SOLVEROK 4 SOLVERFAILED 5 CmplsolverStatusText Description Returns the solver related status text of the Cmpl object Return String SOLVEROK SOLVERFAILED CmpljobId Description Returns the jobId of the Cmpl problem at the connected CMPLServer Return String string of the jobId Cmploutput Description Returns the output of CMPL and the invoked solver Intended to use if an application needs to parse the output Return String string of output of CMPL and the invoked solver Examples Cmpl m new Cmplassignmentcmpl msolve Solves the Cmpl object m locally Cmpl m new Cmplassignmentcmpl mconnecthttp1949545708008 msolve Solves the Cmpl object m remotely and syn chronously on the specified CMPLServer Cmpl m new Cmplassignmentcmpl mconnecthttp1949545708008 msend mknock mretrieve Solves the Cmpl object m remotely and asyn chronously on the specified CMPLServer ArrayListCmpl models new ArrayListCmpl modelsaddnew Cmplm1cmpl modelsaddnew Cmplm2cmpl modelsaddnew Cmplm3cmpl for Cmpl c models cstart Starts all models in separate threads CMPL v112 Manual 153 for Cmpl c models cjoin Waits until the all solving threads are terminated Cmpl m new Cmplassignmentcmpl msolve if msolverStatus CmplSOLVEROK msolutionReport Displays the optimal solution if the solver didnt fail 4434 Reading solutions Setter methods CmplsolutionReport Description Writes a standard solution report to stdOut Parameter Return CmplsaveSolutionsolFileName Description Saves the solutions as CmplSolutions file Parameter String solFile Name optional file name default modelnamecsol Return CmplsaveSolutionAsciisolFileName Description Saves the solutions as ASCII file Parameter String solFile Name optional file name default modelnamesol Return CmplsaveSolutionCsvsolFileName Description Saves the solutions as CSV file Parameter String solFile Name optional file name default modelnamecsv Return Getter methods CmplnrOfVariables Description Returns the number of variables of the generated and solved CMPL model Return long number of variables CMPL v112 Manual 154 CmplnrOfConstraints Description Returns the number of constraints of the generated and solved CMPL model Return long number of constraints CmplobjectiveName Description Returns the name of the objective function of the generated and solved CMPL model Return String objective name CmplobjectiveSense Description Returns the objective sense of the generated and solved CMPL model Return String objective sense CmplnrOfSolutions Description Returns the number of solutions of the generated and solved CMPL model Return int number of solutions Cmplsolver Description Returns the name of the invoked solver of the generated and solved CMPL model Return String invoked solver CmplsolverMessage Description Returns the message of the invoked solver of the generated and solved CMPL model Return String message of the invoked solver CmplvarDisplayOptions Description Returns a string with the display options for the variables of the generated and solved CMPL model Return String display options for the variables CmplconDisplayOptions Description Returns a string with the display options for the constraints of the generated and solved CMPL model Return String display options for the constraints Cmplsolution Description Returns the first optimal CmplSolutions object Return CmplSolutions first optimal solution CMPL v112 Manual 155 CmplsolutionPool Description Returns a list of CmplSolutions objects Return List of CmplSolu tions objects list of CmplSolution object for solutions found CmplSolutionsstatus Description Returns a string with the status of the current solution provided by the invoked solver Return String solution status CmplSolutionsvalue Description Returns the value of the objective function of the current solution Return double objective function value CmplSolutionsidx Description Returns the index of the current solution Return int index of the current solution CmplSolutionsvariables Description Returns a list of CmplSolElement objects for the variables of the current solution Return ArrayListCm plSolElement list of variables CmplSolutionsconstraints Description Returns a list of CmplSolElement objects for the constraints of the current solution Return ArrayListCm plSolElement list of constraints CmplgetVarByNamename solIdx Description Returns a CmplSolElement object or CmplSolArray of CmplSolElement ob jects for the variable or variable array with the specified name Parameter String name int solIdx name of the variable or variable array optional solution index default 0 Return Object CmplSolElement for a single variable CmplSolArray for a variable array CmplgetConByNamesolIdx Description Returns a CmplSolElement object or CmplSolArray of CmplSolElement ob jects for the constraint or constraint array with the specified name Parameter String name int solIdx name of the constraint or constraint array optional solution index default 0 CMPL v112 Manual 156 Return Object CmplSolElement for a single constraint CmplSolArray for a constraint array CmplSolElementidx Description Index of the variable or constraint Return int index of the variable or constraint CmplSolElementname Description Name of the variable or constraint Return String name of the variable or constraint CmplSolElementtype Description Type of the variable or constraint Return String type of the variable or constraint CIB for variables LEG for constraints CmplSolElementactivity Description Activity of the variable or constraint Return Object DoubleLong Activity of the variable or constraint CmplSolElementlowerBound Description Lower bound of the variable or constraint Return double lower bound of the variable or constraint CmplSolElementupperBound Description Upper bound of the variable or constraint Return double upper bound of the variable or constraint CmplSolElementmarginal Description Marginal value shadow prices or reduced costs bound of the variable or constraint Return double marginal value of the variable or constraint Examples Cmpl m new Cmplassignmentcmpl msolve Systemoutprintfs msolver Systemoutprintfs msolverMessage Solves the example from subchapter 41 and displays some information about the generated and solved model CBC CMPL v112 Manual 157 Systemoutprintfd mnrOfVariables Systemoutprintfd mnrOfConstraints Systemoutprintfs mvarDisplayOptions Systemoutprintfs mconDisplayOptions Systemoutprintfs mobjectiveName Systemoutprintfs mobjectiveSense Systemoutprintff msolutionvalue Systemoutprintfs msolutionstatus Systemoutprintfd mnrOfSolutions Systemoutprintfd msolutionidx 11 7 all all costs min 29000000 optimal 1 0 for CmplSolElement v msolutionvariables Systemoutprintf8s 2s 2d 20f 20fn vname vtypevactivity vlowerBoundvupperBound for CmplSolElement cmsolutionconstraints Systemoutprintf8s 2s 20f 20f 20f n cname ctypecactivity clowerBoundcupperBound Displays all information about vari ables and constraints of the optimal solution Variables x11 B 0 0 1 x12 B 0 0 1 x13 B 0 0 1 x14 B 1 0 1 x21 B 0 0 1 x23 B 1 0 1 x24 B 0 0 1 x31 B 1 0 1 x32 B 0 0 1 x33 B 0 0 1 x34 B 0 0 1 Constraints sosm1 E 1 1 1 sosm2 E 1 1 1 sosm3 E 1 1 1 sosl1 L 1 Infinity 1 sosl2 L 0 Infinity 1 sosl3 L 1 Infinity 1 sosl4 L 1 Infinity 1 CmplSolArray x CmplSolArray mgetVarByNamex forint tuple int combinationsvalues Systemoutprintf5s 2d n xgettuplename xgettupleactivity Direct access to the variable vector x by its name Cmpl m new Cmplassignmentcmpl msetOptiondisplay nonZeros msetOptionarg solver cplex Solves the example from subchapter 41 and displays all information about variables and constraints of all solu CMPL v112 Manual 158 msetOptiondisplay solutionPool msolve for CmplSolution s msolutionPool SystemoutprintfSolution number d n sidx 1 SystemoutprintfObjective value f n svalue SystemoutprintfObjective status s n sstatus SystemoutprintlnVariables for CmplSolElement v svariables Systemoutprintf8s 2s 2d 20f 20f n vname vtype vactivity vlowerBound vupperBound SystemoutprintlnConstraints for CmplSolElement c sconstraints Systemoutprintf8s 2s 20f 20f 20f n cname ctype cactivity clowerBound cupperBound tion found Solution number 1 Objective value 29000000 Objective status integer optimal solution Variables x14 B 1 0 1 x23 B 1 0 1 x31 B 1 0 1 Constraints sosm1 E 1 1 1 sosm2 E 1 1 1 sosm3 E 1 1 1 sosl1 L 1 Infinity 1 sosl3 L 1 Infinity 1 sosl4 L 1 Infinity 1 Solution number 2 Objective value 29000000 Objective status integer feasible solution Variables x14 B 1 0 1 4435 Reading CMPL messages Getter methods CmplcmplMessages Description Returns a list of CmplMsg objects that contain the CMPL messages Return ArrayList CmplMsg list of CMPL messages CmplMsgtype Description Returns the type of the messages Return String message type warningerror CMPL v112 Manual 159 CmplMsgfile Description Returns the name of the CMPL file in that the error or warning occurs Return String CMPL file name or CmplData file name CmplMsgline Description Returns the line in the CMPL file in that the error or warning occurs Return String line number CmplMsgdescription Description Returns the a description of the error or warning message Return String description of the error or warning Examples model Cmpldietcmpl modelsolve if modelcmplStatusCmplCMPLWARNINGS for CmplMsg m modelcmplMessages Systemoutprintfs s s s s mtype mfile mline mdescription If some warnings for the CMPL model dietcmpl appear the messages will be shown 444 CmplExceptions jCMPL provides its own exception handling If an error occurs either by using jCmpl classes or in the CMPL model a CmplException is raised by jCmpl automatically This exception can be handled through using a trycatch block try do something catch CmplException e Systemoutprintlne CMPL v112 Manual 160 45 Examples 451 The diet problem 4511 Problem description and CMPL model In this subchapter the jCMPL and jCMPL formulation of the diet problem already discussed in subchapter 2811 is dealt with The first step is to formulate the CMPL model dietcmpl where the sets and parameters that are created in the pyCmpl script have to be specified in the CMPL header entry data data NUTR set FOOD set costsFOOD vitaminNUTRFOOD vitMinNUTR variables xFOOD integer210 objectives cost costsT xmin constraints 2 vitamin x vitMin 4512 pyCMPL The corresponding pyCMPL script dietpy is formulated as follows usrbinpython from pyCmpl import try model Cmpldietcmpl nutr CmplSetNUTR nutrsetValuesA B1 B2 C food CmplSetFOOD foodsetValuesBEEFCHKFISHHAMMCHMTLSPGTUR costs CmplParametercostsfood costssetValues319 259 229 289 189 199 199 249 vitmin CmplParametervitMinnutr vitminsetValues 700 700 700 700 vitamin CmplParametervitaminnutr food CMPL v112 Manual 161 vitaminsetValues 60884015702560 200104035305020 1020153515152515 1520101015151510 modelsetSetsnutrfood modelsetParameterscostsvitminvitamin modelsolve modelsolutionReport except CmplException e print emsg Executing this pyCMPL model by using the command pyCmpl dietpy leads to the following output created by pyCMPLs standard solution report Problem dietcmpl Nr of variables 8 Nr of constraints 4 Objective name cost Solver name CBC Display variables all Display constraints all Objective status optimal Objective value 10114 min Variables Name Type Activity LowerBound UpperBound Marginal xBEEF I 2 200 1000 xCHK I 8 200 1000 xFISH I 2 200 1000 xHAM I 2 200 1000 xMCH I 10 200 1000 xMTL I 10 200 1000 xSPG I 10 200 1000 xTUR I 2 200 1000 Constraints Name Type Activity LowerBound UpperBound Marginal lineA G 150000 70000 inf lineB1 G 133000 70000 inf lineB2 G 86000 70000 inf lineC G 70000 70000 inf CMPL v112 Manual 162 4513 jCmpl The corresponding jCMPL programme dietjava is formulated as follows import jCMPL public class Diet public static void mainString args throws CmplException try Cmpl model new Cmpldietcmpl CmplSet nutr new CmplSetNUTR String nutrLst A B1 B2 C nutrsetValuesnutrLst CmplSet food new CmplSetFOOD String foodLst BEEF CHK FISH HAM MCH MTL SPG TUR foodsetValuesfoodLst CmplParameter costs new CmplParametercosts food Double costVec 319 259 229 289 189 199 199 249 costssetValuescostVec CmplParameter vitmin new CmplParametervitMin nutr int vitminVec 700700700700 vitminsetValuesvitminVec CmplParameter vitamin new CmplParametervitamin nutr food int vitMat 60 8 8 40 15 70 25 60 20 0 10 40 35 30 50 20 10 20 15 35 15 15 25 15 15 20 10 10 15 15 15 10 vitaminsetValuesvitMat modelsetSetsnutr food modelsetParameterscosts vitmin vitamin modelsolve modelsolutionReport catch CmplException e Systemoutprintlne CMPL v112 Manual 163 Executing this jCMPL programme leads to the following output created by jCMPLs standard solution report Problem dietcmpl Nr of variables 8 Nr of constraints 4 Objective name cost Solver name CBC Display variables all Display vonstraints all Objective status optimal Objective value 10114 min Variables Name Type Activity LowerBound UpperBound Marginal xBEEF I 2 200 1000 xCHK I 8 200 1000 xFISH I 2 200 1000 xHAM I 2 200 1000 xMCH I 10 200 1000 xMTL I 10 200 1000 xSPG I 10 200 1000 xTUR I 2 200 1000 Constraints Name Type Activity LowerBound UpperBound Marginal lineA G 150000 70000 Infinity lineB1 G 133000 70000 Infinity lineB2 G 86000 70000 Infinity lineC G 70000 70000 Infinity 452 Transportation problem 4521 Problem description and CMPL model This subchapter discusses the pyCMPL formulation of the transportation problem from subchapter 2816 The CMPL model transportationcmpl can be formulated as follows data plants setcenters setroutes set2croutes splants dcenters variables xroutes real0 objectives costs sum ij in routes cijxij min constraints supplies i in plants sumj in routes i xij si demands j in centers sumi in routes j xij dj CMPL v112 Manual 164 4522 pyCMPL The corresponding pyCMPL script transportationpy is formulated as follows usrbinpython from pyCmpl import try model Cmpltransportationcmpl routes CmplSetroutes2 routessetValues1112142223243133 plants CmplSetplants plantssetValues13 centers CmplSetcenters centerssetValues14 costs CmplParametercroutes costssetValues32652324 s CmplParametersplants ssetValues500060002500 d CmplParameterdcenters dsetValues6000400020002500 modelsetSetsroutes plants centers modelsetParameterscostssd modelsetOutputTrue modelsetOptiondisplay nonZeros modelsolve if modelsolverStatus SOLVEROK modelsolutionReport else print Solver failed modelsolver modelsolverMessage except CmplException e print emsg Executing this pyCMPL model by using the command pyCmpl transportationpy CMPL v112 Manual 165 leads to the following output of CMPL and CBC enabled with modelsetOutputTrue and the standard solution report transportation CMPL model generation running transportation transportation CMPL version 190 transportation Authors Thomas Schleiff Mike Steglich transportation Distributed under the GPLv3 transportation transportation create model instance transportation write model instance transportation CMPL model generation finished transportation transportation Solver running transportation transportation Welcome to the CBC MILP Solver transportation Version 288 transportation Build Date Jan 3 2014 transportation Revision Number 2001 transportation transportation command line ApplicationsCmplbinThirdpartyCBCcbc transportation933604mps min solve gsolu transportation933604gsol default strategy 1 transportation At line 2 NAME transportationcmpl transportation At line 3 ROWS transportation At line 12 COLUMNS transportation At line 29 RHS transportation At line 34 RANGES transportation At line 35 BOUNDS transportation At line 44 ENDATA transportation Problem transportationcmpl has 7 rows 8 columns and 16 elements transportation Coin0008I transportationcmpl read with 0 errors transportation Presolve 6 1 rows 7 1 columns and 14 2 elements transportation 0 Obj 164997 Primal inf 95002001 3 Dual inf 19999999 1 transportation 5 Obj 36500 transportation Optimal objective value 36500 transportation After Postsolve objective 36500 infeasibilities dual 0 0 primal 0 0 transportation Optimal objective 36500 5 iterations time 0002 Presolve 000 transportation Total time CPU seconds 000 Wallclock seconds 000 transportation transportation transportation CMPL Time used for model generation 0 seconds transportation CMPL Time used for solving the model 0 seconds transportation transportation transportation Solution written to cmplSolution file transportation933604csol transportation transportation Solver finished transportation Problem transportationcmpl Nr of variables 8 Nr of constraints 7 Objective name costs Solver name CBC Display variables nonZeroVariables all Display constraints nonZeroConstraints all Objective status optimal Objective value 3650000 min Variables Name Type Activity LowerBound UpperBound Marginal x11 C 250000 000 inf 000 x12 C 250000 000 inf 000 CMPL v112 Manual 166 x22 C 150000 000 inf 000 x23 C 200000 000 inf 000 x24 C 250000 000 inf 000 x31 C 250000 000 inf 000 Constraints Name Type Activity LowerBound UpperBound Marginal supplies1 E 500000 500000 500000 300 supplies2 E 600000 600000 600000 600 supplies3 E 250000 250000 250000 200 demands1 L 500000 inf 600000 000 demands2 L 400000 inf 400000 100 demands3 L 200000 inf 200000 400 demands4 L 250000 inf 250000 300 4523 jCMPL The corresponding jCMPL script transportationjava is formulated as follows import jCMPL import javautilArrayList public class Transportation public static void mainString args throws CmplException try Cmpl model new Cmpltransportationcmpl CmplSet routes new CmplSetroutes 2 int arcs 1 1 1 2 1 4 2 2 2 3 2 4 3 1 3 3 routessetValuesarcs CmplSet plants new CmplSetplants plantssetValues1 3 CmplSet centers new CmplSetcenters centerssetValues1 1 4 CmplParameter costs new CmplParameterc routes Integer costArr 3 2 6 5 2 3 2 4 costssetValuescostArr CmplParameter s new CmplParameters plants int sList 500060002500 ssetValuessList CMPL v112 Manual 167 CmplParameter d new CmplParameterd centers int dArr 6000 4000 2000 2500 dsetValuesdArr modelsetSetsroutes plants centers modelsetParameterscosts s d modelsetOutputtrue modelsetOptiondisplay nonZeros modelsolve if modelsolverStatus CmplSOLVEROK modelsolutionReport else SystemoutprintlnSolver failed modelsolver modelsolverMessage catch CmplException e Systemoutprintlne Executing this pyCMPL model by using the command pyCmpl transportationpy leads to the following output of CMPL and CBC enabled with modelsetOutputTrue and the standard solution report transportation CMPL model generation running transportation CMPL version 190 transportation Authors Thomas Schleiff Mike Steglich transportation Distributed under the GPLv3 transportation create model instance transportation write model instance transportation CMPL model generation finished transportation Solver running transportation Welcome to the CBC MILP Solver transportation Version 288 transportation Build Date Jan 3 2014 transportation Revision Number 2001 transportation command line ApplicationsCmplbinThirdpartyCBCcbc transportation228086mps min solve gsolu transportation228086gsol default strategy 1 transportation At line 2 NAME transportationcmpl transportation At line 3 ROWS transportation At line 12 COLUMNS transportation At line 29 RHS transportation At line 34 RANGES transportation At line 35 BOUNDS transportation At line 44 ENDATA transportation Problem transportationcmpl has 7 rows 8 columns and 16 elements transportation Coin0008I transportationcmpl read with 0 errors transportation Presolve 6 1 rows 7 1 columns and 14 2 elements CMPL v112 Manual 168 transportation 0 Obj 164997 Primal inf 95002001 3 Dual inf 19999999 1 transportation 5 Obj 36500 transportation Optimal objective value 36500 transportation After Postsolve objective 36500 infeasibilities dual 0 0 primal 0 0 transportation Optimal objective 36500 5 iterations time 0002 Presolve 000 transportation Total time CPU seconds 000 Wallclock seconds 000 transportation CMPL Time used for model generation 0 seconds transportation CMPL Time used for solving the model 0 seconds transportation Solution written to cmplSolution file transportation228086csol transportation Solver finished Problem transportationcmpl Nr of variables 8 Nr of constraints 7 Objective name costs Solver name CBC Display variables nonZeroVariables all Display vonstraints nonZeroConstraints all Objective status optimal Objective value 3650000 min Variables Name Type Activity LowerBound UpperBound Marginal x11 C 250000 000 Infinity 000 x12 C 250000 000 Infinity 000 x22 C 150000 000 Infinity 000 x23 C 200000 000 Infinity 000 x24 C 250000 000 Infinity 000 x31 C 250000 000 Infinity 000 Constraints Name Type Activity LowerBound UpperBound Marginal supplies1 E 500000 500000 500000 300 supplies2 E 600000 600000 600000 600 supplies3 E 250000 250000 250000 200 demands1 L 500000 Infinity 600000 000 demands2 L 400000 Infinity 400000 100 demands3 L 200000 Infinity 200000 400 demands4 L 250000 Infinity 250000 300 453 The shortest path problem 4531 Problem description and CMPL model Consider an undirected network G VA where V is a set of nodes and A is a set of arcs joining pairs of nodes The decision is to find the shortest path from a starting node s to a target node t This problem can be formulated as an LP as follows Hillier and Liebermann 2010 p 383f CMPL v112 Manual 169 i jA cijxijmin st i jA xij j i A x ji 1 if is 1 if it 0 otherwise iV xij0i jA The decision variables are xij A with xij1 if the arc i j is used The parameters cij A define the distance between the nodes i and j but can also are interpreted as the time a vehicle takes to drive from node i to node j This CMPL model can be formulated as follows whilst the sets A an V and the parameters cij t and s are defined in a pyCMPL script or jCMPL programme data A set2 cA V set s t parameters i in V is rHsi1 it rHsi1 default rHsi0 variables xA real0 objectives sum ij in A cijxij min constraints node i in V sum j in A i xij sum j in A i xji rHsi To describe the formulation of the shortest path problem in pyCMPL and jCMPL the simple example shown in the following figure is used where the weights on the arcs are interpreted as the time in minutes a vehicle needs to travel from a node i to a node j It is assumed that the starting node is node 1 and the target node is node 7 CMPL v112 Manual 170 1 2 3 4 5 6 7 7 5 9 8 7 5 15 8 6 9 11 4532 pyCMPL The corresponding pyCMPL script shortestpathpy is formulated as follows usrbinpython from pyCmpl import try model Cmplshortestpathcmpl routes CmplSetA2 routessetValues 121421232425 323541424546 5253545657 6465677576 nodes CmplSetV nodessetValues17 c CmplParameterc routes csetValues75789785591567515896811911 sNode CmplParameters sNodesetValues1 tNode CmplParametert tNodesetValues7 modelsetSetsroutes nodes modelsetParameterscsNodetNode modelsolve print Objective Value modelsolutionvalue for v in modelsolutionvariables if vactivity0 print vname vactivity except CmplException e print emsg Executing this pyCMPL script through using the command pyCmpl shortespathpy leads to the following output of the pyCMPL script CMPL v112 Manual 171 Objective Value 220 x14 10 x46 10 x67 10 The optimal route is 1467 with a travelling time of 22 minutes 4533 jCMPL The corresponding jCMPL programme shortestpathjava is formulated as follows package shortestpath import jCMPL public class ShortestPath public static void mainString args throws CmplException try Cmpl m new Cmplshortestpathcmpl CmplSet routes new CmplSetA 2 int arcs 1 2 1 4 2 1 2 3 2 4 2 5 3 2 3 5 4 1 4 2 4 5 4 6 5 2 5 3 5 4 5 6 5 7 6 4 6 5 6 7 7 5 7 6 routessetValuesarcs CmplSet nodes new CmplSetV nodessetValues1 7 CmplParameter c new CmplParameterc routes Integer cArr 7 5 7 8 9 7 8 5 5 9 15 6 7 5 15 8 9 6 8 11 9 11 csetValuescArr CmplParameter sNode new CmplParameters sNodesetValues1 CmplParameter tNode new CmplParametert tNodesetValues7 msetSetsroutes nodes msetParametersc sNode tNode CMPL v112 Manual 172 msolve if msolverStatus CmplSOLVEROK SystemoutprintlnObjective value msolutionvalue for CmplSolElement v msolutionvariables if Double vactivity 0 Systemoutprintlnvname vactivity else SystemoutprintlnSolver failed msolver msolverMessage catch CmplException e Systemoutprintlne Executing this jCMPL programme leads to the following output of the pyCMPL script Objective value 220 x14 10 x46 10 x67 10 As in pyCMPL the optimal route is 1467 with a travelling time of 22 minutes 454 Solving randomized shortest path problems in parallel 4541 Problem description For the last example it was shown that the optimal route travelling from node 1 to node 7 is 1467 This solution is based on the assumption that the travelling times between nodes are certain This example describes how a randomized shortest path problem can be solved where subproblems describing random situations are solved in own threads in parallel 4542 pyCMPL Assuming that the staring node is node 1 and the target node is node 7 the corresponding pyCMPL script shortestpathpy is formulated as follows 1 2 3 4 5 usrbinpython from future import division from pyCmpl import import random CMPL v112 Manual 173 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 50 51 try routes CmplSetA2 routessetValues 121421232425 323541424546 5253545657 6465677576 nodes CmplSetV nodessetValues17 c CmplParameterc routes csetValues75789785591567515896811911 sNode CmplParameters sNodesetValues1 tNode CmplParametert tNodesetValues7 models randC for i in range5 modelsappendCmplshortestpathcmpl modelsisetOptiondisplay nonZeros modelsisetSetsroutes nodes tmpC for m in cvalues tmpCappend m randomrandint404010 randCappendCmplParameterc routes randCisetValuestmpC modelsisetParametersrandCisNodetNode for m in models mstart for m in models mjoin i 0 for m in models print problem i needed time msolutionvalue for v in msolutionvariables CMPL v112 Manual 174 52 53 54 56 57 print vname vactivity i i 1 except CmplException e print emsg This script uses the same sets and parameters as before but for each of the 5 instantiated models in line 29 a new parameter array c is created whilst the original array c is changed by random numbers in line 35 In line 43 all of the models are starting and in line 46 the pyCmpl script is waiting for the termination of all of the models Executing this pyCMPL script through using the command pyCmpl shortespathpy can lead to the following output of the pyCMPL script but every new run will show different results because of the random numbers problem 0 needed time 237 x14 10 x46 10 x67 10 problem 1 needed time 202 x12 10 x25 10 x57 10 problem 2 needed time 133 x14 10 x46 10 x67 10 problem 3 needed time 176 x12 10 x25 10 x57 10 problem 4 needed time 207 x14 10 x46 10 x67 10 Depending on the uncertain traffic situations two different routes between the nodes 17 can be op timal 1467 and 1257 4543 jCMPL Assuming that the staring node is node 1 and the target node is node 7 the corresponding jCMPL pro gramme shortestpathjava is formulated as follows 1 2 package shortestpath import jCMPL CMPL v112 Manual 175 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 import javautilArrayList import javautilloggingLevel import javautilloggingLogger public class shortestPathThreads public static void mainString args throws CmplException try CmplSet routes new CmplSetA2 int arcs 121421232425 323541424546 5253545657 6465677576 routessetValuesarcs CmplSet nodes new CmplSetV nodessetValues17 Integer cArr 75789785591567515896811911 CmplParameter sNode new CmplParameters sNodesetValues1 CmplParameter tNode new CmplParametert tNodesetValues7 ArrayListCmpl models new ArrayListCmpl ArrayListCmplParameter randC new ArrayListCmplParameter for int i 0 i 5 i modelsaddnew Cmplshortestpathcmpl modelsgetisetSetsroutes nodes randCaddnew CmplParameterc routes ArrayListDouble tmpC new ArrayListDouble for Integer cArr1 cArr tmpCaddDoublevalueOfcArr1 DoublevalueOf 40 Mathrandom 40 10 randCgetisetValuestmpC modelsgetisetParametersrandCgeti sNode tNode modelsgetisetOptiondisplay nonZeros CMPL v112 Manual 176 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 for Cmpl c models cstart for Cmpl c models cjoin int i 0 for Cmpl c models Systemoutprintlnmodel StringvalueOfi needed time csolutionvalue for CmplSolElement v csolutionvariables Systemoutprintlnvname vactivity i catch CmplException e Systemoutprintlne catch InterruptedException ex LoggergetLoggershortestPathThreadsclassgetName logLevelSEVERE null ex This script uses the same sets and parameters as before but for each of the 5 instantiated models in line 35 a new parameter array c is created whilst the original array c is changed by random numbers in line 42 In line 51 all of the models are starting and in line 56 the jCmpl programme is waiting for the termination of all of the models Executing this jCMPL programme can lead to the following output of the pyCMPL script but every new run will show different results because of the random numbers model 0 needed time 124438 x12 10 x25 10 x57 10 model 1 needed time 149163 x12 10 x25 10 x57 10 model 2 needed time 152786 x14 10 x46 10 CMPL v112 Manual 177 x67 10 model 3 needed time 15253 x14 10 x46 10 x67 10 model 4 needed time 138339 x14 10 x46 10 x67 10 Depending on the uncertain traffic situations two different routes between the nodes 17 can be op timal 1467 and 1257 455 Column generation for a cutting stock problem 4551 Problem description and CMPL model The following pyCMPL script and the corresponding jCMPL programme including the example are based on the AMPL formulation of a column generator for a cutting stock problem and is taken from Fourer etal 2003 p 304ff In this cutting stock problem long raw rolls of paper have to be cut up into combinations of smaller widths that have to meet given orders and the objective is to minimize the waste In the example the raw width is 110 and the demands for particular widths are given in the following table orders demand withs 48 20 35 45 24 50 10 55 8 75 Fourer Gay Kernigham use the GilmoreGomory procedure to define cutting patterns by involving two lin ear programmes The first model is a cutting optimisation model that finds the minimum number of raw rolls with a given set of possible cutting patterns subject to fulfilling the orders for the particular widths This problem can be for mulated as in the CMPL file cutcmpl as follows data rollWidth widths set patterns set orderswidthsnbrwidthspatterns variables cutpatterns integer0 objectives number sum j in patterns cutj min CMPL v112 Manual 178 constraints fill i in widths sum j in patterns nbrijcutj ordersi The parameter rollWidth defines the width of the raw rolls the set widths defines the widths to be cut the set patterns the set of the patterns the parameter orders the number of orders per width and the parameters nbrij the number of rolls of width i in pattern j The variables are the cutj and they define how many cuts of a pattern j are to be produced The second model is the pattern generation model that is indented to identify a new pattern that can be used in the cutting optimisation data widths set pricewidths rollWidth variables usewidths integer0 reducedCosts real objectives sum i in widths pricei usei max constraints sum i in widths i usei rollWidth This model in the CMPL file cutpatterncmpl requires as specified in the data entry the set widths the parameter rollWidth and a parameter vector price that contains the marginals of the constraints fill of a solved cutcmpl problem with a relaxation of the integer variables cutj It is a knapsack problem that fills a knapsack here a raw roll with a given width rollWidth with the most valuable things here the desired widths via the variables usei where the value of a width i is specified by the pricei 4552 jCMPL The relationship between these two CMPL models and the entire cutting optimisation procedure is controlled by the following pyCMPL script cutpy 1 2 3 4 5 6 7 8 9 10 11 12 usrbinpython from pyCmpl import import math try cuttingOpt Cmplcutcmpl patternGen Cmplcutpatterncmpl cuttingOptsetOptionarg solver cplex patternGensetOptionarg solver cplex CMPL v112 Manual 179 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 50 51 52 53 54 55 56 57 58 r CmplParameterrollWidth rsetValues110 w CmplSetwidths wsetValues 20 45 50 55 75 o CmplParameterordersw osetValues 48 35 24 10 8 nPatwlen p CmplSetpatterns psetValues1nPat nbr for i in rangenPat nbrappend 0 for j in rangenPat for i in wvalues pos wvaluesindexi nbrpospos intmathfloor rvalue i n CmplParameternbr w p nsetValuesnbr price for i in rangewlen priceappend0 pr CmplParameterprice w prsetValuesprice cuttingOptsetSetswp cuttingOptsetParametersr o n patternGensetSetsw patternGensetParametersrpr ri cuttingOptsetOptionarg integerRelaxation while True cuttingOptsolve cuttingOptconByName for i in wvalues pos wvaluesindexi pricepos cuttingOptfillimarginal CMPL v112 Manual 180 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 prsetValuesprice patternGensolve patternGenvarByName if 1patternGensolutionvalue 000001 nPat nPat 1 psetValues1nPat for i in wvalues pos wvaluesindexi nbrposappendpatternGenuseiactivity nsetValuesnbr else break cuttingOptdelOptionri cuttingOptsolve cuttingOptvarByName print Objective value cuttingOptsolutionvalue print Pattern vStr for j in pvalues vStr d j print vStr print for i in rangelenwvalues vStr2d wvaluesi for j in pvalues vStr d nbrij1 print vStr print for j in pvalues if cuttingOptcutjactivity0 print 2d pieces of pattern d cuttingOptcutjactivity j for i in rangelenwvalues print width wvaluesi nbrij1 except CmplException e print emsg CMPL v112 Manual 181 Cplex is chosen as solver for both in the lines 7 and 8 instantiated models lines 1011 In the next lines 13 20 the parameters rollWidth and orders and the set widths are created and the corresponding data are assigned The lines 2635 are intended to create an initial set of patterns whilst the matrix nbr contains only one pattern per width where the diagonal elements are equal to the maximal possible number of rolls of the particular width After creating the vector price with null values in the lines 3742 all relevant sets and parameters are committed to both Cmpl objects lines 4448 In the next lines the GilmoreGomory procedure is performed 1 Solve the cutting optimisation problem cutcmpl with an integer relaxation line 50 and 53 2 Assign the shadow prices cuttingOptfillimarginal to the corresponding elements pricei for each pattern lines 5658 3 Solve the pattern generation model cutpatterncmpl line 62 4 If 1 optimal objective value is approximately 0 line 65 then add a new pattern using the activities patternGenuseiactivity for all elements in widths lines 6870 and jump to step 1 else Solve the final cutting optimisation problem cutcmpl as integer programme lines 75 and 77 After finding the final solution the next lines lines 78103 are intended to provide some information about the final integer solution Executing this pyCMPL model through using the command pyCmpl cutpy leads to the following output of the pyCMPL script Objective value 470 Pattern 1 2 3 4 5 6 7 8 20 5 0 0 0 0 1 1 3 45 0 2 0 0 0 0 2 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 1 0 0 8 pieces of pattern 3 width 20 0 width 45 0 width 50 2 width 55 0 width 75 0 5 pieces of pattern 4 CMPL v112 Manual 182 width 20 0 width 45 0 width 50 0 width 55 2 width 75 0 8 pieces of pattern 6 width 20 1 width 45 0 width 50 0 width 55 0 width 75 1 18 pieces of pattern 7 width 20 1 width 45 2 width 50 0 width 55 0 width 75 0 8 pieces of pattern 8 width 20 3 width 45 0 width 50 1 width 55 0 width 75 0 4553 jCMPL The relationship between these cutpatterncmpl and cutcmpl and the entire cutting optimisation procedure is controlled by the following jCMPL programme CuttingStockjava 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package cuttingstock import jCMPL import javaioBufferedWriter import javaioFileWriter import javaioIOException import javautilArrayList public class CuttingStock public CuttingStock throws CmplException try Cmpl cuttingOpt new Cmplcutcmpl Cmpl patternGen new Cmplcutpatterncmpl cuttingOptsetOptionarg solver cplex patternGensetOptionarg solver cplex CMPL v112 Manual 183 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 50 51 52 53 54 55 56 57 58 59 60 61 62 CmplParameter r new CmplParameterrollWidth rsetValues110 CmplSet w new CmplSetwidths int wVals 20 45 50 55 75 wsetValueswVals CmplParameter o new CmplParameterorders w int oVals 48 35 24 10 8 osetValuesoVals int nPat wlen CmplSet p new CmplSetpatterns psetValues1 nPat ArrayListArrayListLong nbr new ArrayListArrayListLong for int i 0 i nPat i ArrayListLong nbrRow new ArrayListLong for int j 0 j nPat j if i j Double nr MathfloorInteger rvalue int wvaluesi nbrRowadd nrlongValue else nbrRowaddLongvalueOf0 nbraddnbrRow CmplParameter n new CmplParameternbr w p nsetValuesnbr Double price new Doublewlen for int i 0 i pricelength i pricei 00 CmplParameter pr new CmplParameterprice w prsetValuesprice cuttingOptsetSetsw p cuttingOptsetParametersr o n CMPL v112 Manual 184 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 patternGensetSetsw patternGensetParametersr pr int ri cuttingOptsetOptionarg integerRelaxation while true cuttingOptsolve CmplSolArray fillCmplSolArraycuttingOptgetConByNamefill int pos 0 for int with int wvalues pricepos fillgetwithmarginal pos prsetValuesprice patternGensolve CmplSolArray use CmplSolArray patternGengetVarByNameuse if 1patternGensolutionvalue 000001 nPat psetValues1 nPat for int i 0 i wlen i ArrayListLong tmpList nbrgeti tmpListadd Long usegetwgetiactivity nbrseti tmpList nsetValuesnbr else break cuttingOptdelOptionri cuttingOptsolve CmplSolArray cut CmplSolArray cuttingOptgetVarByNamecut BufferedWriter out new BufferedWriternew FileWritercuttingStock stdout outwriteStringformatObjective value 42fnn cuttingOptsolutionvalue outwritePattern CMPL v112 Manual 185 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 outwrite for int j ArrayListInteger pvalues utwriteStringformat d j outwrite for int i 0 i wlen i outwriteStringformat2d wgeti for int j ArrayListInteger pvalues outwriteStringformat d nbrgetigetj 1 outwrite outwrite for int j ArrayListInteger pvalues if Long cutgetjactivity 0 outwrite Stringformat2d pieces of pattern d n Long cutgetjactivity j for int i0 iwlen i outwriteStringformat width d dn wgeti nbrgetigetj1 outclose catch CmplException e Systemoutprintlne catch IOException e SystemoutprintlnIO error e Cplex is chosen as solver for both instantiated models in the lines 15 and 16 lines 1213 In the next lines 1827 the parameters rollWidth and orders and the set widths are created and the corresponding data are assigned The lines 2951 are intended to create an initial set of patterns whilst the matrix nbr con tains only of one pattern per width where the diagonal elements are equal to the maximal possible number of rolls of the particular width After creating the vector price with null values in the lines 5359 all relevant sets and parameters are committed to both Cmpl objects lines 6165 In the next lines the GilmoreGomory procedure is performed 5 Solve the cutting optimisation problem cutcmpl with an integer relaxation line 67 and 70 6 Assign the shadow prices cuttingOptfillimarginal to the corresponding elements pricei for each pattern lines 7578 7 Solve the pattern generation model cutpatterncmpl line 82 CMPL v112 Manual 186 8 If 1 optimal objective value is approximately 0 line 85 then add a new pattern using the activities patternGenuseiactivity for all elements in widths lines 8892 and jump to step 1 else Solve the final cutting optimisation problem cutcmpl as integer programme line 98 and 100 After finding the final solution the next lines lines 101139 are intended to provide some information about the final integer solution Executing this jCMPL model leads to the following output Objective value 4700 Pattern 1 2 3 4 5 6 7 8 20 5 0 0 0 0 1 1 3 45 0 2 0 0 0 0 2 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 1 0 0 8 pieces of pattern 3 width 20 0 width 45 0 width 50 2 width 55 0 width 75 0 5 pieces of pattern 4 width 20 0 width 45 0 width 50 0 width 55 2 width 75 0 8 pieces of pattern 6 width 20 1 width 45 0 width 50 0 width 55 0 width 75 1 18 pieces of pattern 7 width 20 1 width 45 2 width 50 0 width 55 0 width 75 0 8 pieces of pattern 8 CMPL v112 Manual 187 width 20 3 width 45 0 width 50 1 width 55 0 width 75 0 CMPL v112 Manual 188 5 Authors and Contact CMPL Thomas Schleiff HalleSaale Germany Mike Steglich Technical University of Applied Sciences Wildau Germany mikesteglichthwildaude Coliop pyCMPL and CMPLServer Mike Steglich jCMPL Mike Steglich Bernhard Knie Technical University of Applied Sciences Wildau Germany Contact co Mike Steglich Professor of Business Administration Quantitative Methods and Management Accounting Technical University of Applied Sciences Wildau Faculty of Business Administration and Law Hochschulring 1 15745 Wildau Germany Tel 493375 508365 Fax 493375 508566 mikesteglichthwildaude Support via mailing list Please use our CMPL mailing list hosted at COINOR httplistcoinororgmailmanlistinfoCmpl to get a direct support to post bugs or to communicate wishes CMPL v112 Manual 189 6 Appendix 61 Selected CBC parameters The CBC parameters are taken mostly unchanged from the CBC command line help Only the CBC para meters that are useful in a CMPL context are described afterwards Usage CBC parameters opt cbc solverOption solverOptionValue Double parameters dualBound doubleValue Initially algorithm acts as if no gap between bounds exceeds this value Range of values is 1e20 to 1e12 default 1e10 dualTolerance doubleValue For an optimal solution no dual infeasibility may exceed this value Range of values is 1e20 to 1e12 default 1e07 objectiveScale doubleValue Scale factor to apply to objective Range of values is 1e20 to 1e20 default 1 primalTolerance doubleValue For an optimal solution no primal infeasibility may exceed this value Range of values is 1e20 to 1e12 default 1e07 primalWeight doubleValue Initially algorithm acts as if it costs this much to be infeasible Range of values is 1e20 to 1e20 default 1e10 rhsScale doubleValue Scale factor to apply to rhs and bounds Range of values is 1e20 to 1e20 default 1 Branch and Cut double parameters allowableGap doubleValue Stop when gap between best possible and best less than this Range of values is 0 to 1e20 default 0 CMPL v112 Manual 190 artificialCost doubleValue Costs these are treated as artificials in feasibility pump 00 off otherwise variables with costs these are treated as artificials and fixed to lower bound in feasibility pump Range of values is 0 to 179769e308 default 0 cutoff doubleValue All solutions must be better than this value in a minimization sense This is also set by code whenever it obtains a solution and is set to value of objective for solution minus cutoff increment Range of values is 1e60 to 1e60 default 1e50 fixOnDj doubleValue Try heuristic based on fixing variables with reduced costs greater than this If this is set integer variables with reduced costs greater than this will be fixed before branch and bound use with extreme caution Range of values is 1e20 to 1e20 default 1 fractionforBAB doubleValue Fraction in feasibility pump After a pass in feasibility pump variables which have not moved about are fixed and if the preprocessed model is small enough a few nodes of branch and bound are done on reduced problem Small problem has to be less than this fraction of original Range of values is 1e05 to 11 default 05 increment doubleValue A valid solution must be at least this much better than last integer solution Whenever a solution is found the bound on solutions is set to solution in a minimization sense plus this If it is not set then the code will try and work one out Range of values is 1e20 to 1e20 default 1e05 infeasibilityWeight doubleValue Each integer infeasibility is expected to cost this much Range of values is 0 to 1e20 default 0 integerTolerance doubleValue For an optimal solution no integer variable may be this away from an integer value Range of values is 1e20 to 05 default 1e06 preTolerance doubleValue Tolerance to use in presolve Range of values is 1e20 to 1e12 default 1e08 CMPL v112 Manual 191 pumpCutoff doubleValue Fake cutoff for use in feasibility pump 00 off otherwise add a constraint forcing objective below this value in feasibility pump Range of values is 179769e308 to 179769e308 default 0 pumpIncrement doubleValue Fake increment for use in feasibility pump 00 off otherwise use as absolute increment to cut off when solution found in feasibility pump Range of values is 179769e308 to 179769e308 default 0 ratioGap doubleValue If the gap between best solution and best possible solution is less than this fraction of the objective value at the root node then the search will terminate Range of values is 0 to 1e20 default 0 reallyObjectiveScale doubleValue Scale factor to apply to objective in place Range of values is 1e20 to 1e20 default 1 seconds doubleValue maximum seconds After this many seconds coin solver will act as if maximum nodes had been reached Range of values is 1 to 1e12 default 1e08 tightenFactor doubleValue Tighten bounds using this times largest activity at continuous solution Range of values is 0001 to 1e20 default 1 Integer parameters idiotCrash integerValue This is a type of crash which works well on some homogeneous problems It works best on problems with unit elements and rhs but will do something to any model It should only be used before primal It can be set to 1 when the code decides for itself whether to use it 0 to switch off or n 0 to do n passes Range of values is 1 to 99999999 default 1 maxFactor integerValue Maximum number of iterations between refactorizations Range of values is 1 to 999999 default 200 CMPL v112 Manual 192 maxIterations integerValue Maximum number of iterations before stopping Range of values is 0 to 2147483647 default 2147483647 passPresolve integerValue How many passes in presolve Range of values is 200 to 100 default 5 pOptions integerValue If this is 0 then presolve will give more information and branch and cut will give statistics Range of values is 0 to 2147483647 default 0 slpValue integerValue Number of slp passes before primal If you are solving a quadratic problem using primal then it may be helpful to do some se quential Lps to get a good approximate solution Range of values is 1 to 50000 default 1 slogLevel integerValue Level of detail in LP Solver output Range of values is 1 to 63 default 1 substitution integerValue How long a column to substitute for in presolve Normally Presolve gets rid of free variables when there are no more than 3 variables in column If you increase this the number of rows may decrease but number of elements may increase Range of values is 0 to 10000 default 3 Branch and Cut integer parameters cutDepth integerValue Depth in tree at which to do cuts Cut generators may be off on only at root on if they look possible and on If they are done every node then that is that but it may be worth doing them every so often The ori ginal method was every so many nodes but it is more logical to do it whenever depth in tree is a multiple of K This option does that and defaults to 1 off code decides Range of values is 1 to 999999 default 1 cutLength integerValue Length of a cut CMPL v112 Manual 193 At present this only applies to Gomory cuts 1 default leaves as is Any value 0 says that all cuts this length can be generated both at root node and in tree 0 says to use some dynamic lengths If value 10000000 then the length in tree is value10000000 so 10000100 means unlimited length at root and 100 in tree Range of values is 1 to 2147483647 default 1 denseThreshold integerValue Whether to use dense factorization Range of values is 1 to 10000 default 1 depthMiniBab integerValue Depth at which to try mini BAB Rather a complicated parameter but can be useful 1 means off for large problems but on as if 12 for problems where rowscolumns500 2 means use Cplex if it is linked in Oth erwise if negative then go into depth first complete search fast branch and bound when depth value2 so 3 will use this at depth1 This mode is only switched on after 500 nodes If you really want to switch it off for small problems then set this to 999 If 0 the value doesnt matter very much The code will do approximately 100 nodes of fast branch and bound every now and then at depth5 The actual logic is too twisted to de scribe here Range of values is 2147483647 to 2147483647 default 1 diveOpt integerValue Diving options If 2 8 then modify diving options 3 only at root and if no solution 4 only at root and if this heuristic has not got solution 5 only at depth 4 6 decay 7 run up to 2 times if solution found 4 otherwise Range of values is 1 to 200000 default 3 hOptions integerValue Heuristic options 1 says stop heuristic immediately allowable gap reached Others are for feasibility pump 2 says do exact number of passes given 4 only applies if initial cutoff given and says relax after 50 passes while 8 will adapt cutoff rhs after first solution if it looks as if code is stalling Range of values is 9999999 to 9999999 default 0 CMPL v112 Manual 194 hotStartMaxIts integerValue Maximum iterations on hot start Range of values is 0 to 2147483647 default 100 logLevel integerValue Level of detail in Coin branch and Cut output If 0 then there should be no output in normal circumstances 1 is probably the best value for most uses while 2 and 3 give more information Range of values is 63 to 63 default 1 maxNodes integerValue Maximum number of nodes to do Range of values is 1 to 2147483647 default 2147483647 maxSolutions integerValue Maximum number of solutions to get You may want to stop after say two solutions or an hour This is checked every node in tree so it is possible to get more solutions from heuristics Range of values is 1 to 2147483647 default 1 passCuts integerValue Number of cut passes at root node The default is 100 passes if less than 500 columns 100 passes but stop if drop small if less than 5000 columns 20 otherwise Range of values is 9999999 to 9999999 default 1 passFeasibilityPump integerValue How many passes in feasibility pump This fine tunes Feasibility Pump by doing more or fewer passes Range of values is 0 to 10000 default 30 passTreeCuts integerValue Number of cut passes in tree Range of values is 9999999 to 9999999 default 1 smallFactorization integerValue Whether to use small factorization If processed problem this use small factorization Range of values is 1 to 10000 default 1 CMPL v112 Manual 195 strongBranching integerValue Number of variables to look at in strong branching Range of values is 0 to 999999 default 5 threads integerValue Number of threads to try and use To use multiple threads set threads to number wanted It may be better to use one or two more than number of cpus available If 100n then n threads and search is repeatable maybe be somewhat slower if 200n use threads for root cuts 400n threads used in subtrees Range of values is 100 to 100000 default 0 trustPseudoCosts integerValue Number of branches before we trust pseudocosts Range of values is 3 to 2000000 default 5 Keyword parameters bscale option Whether to scale in barrier and ordering speed Possible options off on off1 on1 off2 on2 default off cholesky option Which cholesky algorithm Possible options native dense fudgeLongdummy wssmpdummy crash option Whether to create basis for problem If crash is set on and there is an all slack basis then Clp will flip or put structural variables into basis with the aim of getting dual feasible On the whole dual seems to be better without it and there are alternative types of crash for primal eg idiot or sprint Possible options off on solowhalim halimsolowJJF mods dfeault off crossover option Whether to get a basic solution after barrier Interior point algorithms do not obtain a basic solution and the feasibility criterion is a bit suspect JJF This option will crossover to a basic solution suitable for ranging or branch and cut With the current state of quadratic it may be a good idea to switch off crossover for quadratic and maybe presolve as well the option maybe does this Possible options on off maybe presolve default on CMPL v112 Manual 196 dualPivot option Dual pivot choice algorithm Possible options automatic dantzig partial steepest default automatic factorization option Which factorization to use Possible options normal dense simple osl default normal gammaDelta option Whether to regularize barrier Possible options off on gamma delta onstrong gammastrong deltastrong default off KKT option Whether to use KKT factorization Possible options off on default off perturbation option Whether to perturb problem Possible options on off default on presolve option Presolve analyzes the model to find such things as redundant equations equations which fix some variables equations which can be transformed into bounds etc etc For the initial solve of any problem this is worth doing unless you know that it will have no effect on will normally do 5 passes while using more will do 10 If the problem is very large you may need to write the original to file using file Possible options for presolve are on off more file default on primalPivot option Primal pivot choice algorithm Possible options automatic exact dantzig partial steepest change sprint default automatic scaling option Whether to scale problem Possible options off equilibrium geometric automatic dynamic rowsonly default automatic sparseFactor option Whether factorization treated as sparse Possible options on off default on CMPL v112 Manual 197 timeMode option Whether to use CPU or elapsed time cpu uses CPU time for stopping while elapsed uses elapsed time On Windows elapsed time is always used Possible options cpu elapsed default cpu vector option If this parameter is set to on ClpPackedMatrix uses extra column copy in odd format Possible options off on default off Branch and Cut keyword parameters cliqueCuts option Whether to use Clique cuts Possible options off on root ifmove forceOn onglobal default ifmove combineSolutions option Whether to use combine solution heuristic This switches on a heuristic which does branch and cut on the problem given by just using variables which have appeared in one or more solutions It obviously only tries after two or more solutions See Rounding for meaning of onbothbefore Possible options off on both before default on combine2Solutions option Whether to use crossover solution heuristic This switches on a heuristic which does branch and cut on the problem given by fixing vari ables which have same value in two or more solutions It obviously only tries after two or more solutions See Rounding for meaning of onbothbefore Possible options off on both before default off costStrategy option How to use costs as priorities This orders the variables in order of their absolute costs with largest cost ones being branched on first This primitive strategy can be surprsingly effective The column order option is obviously not on costs but easy to code here Possible options off priorities columnOrder 01first 01last length default off CMPL v112 Manual 198 cutsOnOff option Switches all cuts on or off This can be used to switch on or off all cuts apart from Reduce and Split Then you can do individual ones off or on See branchAndCut for information on options Possible options off on root ifmove forceOn default on Dins option This switches on Distance induced neighborhood Search See Rounding for meaning of onbothbefore Possible options off on both before often default off DivingSome option This switches on a random diving heuristic at various times C Coefficient F Fractional G Guided L LineSearch P PseudoCost V VectorLength You may prefer to use individual onoff See Rounding for meaning of onbothbefore Possible options off on both before default off DivingCoefficient option Whether to try DiveCoefficient Possible options off on both before default on DivingFractional option Whether to try DiveFractional Possible options off on both before default off DivingGuided option Whether to try DiveGuided Possible options off on both before default off DivingLineSearch option Whether to try DiveLineSearch Possible options off on both before default off DivingPseudoCost option Whether to try DivePseudoCost Possible options off on both before default off DivingVectorLength option Whether to try DiveVectorLength Possible options off on both before default off CMPL v112 Manual 199 feasibilityPump option This switches on feasibility pump heuristic at root This is due to Fischetti Lodi and Glover and uses a sequence of Lps to try and get an integer feasible solution Some fine tuning is available by passFeasibilityPump and also pumpTune See Rounding for meaning of onbothbefore Possible options off on both before default on flowCoverCuts option This switches on flow cover cuts either at root or in entire tree See branchAndCut for information on options Possible options off on root ifmove forceOn onglobal default ifmove gomoryCuts option Whether to use Gomory cuts The original cuts beware of imitations Having gone out of favor they are now more fash ionable as LP solvers are more robust and they interact well with other cuts They will al most always give cuts although in this executable they are limited as to number of variables in cut However the cuts may be dense so it is worth experimenting Long allows any length See branchAndCut for information on options Possible options off on root ifmove forceOn onglobal forceandglobal forceLongOn long de fault ifmove greedyHeuristic option Whether to use a greedy heuristic Switches on a greedy heuristic which will try and obtain a solution It may just fix a percent age of variables and then try a small branch and cut run See Rounding for meaning of onbothbefore Possible options off on both before default on heuristicsOnOff option Switches most heuristics on or off Possible options off on default on knapsackCuts option This switches on knapsack cuts either at root or in entire tree Possible options off on root ifmove forceOn onglobal forceandglobal default ifmove liftAndProjectCuts option Whether to use Lift and Project cuts Possible options off on root ifmove forceOn default off CMPL v112 Manual 200 localTreeSearch option This switches on a local search algorithm when a solution is found This is from Fischetti and Lodi and is not really a heuristic although it can be used as one When used from Coin solve it has limited functionality It is not switched on when heuristics are switched on Possible options off on default off mixedIntegerRoundingCuts option This switches on mixed integer rounding cuts either at root or in entire tree See bran chAndCut for information on options Possible options off on root ifmove forceOn onglobal default ifmove naiveHeuristics option Really silly stuff eg fix all integers with costs to zero Do option does heuristic before pre processing Possible options off on both before default off nodeStrategy option What strategy to use to select nodes Normally before a solution the code will choose node with fewest infeasibilities You can choose depth as the criterion You can also say if up or down branch must be done first the up down choice will carry on after solution Default has now been changed to hybrid which is breadth first on small depth nodes then fewest Possible options hybrid fewest depth upfewest downfewest updepth downdepth default fewest pivotAndComplement option Whether to try Pivot and Complement heuristic Possible options off on both before default off pivotAndFix option Whether to try Pivot and Fix heuristic Possible options off on both before default off preprocess option This tries to reduce size of model in a similar way to presolve and it also tries to strengthen the model this can be very useful and is worth trying Save option saves on file pre solvedmps equal will turn cliques into sos will create sos sets if all 01 in sets well one extra is allowed and no overlaps trysos is same but allows any number extra equalall will turn all valid inequalities into equalities with integer slacks Possible options off on save equal sos trysos equalall strategy aggregate forcesos default sos CMPL v112 Manual 201 probingCuts option This switches on probing cuts either at root or in entire tree See branchAndCut for inform ation on options but strong options do more probing Possible options off on root ifmove forceOn onglobal forceonglobal forceOnBut forceOn Strong forceOnButStrong strongRoot default forceOnStrong randomizedRounding option Whether to try randomized rounding heuristic Possible options off on both before default off reduceAndSplitCuts option This switches on reduce and split cuts either at root or in entire tree See branchAndCut for information on options Possible options off on root ifmove forceOn default off residualCapacityCuts option Residual capacity cuts See branchAndCut for information on options Possible options off on root ifmove forceOn default off Rens option This switches on Relaxation enforced neighborhood Search on just does 50 nodes 200 or 1000 does that many nodes Doh option does heuristic before preprocessing Possible options off on both before 200 1000 10000 dj djbefore default off Rins option This switches on Relaxed induced neighborhood Search Doh option does heuristic before preprocessing Possible options off on both before often default on roundingHeuristic option This switches on a simple but effective rounding heuristic at each node of tree On means do in solve ie after preprocessing Before means do if doHeuristics used off otherwise and both means do if doHeuristics and in solve Possible options off on both before default on twoMirCuts option This switches on two phase mixed integer rounding cuts either at root or in entire tree See branchAndCut for information on options Possible options off on root ifmove forceOn onglobal forceandglobal forceLongOn default root CMPL v112 Manual 202 VndVariableNeighborhoodSearch option Whether to try Variable Neighborhood Search Possible options off on both before intree default off Actions barrier Solve using primal dual predictor corrector algorithm dualSimplex Do dual simplex algorithm eitherSimplex Do dual or primal simplex algorithm initialS Solve to continuous This just solves the problem to continuous without adding any cuts outDup takes duplicate rows etc out of integer model primalS Do primal simplex algorithm reallyS Scales model in place stat Print some statistics tightLP Poor persons preSolve for now Branch and Cut actions branch Do Branch and Cut 62 Selected GLPK parameters The following parameters are taken from the GLPK command line help Only the GLPK parameters that are useful in a CMPL context are described afterwards Usage GLPK parameters opt glpk solverOption solverOptionValue General options simplex use simplex method default interior use interior point method LP only scale scale problem default noscale do not scale problem ranges filename write sensitivity analysis report to filename in printable format simplex only CMPL v112 Manual 203 tmlim nnn limit solution time to nnn seconds memlim nnn limit available memory to nnn megabytes wlp filename write problem to filename in CPLEX LP format wglp filename write problem to filename in GLPK format wcnf filename write problem to filename in DIMACS CNFSAT format log filename write copy of terminal output to filename LP basis factorization options luf LU ForrestTomlin update faster less stable default cbg LU Schur complement BartelsGolub update slower more stable cgr LU Schur complement Givens rotation update slower more stable Options specific to simplex solver primal use primal simplex default dual use dual simplex std use standard initial basis of all slacks adv use advanced initial basis default bib use Bixbys initial basis steep use steepest edge technique default nosteep use standard textbook pricing relax use Harris twopass ratio test default norelax use standard textbook ratio test presol use presolver default assumes scale and adv nopresol do not use presolver exact use simplex method based on exact arithmetic xcheck check final basis using exact arithmetic Options specific to interiorpoint solver nord use natural original ordering qmd use quotient minimum degree ordering CMPL v112 Manual 204 amd use approximate minimum degree ordering default symamd use approximate minimum degree ordering Options specific to MIP solver nomip consider all integer variables as continuous allows solving MIP as pure LP first branch on first integer variable last branch on last integer variable mostf branch on most fractional variable drtom branch using heuristic by Driebeck and Tomlin default pcost branch using hybrid pseudocost heuristic may be useful for hard instances dfs backtrack using depth first search bfs backtrack using breadth first search bestp backtrack using the best projection heuristic bestb backtrack using node with best local bound default intopt use MIP presolver default nointopt do not use MIP presolver binarize replace general integer variables by binary ones assumes intopt fpump apply feasibility pump heuristic gomory generate Gomorys mixed integer cuts mir generate MIR mixed integer rounding cuts cover generate mixed cover cuts clique generate clique cuts cuts generate all cuts above mipgap tol set relative mip gap tolerance to tol minisat translate integer feasibility problem to CNFSAT and solve it with MiniSat solver objbnd bound add inequality obj bound minimization or obj bound maximization to integer feasibility problem assumes minisat CMPL v112 Manual 205 References Achterberg T 2009 SCIP solving constraint integer programs Mathematical Programming Compu tation Volume 1 Number 1 141 Coulouris GF J Dollimore T Kindberg G Blai 2012 Distributed Systems Concepts and Design 5th ed AddisonWesley Fourer R D M Gay B W Kernighan 2003 AMPL A Modeling Language for Mathematical Pro gramming 2nd ed Duxbury Press Pacific Grove CA Anderson D R D J Sweeney Th A Williams K Martin 2011 An Introduction to Management Science Quantitative Approaches to Decision Making 13th ed SouthWestern Fourer R J Ma R K Martin 2010 Optimization Services A Framework for Distributed Optimiza tion Operations Research 586 16241636 GLPK 2014 GNU Linear Programming Kit Reference Manual for GLPK Version 454 Hillier F S G J Lieberman 2010 Introduction to Operations Research 9th ed McGrawHill Higher Education Foster I C Kesselman editors 2004 The Grid2 2nd Edition Blueprint for a New Computing In frastructure Kindle ed Morgan Kaufmann Publishers Inc Kshemkalyani AD M Singhal M 2008 Distributed Computing Principles Algorithms and Sys tems Kindle ed Cambridge University Press St Laurent S J Johnston E Dumbill 2001 Programming Web Services with XMLRPC 1st ed OReilly Rogge R M Steglich 2007 Betriebswirtschaftliche Entscheidungsmodelle zur Verfahrenswahl sowie Auflagen und Lagerpolitiken Diskussionsbeiträge zu Wirtschaftsinformatik und Operations Research 102007 MartinLutherUniversität HalleWittenberg CMPL v112 Manual 206