Home
IBM ILOG OPL Language Reference Manual
Contents
1. n be a set of fixed intervals and c a fixed integer rhe span constraint span a bi bi ba holds if and only i r a amp Vie 1 n 727 b Ji 1 n bi ria s a MUD eft ne n b s b e a MaXiejt n b bi The alternative interval constraint alternative a by bi ba holds if and only if w a Wi Ln r b KAWA K c ria amp AKC ln d Yk E K x bx A s a s bx A ela e de vj l m K r b When parameter is ommitted we assume 1 Note that when lt 0 as there cannot be any subset X C l n such that K Q and K ce it means that necessarily interval a is And the contrapositive if interval a is present then necessarily for the constraint to be satisfied it must be that gt 1 lhe synchronization constraint synchronize a by bi n holds if and only if r a gt Yi 1 n x b s a s b A e a e b Note that the alternative span and synchronize constraints cannot be used in meta constraints For syntax and examples see the functions as described in the OPL Language Quick Reference alternative span ILOG OPL LANGUAGE REFERENCE MANUAL synchronize IBM ILOG OPL LANGUAGE REFERENCE MANUAL 151 A logical constraint between interval variables presenceOf 152 B M The presence constraint states a certain interval must be present in the solution The semantics of the presence constraint on a fixed i
2. The null value The null value is a special value used in some places to specify an absence of information For example an array element which has not yet been set has a default value of null The null value is not to be confused with the undefined value which also specifies an absence of information in some contexts See section The undefined value below The null value can be referenced in programs with the keyword nu11 null gt the null value When converted to a number null yields zero 0 Methods of null There is only one method of null Methods of null Syne eect sd null toString Returns the string null IBM ILOG OPL LANGUAGE REFERENCE MANUAL 255 The undefined value 256 B M The undefined value is a special value used in some places to specify an absence of information For example accessing a property of a value which is not defined or a local variable which has been declared but not initialized yields the undefined value There is no way of referencing the undefined value in programs Checking if a value is the undefined value can be done using the typeof operator typeof value undefined gt true if value is undefined false otherwise Methods of undefined There is only one method of undefined Methods of undefined sx fr undefined toString Returns the string undefined ILOG OPL LANGUAGE REFERENCE MANUAL IBM ILOG Script functions In IB
3. Ifthen else statements make it possible to state constraints conditionally as in aae cbal A abs freq f freq g gt d else freq f freqig Conditions in if else statements must be ground that is they must not contain decision variables They can also not contain forall statements like the following ns ool sgopa yb IL 5 6g Implications of constraints can be used instead when conditions contain decision variables Conditionals can also be used in OPL to make different choices according to the truth value of a condition IBM ILOG OPL LANGUAGE REFERENCE MANUAL 105 Filtering with constraints 106 B M In addition to applying constraints to decision variables you can also create constraints on formal parameters to filter aggregates like this Filtering with constraints The cities where we are doing business Siting cites Parise Beri sWasiiinciwOnme sR Onn hy string EuropeanMainCapitals London Paris Berlin Madrid Roma Should we expand business in this city dvar boolean x cities We want to expand business in Europe maximize sum c in cities c in EuropeanMainCapitals x c subject to We can expand business in 2 cities sum c in cities x c lt 2 Strine Eoyqoeiniclsel etess Ee iin eties s xIels iie execute for c in expanded_cities writeln We should expand business in c The result is We should expand business in Paris We s
4. parselnt field writeln Hello name doAction str substring start start length The function is typically either a script variable reference or a property access but it can be any expression the expression must yield a function value or an error is signalled Examples callbacks i arg Calls the function in callbacks i foo Error a string is not a function IBM ILOG OPL LANGUAGE REFERENCE MANUAL 187 Special keywords Special keyword syntax this When referenced in a method returns the current calling object when referenced in a constructor returns the object currently being initialized Otherwise returns the global object See this as a keyword for examples arguments Returns an array containing the arguments of the current function When used outside a function an error is signalled For example the following function returns the sum of all its arguments function sum var res 0 for var i 0 i lt arguments length i res rest arguments i return res The call sum 1 3 5 returns 9 188 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Special operators Special operator syntax new constructor argl typeof value delete variable delete value name delete value name expression expression2 IBM ILOG OPL LANGUAGE Calls the constructor with the given arguments and returns the created value Examples new Array new MyCar Ford 1975 The constructor is typica
5. the second range between parenthesis represents the domain of the interval size the third range represents the domain of the interval length the fourth and last range represents the domain of the interval end Note that the second range may be omitted in case the size and length of the interval variable are necessarily equal When the values are fixed the ranges min max are replaced by a single value For instance the following display represents a fixed interval variable of size 5 that is present starts at 10 and ends at 35 A1 1 10 5 25 gt 35 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 147 Unary constraints on interval variables 148 B M CP Optimizer provides constraints for modelling restrictions that an interval cannot start cannot end or cannot overlap a set of fixed dates Let amp denote a fixed interval and F an integer stepwise function Forbidden start The constraint forbidStart amp F states that whenever the interval is present it cannot start at a value t where F t 0 Forbidden end The constraint forbidEnd amp F states that whenever the interval is present it cannot end at a value t where F t 1 0 Forbidden extent The constraint forbidExtent amp F states that whenever the interval is present it cannot overlap a point t where F t 0 More formally forbidStart a F amp a 1 Vv F s a 0 forbidEnd a F a L v F e a 1 0 forbidErte
6. Any other non Boolean values yield true For example The 10 commandments indexOf 10 gt 4 The 10 commandments gt The 10 commandments if writeln True else writeln False if 123 writeln True else writeln False This displays False then True ILOG OPL LANGUAGE REFERENCE MANUAL 229 Boolean methods There is only one Boolean method Boolean method boolean toString Returns a string representing the Boolean value either true or false Example true toString gt true false toString gt false 230 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Logical operators The following Boolean operators are available l Note For C C programmers These operators are the same as in C and C Logical operators Sma Bet boolean Logical negation Examples true gt false false gt true exp amp amp exp2 Returns true if both Boolean expressions exp1 and exp2 are true Otherwise returns false If exp1 is false this expression immediately returns false without evaluating exp2 so any side effects of exp2 are not taken into account Examples true amp amp true gt true true amp amp false gt false false amp amp whatever gt false whatever is not evaluated exp exp2 Returns true if either Boolean expression exp1 or exp2 or both is true Otherwise returns false If exp1 is true this expression immediately returns t rue
7. M Logical constraints are one particular kind of discrete or numerical constraints OPL and CPLEX can translate logical constraints automatically into their transformed equivalent that the discrete MIP or continuous LP optimizers of IBM ILOG CPLEX can process efficiently This section describes all the available logical constraints as well as the logical expressions that can be used in logical constraints Logical constraints are available in constraint programming models without linearization For an example of how OPL uses logical constraints see Tutorial Using CPLEX logical constraints in the Language User s Manual In this section you will learn What are logical constraints What can be extracted from a model with logical constraints Which nonlinear expressions can be extracted Logical constraints for counting How are logical constraints extracted What are logical constraints For IBM ILOG CPLEX a logical constraint combines linear constraints by means of logical operators such as logical and logical or negation not conditional statements if then to express complex relations between linear constraints IBM ILOG CPLEX can also handle certain logical expressions appearing within a linear constraint One such logical expression is the minimum of a set of variables Another such logical expression is the absolute value of a variable There s more about logical expressions in Which non
8. Oils Oil from DBRead db SELECT name name capacity price octane lead FROM Oa i Data ai You can also write Gasolines from DBRead db SELECT name FROM GasData Gas from DBRead db SELECT name demand price octane lead FROM GasData LOG OPL LANGUAGE REFERENCE MANUAL 43 44 B M Oils from DBRead db SELECT name from OilData Oil from DBRead db SELECT name capacity price octane lead FROM OilData LOG OPL LANGUAGE REFERENCE MANUAL Initializing tuples You initialize tuples either by giving the list of the values of the various fields see Tuples or by listing the fields and values For example In the mod file you write tuple point Terrase Berrie erg isxonbiaic eile 5 of Seun IAs 5 of In the dat file you write pl lt y 1 x 2 gt p2 lt 2 1 gt As with arrays the delimiters lt and gt are replaced by lt and gt and the ordering of the pairs is not important OPL checks whether all fields are initialized exactly once The type of the fields can be arbitrary and the fields can contain arrays and sets Example 1 tuple Rectangle For example the following code lines declare a tuple with three fields the first is an integer and the other two are arrays of two points tuple Rectangle tie as abaua Sx fg 328 abiane libsa AIS Rectangle r execute writeln r A specific rectangle can be declared in the data file as e
9. Some classical cost functions in scheduling are earliness tardiness costs makespan and activity execution or non execution costs CP Optimizer generalizes these classical cost functions and provides a set of basic expressions that can be combined together this allows you to express a large spectrum of scheduling cost functions that can be efficiently exploited by the CP Optimizer search IBM ILOG OPL LANGUAGE REFERENCE MANUAL 139 For the description of the symbolic notation used throughout this section see Notations 140 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Piecewise linear and stepwise functions In CP Optimizer piecewise linear functions are typically used to model a known function of time for instance the cost incurred for completing an activity after a known date t Stepwise functions are typically used to model the efficiency of a resource over time A piecewise linear function F t is defined by a tuple F piecewise S T to vg where e S is a vector of n 1 change values s R for F e T is a vector of n values t R for F such that Vi l n 1 ti lt tiga AVi 1 n 2 ti lt ti42 e tp vo is a reference point of the function The function is defined everywhere on oo 00 as follows e F to vo e the slope F t of F on the segment oo t is equal to s4 e the slope F t of F on the segment f 00 is equal to s 44 e Vi 1 n 1 if ti tiz1 then the s
10. The above piecewise linear function has a fixed number of pieces but OPL also allows generic pieces The number of pieces may then depend on the input data as in piecewise i in 1 n slope i gt breakpoint i slope n 1 shiplo di gt This piecewise linear function is equivalent to slope 1 ship o d when ship o d lt breakpoint 1 is equivalent to slope 1 breakpoint 1 ki 7 i2 slope i breakpoint i breakpoint i 1 slope k ship o d breakpoint k 1 when breakpoint k 1 lt ship o d lt breakpoint k 1 lt k lt n and equivalent to ILOG OPL LANGUAGE REFERENCE MANUAL slope 1 breakpoint 1 a pH T slope i breakpoint i breakpoint i 1 slope n 1 ship o d breakpoint n otherwise Note that there may be several generic pieces in piecewise linear functions It is important to stress that breakpoints and slopes in piecewise linear functions must always be grounded by a point on the piecewise linear function Such a point called an anchor point uniquely defines the function Also the breakpoints must be strictly increasing To sort your model data for this purpose use sorted sets as explained in Sorted and ordered sets Section Piecewise linear programming in the Language User s Manual discusses piecewise linear functions applied to an inventory problem Discontinuous piecewise linear functions OPL also allows y
11. ILOG OPL LANGUAGE REFERENCE MANUAL pulse u v h h step u h 0 0 pulse a hpivh meh eae aes stepAtStart a h h stepAtStart a hmin Nmax a stepAtEnd a h h stepAtEnd a h min Pmax mE Elementary cumul function expressions More formally let U V E Zand h Z and we define the following particular functions of F ii 0 is the null function that is the function F such that Yt Z F t 0 pulse u v h is the function F such that F t h if t u v F t 0 otherwise step u h pulse u oo h The semantics of the elementary function expressions is listed in the following table together with the formal definition of their domain The function set Oa is equal to the singleton 0 ip dom a that is if interval variable a is possibly absent and equal to the empty set otherwise IBM ILOG OPL LANGUAGE REFERENCE MANUAL 159 160 B M Function expression Domain pulse u v h singleton step u h singleton stepAtStart a h stepAtStart a hmin stepAtE nd a h stepAtE nd a hmin hmar Elementary cumul function expressions A cumul function expression f is an expression built as the algebraical sum of the elementary function expressions in the table or negations More formally it is a construct of the form f gt amp fi where e 1 1 and f is an elementary function expression When all elementary function ex
12. Providence Boston wheat gt lt UPPOvanGenee iu mm OS ite lls meen eae Olen lt UPPOVinGenee A BOS CONN Sa ES lt Providence Boston wheat gt ILOG OPL LANGUAGE REFERENCE MANUAL B M lt Providence Mansfield wheat gt lt Providence Mansfield flour gt lt izxosiico ios EE rO ICENEAN lS Sizkosic ion AE OVIAENCE u EOE Note In dat files the separating comma is optional For strings without any special characters even the enclosing quotes are optional LOG OPL LANGUAGE REFERENCE MANUAL 39 Initializing arrays 40 B M You can initialize arrays Externally Internally In preprocessing instructions As generic arrays As generic indexed arrays Externally Arrays can be initialized by external data in which case the declaration has the form sie aber 0 fe Dereon a ar De Che Ge ere and the actual initialization is given in a data source which is a separate dat file in IBM ILOG OPL Listing values This is how arrays are initialized in most of the examples presented so far Multidimensional arrays in OPL are in fact arrays of arrays and must be initialized accordingly For example the declaration ox mol eal ies Sy Ine eyo ol hes Sl cose Wes eere real es ey a Il Osn 207 Sly Op S07 S0 l initializes a two dimensional array by giving initializations for the one dimensional arrays of its first dimension It is easy to see how to ge
13. The syntax of the actual queries may differ from one database system to another ILOG OPL LANGUAGE REFERENCE MANUAL Spreadsheet Input Output Describes how to connect an MS Excel spreadsheet read from it and write the results to the connected spreadsheet In this section The oilsheet example Explains spreadsheet input and output in the context of an oil spreadsheet Connection to a spreadsheet Explains how to connect OPL to a spreadsheet Reading from a spreadsheet Explains how to read from a spreadsheet from within OPL Writing to a spreadsheet Explains how to write to a spreadsheet from within OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 59 The oilsheet example 60 B M This section uses the 0ilSheet example to demonstrate operations with an MS Excel spreadsheet You can find this example in lt OPL_dir gt examples opl oil where lt OPL_dir gt is your installation directory Using spreadsheets through ODBC If you access spreadsheet data through an ODBC connection using a JDBC ODBC client the ODBC driver returns NULL if the data is not of the right type instead of reporting a specific data type error See http support microsoft com kb 194124 EN US for details ILOG OPL LANGUAGE REFERENCE MANUAL Connection to a spreadsheet The spreadsheet operations in OPL all refer to a spreadsheet connection The instruction ee Clee seal ey 27 SheetConnection sheet transport xls establishes
14. for strings 225 logical 231 numeric 214 precedence 182 shorthand 186 special 189 syntax 191 or logical constraint 122 ord OPL function 98 order for processing script blocks 72 ordered sets 29 special ordered sets not supported 29 ordered OPL keyword 130 REFERENCE MANUAL overflow and integer expressions 88 piecewise linear functions 91 discontinuous 93 pwlFunction 19 piecewise OPL keyword 91 preprocessing data 72 prev OPL function 98 prevc OPL function 98 processing order preprocessing items 72 prod OPL keyword 90 program unit and local variables scripting 196 properties accessing value of 185 for IBM ILOG Script arrays 236 for strings 221 pwlFunction OPL keyword 19 quotes 218 228 range float data type 23 ranges 22 and set expressions 98 reading from a database 55 from a spreadsheet 62 return IBM ILOG Script keyword 198 rows adding to a database 57 updating in a database 58 scheduling constraints in CP 126 scope hiding 134 scope of script variables 196 script variables declaration 196 inside a function definition 196 outside a function definition 196 reference to 184 scope 196 semi colon 174 set expressions 98 and ranges 98 construction 98 functions 98 setof OPL keyword 29 sets 29 allowed operations 29 and data consistency 69 and sparsity 48 IBM ILOG OPL LANGUAGE generic 48 initializing 47 of tuples initialization 38 ordered versus sorted 31 SheetConnect
15. key int startTime key int endTime int minRequirement int maxRequirement In Declaring a tuple using a set of keys nurses mod a shift is uniquely identified by the department name the date and start and end times all defined as key fields Initializing tuples You initialize tuples by giving the list of the values of the various fields as in Xone jo lt 2 Soe which initializes p x to 2 and p y to 3 See Initializing tuples for details ILOG OPL LANGUAGE REFERENCE MANUAL 27 28 B M Limitations on tuples When using tuples in your models you should be aware of various limitations Data types in tuples Not all data types are allowed inside tuples The limitations are given here Data types allowed in tuples Primitives int float string Tuples also known as subtuples Arrays with primitive items not string that is integer or float arrays Sets with primitive items that is integer float or string sets Data types not allowed in tuples Sets of tuples instances of IloTupleSet Arrays of strings tuples and tuple sets Multidimensional arrays Tuple indices and tuple patterns You cannot mix tuple indexes and patterns within the declaration and the use of decision expressions For example these code lines raise the following error message Data not consistent for xxx can not mix pattern and index between declaration of dexpr and instantiation Do not mix tuple indices a
16. multidimensional 25 of decision variables initialization 84 one dimensional 24 properties IBM ILOG Script 236 assert OPL keyword 71 processing order of statements 72 assertions 71 assignment operators 186 Boolean expressions 100 constraints 102 Boolean literals 227 conversion to 229 Boolean method toString 230 brackets delimiters in IBM ILOG Script for OPL 175 break IBM ILOG Script keyword 194 breakpoints in piecewise linear functions 91 Copyright IBM Corp 1987 2009 C Index building blocks 10 card OPL function 98 cardinality constraints 123 case sensitivity of the scripting language 177 collections not sorted in tuple sets with no keys 32 comments delimiters 176 compatibility constraints in CP 126 compound statements in IBM ILOG Script for OPL 175 conditional constraints 105 conditional expressions for float and integers 88 conditional statements in IBM ILOG Script for OPL 175 194 connection to a database 54 to a spreadsheet 61 consistency of model data 67 constants 213 dynamic collection 81 constraints basic 119 conditional 105 declaration 103 discrete 119 float 118 for compatibility CP 126 for filtering 106 labeling 107 logical CPLEX 122 logical for CP 126 nonlinear rejected by CPLEX 119 scheduling 126 specialized CP 127 259 260 string 120 types 117 using 103 constructors for IBM ILOG Script arrays 235 for IBM ILOG Script dat
17. this 188 242 244 tuple 26 union 98 var 196 with 69 labeled assertions 112 labeled constraints 107 last OPL function 98 lazy instantiation 72 limitations data types 28 literals 181 logical constraints definition and extraction 122 for CP 126 logical expressions 122 logical operators 231 loops in IBM ILOG Script 194 max OPL keyword 90 maxint OPL keyword 16 88 memory allocation and management and data initialization 50 memory consumption and multidimensional arrays 25 methods built in for objects 245 defining for objects 241 for arrays 237 for Booleans 230 IBM ILOG OPL LANGUAGE for dates 251 for functions 257 for numbers 211 for strings 222 for the null value 255 for the undefined value 256 min OPL keyword 90 models building 10 connecting to databases 52 54 conventions 10 efficiency 107 readability 133 134 multidimensional arrays 25 next OPL function 98 nextc OPL function 98 nonlinear constraints 119 nonlinear expressions in logical constraints 123 not logical constraint 122 Not A Number 209 null value 255 null IBM ILOG Script keyword 255 numbers 203 automatic conversion to 210 methods 211 numeric constants 213 numeric functions 212 numeric operators 214 objective function and decision variables 76 objects 239 constructor 243 octal numbers 208 one dimensional arrays 24 operators aggregate 90 assigning a value 186 for IBM ILOG Script dates 254
18. IBM ILOG OPL LANGUAGE REFERENCE MANUAL Date methods B M Date methods date getTime date setTime milliseconds date toLocaleString date toUTCString Returns or sets the number of milliseconds since 00 00 00 UTC January 1 1970 Example Suppose that the date d has been created with d new Date 3427 Then d getTime gt 3427 Returns a string representing the date in local time or in UTC repectively Example Suppose that the date d has been created with d new Date 3 12 1997 12 45 00 0 Then d toLocaleString gt 03 12 1997 12 45 00 000 d toUTCString gt 03 12 1997 10 45 00 000 ILOG OPL LANGUAGE REFERENCE MANUAL 251 Ea assuming a local time zone offset of 2 hours with respect to Greenwich Mean Time date getYear Returns or sets the year of date date setYear year date getMonth Returns or sets the month of date date setMonth month date getDate Returns or sets the day of date date setDate day date getHours Returns or sets the hours of date date setHours day date getMinutes Returns or sets the minutes of date date setMinutes minutes date getSeconds Returns or sets the seconds of date date setSeconds seconds date getMilliseconds Returns or sets the milliseconds of date date setMilliseconds millisecs date toString Returns the same value as date toLocaleString 252 IBM ILOG OPL LANGUAGE REFEREN
19. In the second case of course the expressions may contain decision variables Boolean expressions containing decision variables are called constraints and are subject to a number of restrictions for example float constraints must be linear piecewise linear or quadratic ILOG OPL LANGUAGE REFERENCE MANUAL Data and decision variable identifiers B M Since data and decision variable identifiers are the basic components of expressions we will review briefly here how they are used to build expressions If r is a tuple with a field capacity of type T then r capacity is an expression of type T If a is an n dimensional array of type T afte 1 e n is an expression of type T provided that e i is well typed For instance the excerpt int limit routes Gwar ink RE ans plr in routes ano E contains an expression limit r of type integer Indices of arrays can be complex expressions For instance the excerpt ahate saoti eies Soap range Flight 1 nbFlights string Employee dvar int crew Flight Employee in 0 1 Constraints 4 forall e in Employee PonesyiLil aia GL pidlowilaleinies gt 2 crew i e crew i 1 e crew i 2 e gt 1 contains an integer expression crew i 1 e whose first index is itself an integer expression ILOG OPL LANGUAGE REFERENCE MANUAL 87 Integer and float expressions 88 B M Integer expressions Integer expressions are constructed from integer
20. Nodes d Edge setEdges lt o d gt o d in Nodes edges o d 1 computes this sparse representation using a simple generic set It is of course possible to define generic arrays of sets For example the declaration tner akii sim Si5 5 A te EG ait Gl OR ES imecl a SS Oe initializes a 3 to 3 6 9 and a 4 to 4 8 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 49 Initialization and memory allocation In OPL the initialization mode you choose affects memory allocation Namely external initialization from a dat file while enabling a more modular design may have a significant impact on memory usage Internal initialization Internal data directly from the model file is initialized when first used This is also called lazy initialization Unused internal data elements are not allocated any memory In other words internal data is pulled from OPL as needed Example of lazy initialization int a 2 int b 2 ane a2 Veg int b2 2 b execute BVP arte bay writeln a2 writeln b2 assert a2 4 assert b2 6 External initialization In contrast data from a data file is initialized while the dat file is parsed and is allocated memory whether it is used by the model or not In other words external data is pushed to OPL 50 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Database initialization Describes how to connect to one or several relational databases how to
21. Quick Reference The numerical expressions are startEval endEval lengthEval and sizeEval and they allow evaluation of a piecewise linear function on a given bound of an interval As with integer expressions in the case of optional intervals an integer value dval must be specified which represents the value of the expression when the interval is absent If this value is omitted it is supposed to be 0 For the syntax and examples of the use of a numerical expression see endEval lengthEval sizeEval and startEval in the OPL Language Quick Reference Let amp denote a fixed interval variable The semantics of these expressions is shown in the table Expression Semantics aw sla if x a startOfla dval dval otherwise endOfia dval if z a oi otherwise l a if x a dval otherwise sz a if x a dval otherwise lengthOfia dval sizeOfia dval Fi s a if x a dval otherwise F e a if x a dval otherwise Fi i a if x a dval otherwise Fi sz a if x a dval otherwise startEval a F dval endEval a F dval lengthEval a F dval sizeEval a F dval Expression semantics Important The piecewise linear function Fused in eval expressions must be a semi convex function A semi convex function is a function such that if one draws a horizontal IBM ILOG OPL LANGUAGE REFERENCE MANUAL 153 line anywhere in the Cartesian plane corresponding to the graph of the function the set of x such that F x is
22. aa a a aa E a essa caatalehisadize ede andisnaseetasdiatiadeesse 133 Filtering in tuples Of Parameters cccececceeeeeeeeceeeeeeeseeeseneeeeeneneesseneneneneeseseeesesesenenensesssoeeneseeees 134 Schedulingws sacs ctr ieee E eee seeded clei ei cl ei 137 INtrOGUCHO Nis fesse ads tals aeteese enti Bagh airtel ansehen eta E AE 139 Piecewise linear and stepwise FUNCTIONS ee eeseeeeeeneeeeeneeetenneeeeeaeeeeeaaeetenneeeseaeeeeteneetesnneeteneeees 141 Interval Varables suites nt ee eater eo Ee ee ee a a eedi Unary constraints on interval variables Precedence constraints between interval VariableS eeseeeeseeeeeneeeeenneeeeeneeeseneeeeseneeeesnneerenaeees 149 Constraints on groups of interval VariableS ccceeceeeeeeeeeeeeeeeeeeeaeeeeeessaeeeeeseeeeeeesnaeesneeseaeeeeeeees 150 A logical constraint between interval variables preSenceOF escceeceseeeeeeeeeeeteneeeeeeseaeeteeeeenees 152 Expressions on interval Variables ceesseeeeseeeeeseeeeseeeeeaneeseneeeseaeeeesnaeesenaeeeseeeeeseaeeeesneeeeenaeees 153 Sequencing of interval VariableS cecceseeeeeeseeeeeeeeeeeeeeeeeeeeeaeeseaeeeeeseaeeseeeseaeeseeseaeeseeeeeeeeneeess 155 Cumulative finctions scien nats Sess died ote eee Miah nibaiadie nwt ea 158 Slate TUNCIONS a AwiStAd eeii iedee eaa e need tits Solna natn a 163 NOtatlons i224 EAA EA gate leita dinate dee cdt A A N 168 IBM ILOG Seript for OP Lea ices ccccessesccsceesicedeescctedscdiecteidd
23. absent intervals Important The intensity step function F should be a stepwise function with integer values and is not allowed to exceed the granularity 100 by default The following figure depicts an interval variable of size 14 with its intensity function A valid solution is represented where the interval starts at 10 and ends at 27 Indeed in this case 2 F t 1420 f Tat 142 42 G 100 a Intensity function 100 60 Sum 1420 100 0 20 30 size 14 10 27 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 145 146 B M OPL formulation Typically the problem structure will indicate if an interval can be optional or not and the keyword optional is used or not in the definition of the interval variable In the case where the optionality depends on input data you can specify a boolean parameter to the optionality field optional true being equivalent to optional and optional false being equivalent to the omission of optional A window StartMin End Max can be specified to restrict the position of the interval variable By default an interval variable will start after 0 and end before maxint 2 The fixed size or the size range for the interval is specified with the size keyword Note that these bounds are taken into account only when the interval variable is present in the final schedule that is they allow specifying conditional bounds on the interval variable would the interval be present in the fi
24. all IBM ILOG OPL V6 3 IBM ILOG OPL Language Reference Manual Copyright International Business Machines Corporation 1987 2009 US Government Users Restricted Rights Use duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp Copyright COPYRIGHT NOTICE Copyright International Business Machines Corporation 1987 2009 US Government Users Restricted Rights Use duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp Trademarks IBM the IBM logo ibm com WebSphere ILOG the ILOG design and CPLEX are trademarks or registered trademarks of International Business Machines Corp registered in many jurisdictions worldwide Other product and service names might be trademarks of IBM or other companies A current list of IBM trademarks is available on the Web at Copyright and trademark information at http Awww ibm com legal copytrade shtml Adobe the Adobe logo PostScript and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and or other countries Linux is a registered trademark of Linus Torvalds in the United States other countries or both Microsoft Windows Windows NT and the Windows logo are trademarks of Microsoft Corporation in the United States other countries or both Java and all Java based trademarks and logos are trademarks of Sun Microsystems Inc in the United States other count
25. and Infinity are used to indicate infinite values and overflows in arithmetic operations The global script variable Infinity contains the positive infinity The negative infinity can be computed using the negation operator Infinity Examples of Infinity 1 0 Infinity SAO IE LRE 1 oue tiie 0 Infinity Infinity true ILOG OPL LANGUAGE REFERENCE MANUAL 209 Automatic conversion to a number 210 B M When a function or a method which expects a number as one of its arguments is passed a nonnumeric value it tries to convert this value to a number using the following rules A string is parsed as a number literal If the string does not represent a valid number literal the conversion yields NaN The Boolean true yields the number 1 The Boolean false yields the number 0 The null value yields the number 0 A date yields the corresponding number of milliseconds since 00 00 00 UTC January 1 1970 For example if the Math sqrt function is passed a string this string is converted to the number it represents Mattie sicia ta eels mao Similarly operators which take numeric operands attempt to convert any nonnumeric operands to a number m3 x wan 1D For operators that can take both strings concatenation and numbers addition such as the conversion to a string takes precedence over the conversion to a number See Automatic conversion to a string In other words if at least one of the
26. asSet 1 10 initializes s to the finite set 1 2 10 Important The range 1 10 takes constant space while the set s takes space proportional to the number of elements in the range Functions for sets Functions over sets shows the functions available over sets These methods apply to all sets including sets of tuples and other complex sets In this section we assume that sistheset3 6 7 9 itemis an element of s nis an integer number ILOG OPL LANGUAGE REFERENCE MANUAL Functions over sets IG E EE OSESE ord card S returns the size of s that is the number of items ord S item returns the position of item in S Positions start at 0 and ord S item produces an execution error if item is notin S Example ord S 6 evaluates to 1 and ord S 9 to 3 The order of items in an explicit set is by order of appearance in the initialization and is implementation dependent when the sets are the results of a set operation first S returns the first item in s 3 in this example item S n returns the n th item in set S Counting starts from 0 This is equivalent to next first S n Example item S 1 6 last S returns the last item in s 9 in this example next S item returns the item in S that comes after item and produces an execution error if item is the last item Example next S 3 6 next S item n returns the n th next item next S item is equivalent to next S item
27. before 1970 If the argument cannot be converted to a number the third constructor syntax is used Examples new Date 0 gt adate representing 00 00 00 UTC January 1 1970 new Date 1000 60 60 24 20 gt a date representing twenty days after 00 00 00 UTC January 1 1970 new Date 1000 60 60 24 20 gt adate representing twenty days before 00 00 00 UTC January 1 1970 new Date string Returns the date described by string which must have the form month day year hour minute second msecond The date expressed in string is taken in local time Example new Date 12 25 1932 14 35 12 820 A date representing December 25th 1932 at 2 35 PM plus 12 seconds and 820 milliseconds local time new Date year Returns a new date representing the given year month day and so on taken in local time The arguments are month ear any integer day elk is month range 0 11 where 0 January 1 February and so on hours day range 1 31 default 1 minutes hours range 0 23 default 0 seconds mseconds inl minutes range 0 59 default 0 seconds range 0 59 default 0 mseconds range 0 999 defaults to 0 Examples new Date 1932 11 25 14 35 12 820 A date representing December 25th 1932 at 2 35 PM plus 12 seconds and 820 milliseconds local time IBM ILOG OPL LANGUAGE REFERENCE MANUAL 249 new Date 1932 11 25 A date representing December 25th 1932 at 00 00 local time 250
28. constants integer data integer decision variables and the traditional integer operators such as div mod or The operator div represents the integer division for example 8 div 3 2 and the operator mod or represents the integer remainder OPL also supports the function abs which returns the absolute value of its argument and the built in constant maxint which represents the largest integer representable in OPL Note that expressions involving large integers may produce overflow Example for int Note the result int a maxint 2 float b infinity 2 execute writeln a writeln b gives 2147483647 Infinity Most of these expressions such as or div are not available for constraints defined in CPLEX models but are available for CP models See also Constraints available in constraint programming Float expressions Float expressions are constructed from floats float data and variables as well as operators such as In addition OPL contains a float constant infinity to represent replace with sign infinity and a variety of float functions depicted in OPL functions in the Language Quick Reference Conditional expressions Conditional expressions are expressed like this condition thenExpr elseExpr where condition is a ground condition with no decision variable If condition is true the condition evaluates to thenExpr otherwise it evaluates to elseExpr ILOG OPL L
29. constraint alwaysNoState Specialized constraints The CP Optimizer engine also accepts some powerful combinatorial constraints known as specialized constraints For these constraints some powerful propagation algorithms are used to reduced the decision variable domains allDifferent constrains variables within a dvar array to all take different values allMinDistance constrains variables within a dvar array to all take values that are one to one different by at least a given gap inverse takes two arrays of integer variables that must be indexed by an integer and be one dimensional lex states that the first array of variables is less than or equal to the second array of variables in the alphabetical order pack represents some simple but powerful one dimensional packing constraint See the individual entries under OPL functions in Language Quick Reference for a complete description of each constraint IBM ILOG OPL LANGUAGE REFERENCE MANUAL 127 128 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Formal parameters Describes basic formal parameters tuples of parameters and filtering in tuples of parameters In this section Basic formal parameters Provides an overview of formal parameters in OPL Tuples of parameters Shows how tuples of formal parameters can be created in aggregate operators Filtering in tuples of parameters Explains the process of filtering inside tuples IBM ILOG OPL LANGUAGE REFERENCE MA
30. dynamically create arrays to be used in expressions or constraints is to explicitly define the array using the notation and including any variables or values into it Mixes are not allowed For example you can write forall i in R allDifferent x i yli zlil ILOG OPL LANGUAGE REFERENCE MANUAL Appending arrays You can also concatenate several arrays using the append function For example if you want to express that all variables from array x and array y are different you can use an allDifferent constraint applied to the appended arrays as in Appending arrays Appending arrays tekne Ci2 s range R 1 10 ever anki R 2n70 20 evar antay Ran 04 20 Manamize sum a an Ry ela eyes subject to allDifferent append all i in 1 2 x i all i in 4 6 yl il IBM ILOG OPL LANGUAGE REFERENCE MANUAL 83 Initialization of decision variable arrays The dynamic collection of decision variables allows you to dynamically initialize an array of decision variables The variables are then shared between the two arrays of variables Here is an example of what is possible ehyelie lige fash allio GRU alot IRE ebene aiae Wl S lt 1 ili 8 eiyan diae SRE ella AR ab ale RY fab ohyelie alii S72 Pal alot IR Sesh 9 dvar int y3 R aL Sse e ab aliot 2 4 dvar int y4 R sible Ile Se S4p Sho es ohyelie aiae WAS Mor mm appendia MLORITIR EE R S A 5 lt fal
31. expressions and Boolean expressions ILOG OPL LANGUAGE REFERENCE MANUAL 7 Constraints Specifies the constraints supported by OPL and discusses various subclasses of constraints to illustrate the support available for modeling combinatorial optimization applications Formal parameters Describes basic formal parameters tuples of parameters and filtering in tuples of parameters Scheduling Describes how to model scheduling problems in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL Models Describes the overall structure of OPL models and gives an example of a simple model In this section Building a model Describes the basic building blocks of OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 9 Building a model 10 B M Describes the primary elements of the OPL language and how they are used to build and optimization model The basic building blocks of OPL are integers floating point numbers identifiers strings and the keywords of the language Identifiers in OPL start with a letter or the underscore character _ and can contain only letters digits and the underscore character Note that letters in OPL are case sensitive Integers are sequences of digits possibly prefixed by a minus sign Floats can be described in decimal notation 3 4 or 2 5 or in scientific notation 3 5e 3 or 3 4e10 The OPL reserved words are listed in Part OPL keywords of the Language Quick Reference Comments in OPL are written in b
32. labeled as shown in Labeling constraints production mod you change possible existing constraint names in your models to labels Compare Deprecated constraint names with Labeling constraints production mod You do not need to previously declare the label as was the case with constraint names and you use the colon sign instead of the equal sign Deprecated constraint names constraint capacityCons r constraint demandCons p minimize sum p in Products insideCost p inside p outsideCost p outside p subjecte Eo forall r in Resources capacityCons r sum p in Products consumption p r inside p lt capacityl r fora PRPM Products demandCons p inside p outside p gt demand p IBM ILOG OPL LANGUAGE REFERENCE MANUAL 115 116 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Types of constraints Describes constraint classification depending on their operand type In this section Float constraints Describes float constraints and their use in OPL Discrete constraints Shows how to use discrete constraints within OPL String constraints Describes the use of string constraints in OPL Implicit constraints Explains that implicit constraints may imply infeasibility Logical constraints for CPLEX Describes the use of logical constraints in OPL Constraints available in constraint programming Lists the types of constraints available when doing constraint programming in OPL IBM ILOG OPL
33. pre Duration p pre More generally an expression a ia S where s is a set of tuples containing n fields can be replaced by a formal parameter expression Slee ea that contains n formal parameters Each time a tuple r is selected from S its fields are assigned to the corresponding formal parameters This functionality is often useful in producing more readable models IBM ILOG OPL LANGUAGE REFERENCE MANUAL 133 Filtering in tuples of parameters 134 B M OPL enables simple equality constraints to be factorized inside tuples which is important in obtaining more readable and efficient models In this context slicing refers to nested iterations with filtering conditions Consider for instance a transportation problem where products must be shipped from one set of cities to another set of cities The model may include a constraint specifying that the total shipments for all products transported along a connection may not exceed a specified limit This can be expressed by a constraint Explicit slicing forall c in connections sum lt p co gt in routes c co trans lt p c gt lt limit This constraint states that the total products shipped along each connection c is not greater than limit OPL must scan the entire set routes to select the tuples involving each connection In this example the expression c co is used to make slicing explicit The constraint would be stated equivalently as follows Impl
34. read from such databases using traditional SQL queries and to write the results back to the connected database In this section The oil database example Explains database initialization in the context of an oil database Supported databases Provides a reference of the databases supported by OPL Connection to a database Shows how to connect OPL to a database Reading from a database Explains the process of reading data from a database in OPL Writing to a database Explains the process of writing to a database from OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 51 The oil database example 52 B M The syntax for databases is valid only for data files with the extension dat not for model files with the extension mod This section uses the 0i1DB example to demonstrate operations with a Microsoft Access database You can find this example in lt OPL_dir gt examples opl oil where lt OPL_dir gt is your installation directory Working with databases 0i1DB dat DBConnection db access 0ilDB mdb Gasolines from DBRead db SELECT name FROM GasData Oils from DBRead db SELECT name FROM OilData GasData from DBRead db SELECT FROM GasData OilData from DBRead db SELECT FROM OilData MaxProduction 14000 ProdCost 4 DBExecute db drop table Result DBExecute db create table Result oil varchar 10 gas varchar 10 blend real ar real Result to DBUpdate db INSERT INTO Result
35. strictly increasing However in most cases the data supplied by a database or a dat file is not sorted in an increasing numeric or lexicographic order As a consequence you have to add complex and verbose scripting statements to sort the data To avoid these extra code lines the sorted property of sets enables you to sort data by specifying a single keyword as shown in the code extract below Piecewise linear function with sorted sets Writing piecewise linear functions becomes easier as one code line is sufficient instead of several dozens Piecewise linear function with sorted sets tuple Cost key int BreakPoint float Slope Sontced Cosic a8 Kil anos KO Boss lt Sp 4 595 lt 25 42 559 float lastSlope 3 5 dva rE TONERE minimize piecewise t in sS olope e t BreakPoint Tasto lopek x See also Piecewise linear functions LOG OPL LANGUAGE REFERENCE MANUAL 33 34 B M For more information See Data sources to learn about data initialization See Introduction to scripting of the Language User s Manual on how to set declarations ILOG OPL LANGUAGE REFERENCE MANUAL Data sources Describes data and database initialization spreadsheet input output data consistency and preprocessing In this section Data initialization Defines internal versus external initialization describes how to initialize arrays tuples and sets and discusses memory allocation aspects of data initialization Datab
36. the Object constructor For example the following program creates a new object stores it in the variable myCar and adds the properties name and year to it myCar new Object o contains no properties myCar name Ford myCar year 1985 Now myCar name gt Ford mycar year E 2985 240 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Defining methods B M Since a method is really a property which contains a function value defining a method simply consists in defining a regular function then assigning it to a property For example the following program adds a method start to the myCar object defined in the previous section function start _engine writeln vroom vroom myCar start start engine Now the expression myCar start will call the function defined as start_engine Note that the only reason for using a different name for the function and for the method is to avoid confusion we could have written fUNCtILGM Start 4 writeln vroom vroom myCar start start ILOG OPL LANGUAGE REFERENCE MANUAL 241 this as a keyword 242 B M Inside methods the this keyword can be used to reference the calling object For example the following program defines a method getName which returns the value of the name property of the calling object and adds this method to myCar function get _name return this name myCar getName get _name Inside constructors this re
37. to model a known function of time for instance the cost incurred for completing an activity after a known date Note that you must ensure that the array of values T i is sorted The meanings of the s T and v vectors are described in Piecewise linear and stepwise functions in the Language Reference Manual Syntax pwlrunction F piecewise z an 1 n S il gt Plil Sim 1 0 v0 pwlFunction F piecewise V 1 gt T 1 V n gt T n V n 1 aro meneron Ia fal ali Soo AECE SE oss ll occas IF Example int n 2 float objectiveforxequals0 300 float breakpoint 1 n 100 200 eloeic Silos cin ik lps S 2 ohygelie iie Sip maximize piecewise i in 1 n slope i gt breakpoint i slope n 1 0 objectiveforxequals0O x subject to true Piecewise linear functions are covered in detail in Piecewise linear and stepwise functions ILOG OPL LANGUAGE REFERENCE MANUAL 19 Stepwise functions 20 B M Shows how to declare stepwise functions in the OPL language Stepwise linear functions are typically used to model the efficiency of a resource over time A stepwise function is a special case of piecewise linear function where all slopes are equal to 0 and the domain and image of F are integer Note that you must ensure that the array of values T i is sorted Syntax stepFunctiion F stepwise i in 1 n V gt 2 i Vintl steprunection FS stepwise Vilieerili 5 Vinle
38. variable Decision variable types are references to objects whose exact nature depends on the underlying optimizer of a model A decision variable can be instantiated only in the context of a given model instance The purpose of an OPL model is to find values for the decision variables such that all constraints are satisfied or in optimization problems to find values for the variables that satisfy all constraints and optimize a specific objective function Variables in OPL are thus essentially decision variables and differ fundamentally from variables in programming languages such as Java and ILOG Script Note OPL decision variables are noted with the dvar keyword while the keyword var denotes ILOG Script variables A decision variable declaration in OPL specifies the type and set of possible values for the variable Once again decision variables can be of different types integer float and it is possible to define multidimensional arrays of decision variables The declaration dvar int transp Orig Dest in 0 100 declares a two dimensional array of integer variables The decision variables are constrained to take their values in the range 0 100 i e any solution to the model containing this declaration must assign values between 0 and 100 to these variables Note that all integer variables need a finite range in OPL Arrays of decision variables can be constructed using the same index sets as arrays of data In particular it is al
39. weheel s Kip sje aist joeiatiess Op the type check displays the error Aggregate set is currently not supported for filter expressions For an expression such as lanpe Oeae gt fat al alier ih gL n E Speitioh oee al Oe the type check displays the error Aggregate sum is currently not supported for filter expressions Several parameters can often be combined together to produce more compact statements For instance the declaration Aue s SUI ark ye CO e is equivalent to dine S Sia wat lal eimi SiH a tee ai Pare gs which is less readable The declaration dine S sei i daai Cate ito eee is equivalent to ime eet S eem ites Sa ete a als emp ci he These parameters can of course be subject to filtering conditions The excerpt foralil a a aj Is sit 8 a ali l 3 gt 0 4 gt is equivalent to IBM ILOG OPL LANGUAGE REFERENCE MANUAL 131 132 B M ROEA al stig iL 5 Aso oa abi ls cin 8 aLI alil j gt 0 Here is an even more compact form forall ordered i j in 1 n ei hall ap tole Indeed in many applications one is interested given a set S in stating filters or conditions over all pairs i j of elements of S satisfying i lt j in the ordering associated with S In this excerpt T S forall tordgeredi sr E Em Go meneners FOrad ITs DA Oy Eer SS OTA OASI lt Or Or E or the first forall line is equivalent to the second one and illust
40. which this index is to be contained some possible filters to filter out some of the enumerated combinations and a body here of the form x i j The variables or values in the resulting array follow the logical order of enumerating the index combinations as defined by the generators By default this dynamic array is indexed from 0 to numberOfElements 1 As some constraints make a particular usage of the index it may be interesting to define another indexing schema For this it is possible to dynamically define the range of the resulting array of variables by using the syntax minindex maxindex Finally it is possible to use as maxIndex to indicate that only the minIndex is defined the maxIndex will be set accordingly depending on the number of elements Here is a complete of usage of the syntax iousjalinve Cize alge ish 5 range R 1 n Ova ant R ao Be subject to allDifferent all i in R i 2 1 x i Obviously this is just a new possibility to define array of variables or values and in all the constraints and expressions that take arrays You can use either this new syntax or pass directly a named array When you pass a named array and indexes make sense in the constraint its indexer will be used to index the elements if it has one dimension only If it has two dimensions the indexer cannot be used ILOG OPL LANGUAGE REFERENCE MANUAL 81 Explicit arrays 82 B M Another useful syntax to
41. without evaluating exp2 so any side effects of exp2 are not taken into account Examples false true gt true false false gt false true whatever gt true whatever is not evaluated condition exp1 lf condition is true this expression returns exp1 otherwise it returns exp2 exp2 When condition is true the expression exp2 is not evaluated so any side effects it may contain are not taken into account Similarly when condition is false exp1 is not evaluated Examples true 3 14 whatever gt 3 14 false whatever Hello gt Hello IBM ILOG OPL LANGUAGE REFERENCE MANUAL 231 232 IBM ILOG OPL LANGUAGE REFERENCE MANUAL IBM ILOG Script arrays Array representation and functions In this section Introduction Provides an overview of the use of arrays in IBM ILOG Script Array constructor Provides a reference for array constructors in IBM ILOG Script Array properties Provides a reference of the properties of arrays Array methods Provides a reference of array methods IBM ILOG OPL LANGUAGE REFERENCE MANUAL 233 Introduction Arrays provide a way of manipulating ordered sets of values referenced through an index starting from zero 0 Unlike arrays in other languages IBM ILOG Script arrays do not have a fixed size and are automatically expanded as new elements are added For example in the following program an array is created empty and new elements are then added a new Arr
42. 1 A circular version of next nextC S item returns the first item in S if item is the last item Example nextc S 9 3 nextc S item n returns the n th circular next item nextc S item is equivalent to nextc S item 1 prev S item returns the item in s that comes before item and produces an execution error if item is the first item Example prev S 6 3 prev S item n returns the n th previous item prev S item is equivalent to prev S item 1 A circular version of prev prevc S item returns the last item in s if item is the first item Example prev S 3 9 prevc S item n returns the n th circular previous item prevc S item is equivalent to prevc S item 1 LOG OPL LANGUAGE REFERENCE MANUAL 99 Boolean expressions 100 B M Boolean expressions can have various operand types in OPL They are constructed in different ways from integer expressions using the traditional relational operators not equal gt gt lt and lt from float expressions using the same relational operators from string expressions and support the same operators as well For convenience OPL offers a range expression to express special combinations for constraints They are of the form a jail Se ja Jo where op1 and op2 are either of the relational operators lt or lt a and b are boundary expressions which need to be ground xis an expression Those e
43. 1 and string2 Examples Hello world Hello world When the operator is used to add a string to a nonstring value the nonstring value is first converted to a string Examples Your age is 23 gt Your age is 23 23 is your age gt 23 is your age The operator returns the Boolean true if stringl and string2 are identical and false otherwise Two strings are identical if they have the same length and contain the same sequence of characters The operator is the converse of Examples a string a string gt true a string another string gt false a string A STRING gt false a string a string gt false a string another string gt true When the operators and are used to compare a string with a number the string is first converted to a number and the two numbers are compared numerically Examples 12 12 gt false 12 12 gt true The operator lt returns true if string strictly precedes string2 lexicographically and false otherwise The operator lt returns true if string strictly precedes string2 lexicographically or is equal to it and false otherwise and so on Examples abc lt xyz gt true a lt abc gt true xyz lt abc gt false abc lt abc gt false abc gt xyz gt false a gt abc gt false xyz gt abc gt true Etc When one of these operators is used to compare a strin
44. 35 Array properties Array properties Sma eer SSCS array index lf index can be converted to a number between 0 and 2e32 2 see Automatic conversion to a number array index is the value of the index th element of the array Otherwise it is considered as a standard property access If this element has never been set nu11 is returned Example Suppose that the array a has been created with a new Array foo 12 true Then a 0 gt foo a 1 gt 12 a 2 gt true a 3 gt null a 1000 gt null When an element of an array is set beyond the current length of the array the array is automatically expanded a 1000 bar the array is automatically expanded Unlike other properties the numeric properties of an array are not listed by the for in statement array length The length of array which is the highest index of an element set in array plus one It is always included in 0 to 2e31 1 When a new element is set in the array and its index is greater or equal to the current array length the Length property is automatically increased Example Suppose that the array a has been created with a new Array a b c Then a length gt 3 a 100 bar a length gt 101 You can also change the length of an array by setting its length property a new Array a 4 foo a 9 bar a length gt 10 a length 5 a length gt 5 a 4 gt foo a 9 gt null 236 IBM ILOG OPL LANGUA
45. 5 84 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Expressions Describes data and decision variable identifiers integer and float expressions aggregate operators piecewise linear functions continuous and discontinuous set expressions and Boolean expressions In this section Usage of expressions Describes how to use expressions in OPL Data and decision variable identifiers Describes the use of identifiers within OPL expressions Integer and float expressions Describes the use of constants data decision variables and operators within OPL expressions Aggregate operators Describes the operators available for computing integer and float summations Piecewise linear functions Describes the use of piecewise linear functions in OPL Set expressions Describes the use of set expressions in OPL Boolean expressions Describes the use of Boolean expressions in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 85 Usage of expressions 86 B M Expressions are used in fundamentally different ways in OPL to specify items in generic arrays and sets described in this chapter to filter iterations see Formal parameters to state constraints over decision variables see Constraints In the first two cases the expressions do not contain decision variables since decision variables have no value at this stage of the computation These expressions are said to be ground and they are subject to almost no restrictions
46. 58 next 98 nextc 98 ord 98 over set expressions 98 prev 98 prevc 98 sign 93 functions numeric 212 generic sets 48 133 ground IBM ILOG OPL LANGUAGE breakpoints and slopes in piecewise linear functions 91 conditions in if then else statements 105 expressions and relations 86 hexadecimal numbers 207 IBM ILOG Script compound statements 175 default values of statements 199 syntax 173 identifiers 177 conventions 10 for data and variables 87 if IBM ILOG Script keyword 194 if then else conditional constraints 105 implication logical constraint 122 implicit slicing 134 indexed labels 110 infinity 209 infinity OPL keyword 17 88 initializing arrays 40 arrays of decision variables 84 data 37 38 set of tuples 38 sets 47 tuples 45 input output data to from a database 51 data to from a spreadsheet 59 integer constant maxint 16 integer expressions 88 integer ranges 22 integers 16 inter OPL keyword 98 internal data 38 and memory allocation 50 sets 47 item function 98 keys in tuple declarations 26 keywords arguments 188 assert 71 break 194 continue 194 DBExecute 57 DBRead 55 DBUpdate 58 diff 98 dvar 76 else 194 REFERENCE MANUAL 261 262 float 17 for 194 function 198 if 194 infinity 17 88 inter 98 max 90 maxint 88 min 90 null 255 ordered 130 piecewise 91 prod 90 return 198 setof 29 SheetConnection 61 SheetRead 62 special 188 static 198 string 18 sum 90 symdiff 98
47. 6 Expressions Of decision VariableS esceeesceeseneeeeeeneeeeeaeeeseaeeeeseneeeeeaeeeseneeeeseeeeeeeneesesaeeeneneeeeea 78 Dynamic collection of elements into ArrayS ee eee eeseeeeeneeeteneeeeeeneeeeeaeeeteneeeeteneeeesneeetenaeeeneneeeeeea 79 EXPRESSIONS cstc5 o a a a a a a a hiditviee eve dee ds St thet wie ea eae eee 85 Usage of epre SSON She T a a a ae E a teagead a a aa ra Ea aea cats EAr Eea AES AEEA NSA E 86 Data and decision variable identifiers eeeeseseeeeesneeeeeneeeteneeeeeeaeeeeeaeeeteeeeeteneeeeseneesenaeeeneneeeeeea 87 Integer and float ExPreSSiONS cesececeseeceeseceeeeeeeeeneeseeeeeeeeseenenesaesenenecensgseneseaeeneseeeeeneeeeseesenenes 88 Aggregate operators iei dined de ie ln needa atlas 90 Copyright IBM Corp 1987 2009 3 Piecewis linear TUNCHONS isror ane eea aaaea vith cuveiateees aa iar ideea idian 91 Set eXPrESSIONS arrra n a a e a a r e a a a e a a A R 98 zte lo ETEA SEE oIa AEE EEES 100 eola E EAE A AOSE AEE AE A E EE 101 Intr d ctioM iere ed Re deed ee Se aea a A a 102 Using Constraints Iruni a edie i eaten A E ee 103 Constraint aDeSe a a Aided deine AAR a a acta E SE 107 Types Of CONSTAINS smse ede veratrine a nae eee ee a el 117 FOrMal DaraMetersivss ia cesiind eile thi Seter ee le ee ete ee SIA ace 129 Basic formal parametersy cc c stsciscesupcchsicsauacesdaeguetetvansapassepennaldendecedaneadensashecadesepaviazseaagseatseheerease as 130 Tuples Of parameters aia a a
48. ANGUAGE REFERENCE MANUAL B M Examples int value Ine signvelue veluds0 Fl velvet OF int absValue value gt 0 value value See the numeric functions in OPL functions in the Language Quick Reference Counting expressions Among integer expressions there are also some combinatorial expressions For example you can use the count function to count the number of times a particular value appears in an array of decision variables You can use such an expression in modeling constraints only if the modeling constraints are part of a model that is solved by the CP Optimizer engine that is starting with the using CP statement The constraint states that in the array of variables x exactly three variables take the value 2 For more information see count in the Language Quick Reference ILOG OPL LANGUAGE REFERENCE MANUAL 89 Aggregate operators 90 B M Integer and float expressions can also be constructed using aggregate operators for computing summations sum products prod minima min and maxima max of a collection of related expressions For instance the excerpt it eapacwtiy Rout eet soa int minCap min r in Routes capacity r uses the aggregate operator min to compute the minimum value in array capacity The form of the formal parameters in these aggregate operators is very general and is discussed at length in Formal parameters For information on operators in gene
49. Basic constraints Basic discrete constraints are constructed from discrete data discrete variables and the arithmetic operators and functions defined in Expressions For instance the excerpt range r 1 5 ver koe Ih on COs avar ant 6b maximize obj subject to obj sum ordered i j in r abs x i x j forall ordered i j in r abs x i x j generates distance constraints between integer variables Note that the following code creates an error because IBM ILOG CPLEX does not accept non linear constraints aver ant x an 0 1000 minimize X subject to X mod 7 0 ILOG OPL LANGUAGE REFERENCE MANUAL 119 String constraints String constraints cannot be used on decision variables or added to the model to be solved They can only be used on indexers to filter aggregates see Filtering with constraints For example Velen be ae os ever antes am Oo Os minimize sum i in s x il subject to je neeulil al alioy 8 al Se ei ial ey 120 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Implicit constraints B M Implicit constraints are implied by operators For example iusjalinvey Cs dime Sieste over ioie o a aL Se maximize a x subject to x 5 makes the model infeasible even though GSi C125 Taie epa ae eyen aline 5 alin ils oP subject to X 5 is feasible ILOG OPL LANGUAGE REFERENCE MANUAL 121 Logical constraints for CPLEX 122 B
50. CE MANUAL Date functions B M Date functions Date UTC year month day hours minutes seconds mseconds J J Date parse string Returns a number representing the given date taken in UTC The arguments are year any integer month range 0 11 where 0 January 1 February and so on day range 1 31 default 1 hours range 0 59 default 0 minutes range 0 59 default 0 seconds range 0 59 default 0 mseconds range 0 999 default 0 Same as new Date string but the result is returned as a number rather than as a date object ILOG OPL LANGUAGE REFERENCE MANUAL 253 Date operators 254 B M There are no specific operators for dealing with dates but since numeric operators automatically convert their arguments to numbers these operators can be used to compute the time elapsed between two dates to compare dates or to add a given amount of time to a date For example datel date2 gt the number of milliseconds elapsed between datel and date2 datel lt date2 gt true if datel is before date2 false otherwise new Date date 10000 gt a date representing 10000 milliseconds after date The following program displays the number of milliseconds taken to execute the statement lt do something gt before new Date lt do something gt after new Date writeln Time for doing something after before milliseconds LOG OPL LANGUAGE REFERENCE MANUAL
51. CE MANUAL 13 14 B M ILOG OPL LANGUAGE REFERENCE MANUAL Basic data types Describes integers floats strings piecewise linear functions and stepwise functions in OPL In this section Integers Describes integers int in OPL Floats Describes floats float in OPL Strings Describes strings string in OPL Piecewise linear functions Describes piecewise linear functions pwlFunction in OPL Stepwise functions Describes stepwise functions stepFunction in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 15 Integers 16 B M Shows how to declare integers in the OPL language OPL contains the integer constant maxint which represents the largest positive integer available OPL provides the subset of the integers ranging from maxint to maxint asa basic data type A declaration of the form ane a 25 declares an integer i whose value is 25 The initialization of an integer can be specified by an expression For instance the declaration inh n Sy int size n n initializes size as the square of n Expressions are covered in detail in Expressions ILOG OPL LANGUAGE REFERENCE MANUAL Floats B M Shows how to declare floats in the OPL language OPL also provides a subset of the real numbers as the basic data type float The implementation of floats in OPL obeys the IEEE 754 standard for floating point arithmetic and the data type float in OPL uses double precision floati
52. GE REFERENCE MANUAL Array methods B M Array methods array join separator array sort function array reverse ILOG OPL Returns a string which contains the elements of the array converted to strings concatenated together and separated with separator If separator is omitted it is taken to be Elements which are not initialized are converted to the empty string See also the string method split Example Suppose that the array a has been created with a new Array foo 12 true Then a join gt foo 12 true a join gt foo 12 true Sorts the array The elements are sorted in place no new array is created If function is not provided array is sorted lexicographically Elements are compared by converting them to strings and using the lt operator With this order the number 20 would come before the number 5 since 20 lt 5 is true If function is supplied the array is sorted according to the return value of this function This function must take two arguments x and y and return 1 if x is smaller than y 0 if x is equal to y 1 if x is greater than y Example Suppose that the function compareLength is defined as function compareLength x y if x length lt y length return 1 else if x length y length return 0 else return 1 and that the array a has been created with a new Array giraffe rat brontosaurus Then a sort will reorder its elem
53. IBM ILOG CPLEX of new variables and constraints For more details on this transformation refer to the IBM ILOG CPLEX documentation ILOG OPL LANGUAGE REFERENCE MANUAL Constraints available in constraint programming This section lists the constraints and expressions available for OPL CP models See the OPL Language Quick Reference and the CP Optimizer User s Manual for further details Arithmetic constraints and expressions Logical constraints for CP Compatibility constraints Specialized constraints Arithmetic constraints and expressions The following arithmetic constraints and expressions are available for OPL CP models The references point to the OPL Language Quick Reference Arithmetic operations addition subtraction multiplication scalar products integer division floating point division modular arithmetic Arithmetic expressions for use in constraints standard deviation see standardDeviation minimum see min maximum see max counting see count absolute value see abs element or index see element Arithmetic constraints equal to not equal to strictly less than IBM ILOG OPL LANGUAGE REFERENCE MANUAL 125 126 B M strictly greater than less than or equal to greater than or equal to Logical constraints for CP The following logical constraints are available for OPL CP models Logical AND ia Logical OR EA fe B
54. Jo iia EO ductses InsideCost p Inside p OutsideCost p Outside p subject to forall r in Resources ctCapacity Sum die Produets Consumplioniplpe Insidelp lt Capacity elr forallip 2n Products ctDemand Inside p Outside p gt Demand p Labeling constraints production mod is equivalent to Stating constraints by means of an optimization instruction The only difference is that the constraint on the production capacity has been labeled ctCapacity and the constraint on the demand of products has been labeled ctDemand These labels can be used to display the data IBM ILOG OPL LANGUAGE REFERENCE MANUAL 109 Using indexed labels In some cases it is more convenient to use indexed labels Indexed labels enable you to control how a constraint is assigned to an array item Indexed labels on constraints t ransp2 mod shows that the transp2 mod example identifies constraints using indexed labels following this syntax constraint ctDemand Products ctDemand p Indexed labels on constraints transp2 mod Roma go iim Doctors a C aa Dest hol ctDemand p d Swin o wn heap jo Trans lt p o d gt Demand lt p d gt GuGapaciktyicme Oma Our CETS sum lt p o d gt in Routes Trans lt p o d gt lt Capacity A case where you need indexed labels to reduce memory overhead is when you use forall iterations with variable sizes as shown in forall iterations w
55. LANGUAGE REFERENCE MANUAL 117 Float constraints Float constraints are constraints involving float decision variables When modeled in OPL they are restricted to be linear or piecewise linear OPL has efficient algorithms for solving linear piecewise linear quadratic or logical constraints but in general these algorithms do not apply to nonlinear problems Note that the linearity requirement precludes the use of relations with variables in constraints and the use of non ground expressions as indices of float arrays In addition operators lt and gt are not allowed for float constraints However integers and integer variables may occur in a float constraint provided that the constraint remains linear or quadratic OPL supports all the expressions supported by CPLEX provided that the constraint is of one of the types described at the beginning of this paragraph 118 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Discrete constraints B M Discrete constraints are arbitrary Boolean expressions with integer operands possibly containing variables These constraints must be well typed but no restrictions are imposed on them It is however useful to review subclasses of these constraints to illustrate the functionalities of OPL MP models solved by the CPLEX engine can contain only basic constraints see the next section Basic constraints Logical constraints can be set by filtering of forall and sum constraints
56. M ILOG Script functions are regular values also known as first class values which can be manipulated like any other type of value They can be passed to functions returned by functions stored into script variables or into object properties and so on For example the function parseInt is a function value which is stored in the parseInt variable parseint gt a function value This function value can be for example assigned to another variable myFunction parseInt and then called through this variable my eume talons i 5 ae Function methods There is only one method of functions Function methods function toString Returns a string which contains some information about the function Examples foo substring toString primitive method substring eval toString primitive function eval IBM ILOG OPL LANGUAGE REFERENCE MANUAL 257 Miscellaneous functions Miscellaneous functions six eet CCS stop Stops the execution of the program at the current statement and if the debugger is enabled enters debug mode write arg Converts the arguments to strings and prints them to the current debug output argn The implementation depends on the application in which IBM ILOG Script is embedded The function writeln prints a newline at the end of the output while writeln arg1 write does not argn loadFile string Loads the script file whose path is string The path can b
57. NGUAGE REFERENCE MANUAL 245 246 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Dates Date representation and functions In this section Introduction Provides an overview of dates and date functions in IBM ILOG Script Date constructor Explains the different forms of the date constructor Date methods Provides a reference of date methods in IBM ILOG Script Date functions Provides a reference of date functions Date operators Explains the use of date operators in IBM ILOG Script IBM ILOG OPL LANGUAGE REFERENCE MANUAL 247 Introduction Date values provide a way of manipulating dates and times Dates can be best understood as internally represented by a number of milliseconds since 00 00 00 UTC January 1 1970 This number can be negative to express a date before 1970 Note For C C programmers Unlike dates manipulated by the standard C library date values are not limited to the range of 1970 to 2038 but span approximately 285 616 years before and after 1970 When converted to a number a date yields the number of milliseconds since 00 00 00 UTC January 1 1970 248 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Date constructor The date constructor has four distinct forms Date constructor new Date Returns the date representing the current time new Date milliseconds Returns the date representing 00 00 00 UTC January 1 1970 plus milliseconds milliseconds The argument can be negative to express a date
58. NUAL 129 Basic formal parameters 130 B M Formal parameters play a fundamental role in OPL they are used in aggregate operators generic sets and forall statements The simplest formal parameter has the form pins where p is the formal parameter and S is the set from which p takes its values The set S can be an integer range as in int n 6 hits Co NING alia aan AA a string set as in Sering PEroduc tsi Si Woes Weianele 3 float cost Products 12000 10000 float maxCost max p in Products cost p ora tuple set as in Terik WCaleakes af Hemise Viroacloin Yee ila js tuple Connection SEGREG string dest Connection Connections a Pardis Remmi nau Dare S AaRON Omen hry tloat costiconnectrons h le L000 2000 T float maxCost max r in connections cost r Ifyou need to filter the range of the formal parameters using conditions the formal parameter then takes the form p in S filtering condition and assigns to p all elements of S according to the filter applied For instance in the excerpt int n 8 ekvenas abge ehi an P Aae subject to eoe LIL at aa il ie oralig im tL g Ge a lt J ILOG OPL LANGUAGE REFERENCE MANUAL the constraint a i j gt 0 is modeled for all i and j such that 1 lt i lt j lt 8 Note OPL does not support aggregates in filter expressions For example For an expression such as aioe DOCERE SCE sat a aya Gee ik g
59. REFERENCE MANUAL 175 Comments Script supports two different styles of comments Single line comments A single line comment starts with and stops at the end of the line Example x 1 Increment x y y 1 then decrement y x Il Multiple line comments To span on more than one line comments must start with a and ends with a Nested multiple line comments are not allowed Example The following statement increments x x xtl The following statement decrements y y y A comment can be inserted here 1 176 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Identifiers Identifiers are used to name script variables and functions An identifier starts with either a letter or an underscore and is followed by a sequence of letters digits and underscores The following are examples of identifiers car x12 main_window BECO The language is case sensitive so that the uppercase letters A Z are distinct from the lowercase letters a z For example the identifiers car and Car are distinct IBM ILOG OPL LANGUAGE REFERENCE MANUAL 177 178 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Expressions in IBM ILOG Script Expressions are a combination of literals script variables special keywords and operators In this section Literals Explains the use of literals in IBM ILOG Script Operators Explains the use of and precedence of operators inIBM ILOG Script Syntax of dif
60. S OPO Op alon Ss Example 2 tuple Precedence The declaration IBM ILOG OPL LANGUAGE REFERENCE MANUAL 45 46 B M tuple Precedence string name String after defines a tuple in which the first field is a set item and the second field is a set of values A possible precedence can be declared as follows Precedence p lt al a2 a3 a4 a5 gt assuming that al a5 are strings You can also initialize tuples internally within the mod file If you choose to do so you cannot use the named tuple component syntax lt gt which is supported in dat files but not in mod files Components may be expressions and will be evaluated during initialization ILOG OPL LANGUAGE REFERENCE MANUAL Initializing sets You can initialize sets Externally Internally As generic sets Externally As stated in Initializing sets the simplest way to initialize a set is by listing its values explicitly in the dat file For example the declaration mod file tuple Precedence int before int after Precedence precedences fe lec Seal ies 3 7 precedences lt 1 2 gt lt 1 3 gt lt 3 4 gt initializes a set of tuples Internally You can also initialize sets internally in the mod file more precisely by using set expressions using previously defined sets and operations such as union intersection difference and symmetric difference The symmetric difference
61. SrOfint ag Over aiae aries es minimize X Subijiect stom forall i in setOfInt X gt i In the dat file DBconnection db oracle9 connectionString setOfInt from DBread db myQuery ILOG OPL LANGUAGE REFERENCE MANUAL Writing to a database Writing to a database to update it mostly follows the same lines Publishing results to a database is similar to parameterized data initialization Here is an example extracted from the oil code sample All database publishing requests are carried out during postprocessing if a solution is available Such requests are processed in the order declared in the dat file s If your RDMBS supports transactions every single publishing request is sent within its own transaction Adding rows To add rows 1 Write in the model file tuple result String oily SENGAJA float blend Eloek ae result Result ee lt Or Gi Bike Gl Kouichi pestle Ones O acennGacolmamesuals 2 Write in the data file DBExecute db drop table Result DBExecute db create table Result oil varchar 10 gas varchar 10 blend real a real Result to DBUpdate db INSERT INTO Result oil gas blend a VALUES In this example you use a DBExecute statement to send SQL DDL data definition language instructions to the Relational Database Management Server RDBMS a DBUpdate statement to modify the data see Updating existing rows More general
62. Started with the IDE You can access the slack and dual values for labeled constraints when a solution is available See the class IloConstraint in the Reference Manual of IBM ILOG Script Extensions for OPL Only labeled constraints are considered by the relaxation and conflict search process in infeasible models see Relaxing infeasible models in IDE Tutorials Cost However labeling constraints has a performance and memory cost which can be significant especially when a tuple pattern is used as the index Therefore you are encouraged to not use labels for large models or if you do at least use tuple indices instead of tuple patterns More precisely constraint labels are used in three cases IDE expand actions in slack and dual values with solutions and with relaxation and conflict detection If you do not need these three use cases you should get rid of the label to speed up the execution and lower memory consumption 108 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Labeling constraints To label a constraint Just type the character string you want followed by the colon sign before the constraint you want to label as shown in Labeling constraints production mod If you used to declare constraint names in your existing OPL models see Compatibility between constraint names and labels below Note A constraint label or name cannot start with a number Labeling constraints production mod minimize Stimi
63. Tiny Vintl 3 Ssteprunection Ft in stepwise 2 visl saa Js Example A declaration of the form stepFunction f stepwise 0 gt 3 2 assert ay assert 3 assert 3 i J 1 DA declares a stepwise function f Example Another example declaring the stepwise function F2 stepFunction F2 stepwise 0 gt 0 100 gt 20 60 gt 30 100 Loe ia Pe Oras execute writeln ii Write ly PAC 285 je Stepwise functions are covered in detail in Piecewise linear and stepwise functions ILOG OPL LANGUAGE REFERENCE MANUAL Data structures Describes how the basic data types can be combined using arrays tuples and sets to obtain complex data structures In this section Ranges Describes ranges in OPL Arrays Describes one dimensional arrays and multidimensional arrays Tuples Describes how to declare tuples use keys on tuples initialize tuples Also indicates the limitations to which tuples are subject Sets Gives a definition of sets a list of the operations allowed on sets and a few words on their initialization Sorted and ordered sets Shows how sets are sorted and ordered in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 21 Ranges 22 B M Integer ranges are fundamental in OPL since they are often used in arrays and variable declarations as well as in aggregate operators queries and quantifiers Declaring ranges To specify an integer range you give its lower an
64. a connection sheet to a spreadsheet named transport xls The connection sheet should be viewed as a handle on the spreadsheet Note that it is possible in OPL to connect to several spreadsheets within the same model Note that SheetConnection takes only one parameter and that you don t need to specify the full path to the spreadsheet name Relative paths are resolved using the current directory of dat files i Note In this section we often use the word spreadsheet for spreadsheet connection IBM ILOG OPL LANGUAGE REFERENCE MANUAL 61 Reading from a spreadsheet 62 B M In OPL spreadsheet ranges can be read into one or two dimensional arrays or sets For instance the instructions mod file string Gasolines tuple GasType float demand float price float octane float lead GasType gas Gasolines Pe Seve mile 7 SheetConnection sheet oilSheet xls Gasolines from SheetRead sheet gas A2 A4 gas from SheetRead sheet gas B2 E4 What data can be read from an Excel spreadsheet OPL opens a spreadsheet in read only mode to read data from it The types of data elements supported are sets with integers floats strings or tuples scalar integers floats or strings arrays with integers floats one or two dimensional strings or one dimensional tuples one or two dimensional arrays of simple types for such arrays the data must be formatted that i
65. a reference for the syntax of conditional statements in OPL Declaration of script variables Provides a reference for the syntax of script variable declarations in OPL Function definitions Provides a reference for the syntax of function definitions in OPL Default values Lists the default values used in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 193 Conditional statement 194 B M Loops Conditional statement syntax if expression statement else statement2 Loop syntax while expression statement for initialize condition update statement where condition and update are expressions and initialize is either an expression or has the form var variable expression ILOG OPL LAN Evaluate expression if it is true execute statement1 otherwise if statement2 is provided execute statement2 If expression gives a non Boolean value this value is converted to a Boolean value Examples if a b writeln They are equal else writeln They are not equal if s indexOf a lt 0 write The string s writeln doesn t contains the letter a Execute statement repeatedly as long as expression is true The test takes place before each execution of statement If expression gives a non Boolean value this value is converted to a Boolean value Examples while a a lt b a a 1 while s length r s charAt 0 r s s substring 1 Evaluat
66. able for an element depends on its type All elements can be read but modifications are possible only for primitive types int float string and primitive items of arrays and tuples See the intro to the Reference Manual of IBM ILOG Script Extensions for OPL about these limitations You can change the domain boundaries for decision variables as well as their priority in the preprocessing phase You can also use preprocessing to change CPLEX or CP Optimizer parameter settings see Changing option values in the Language User s Manual Elements of a range or constraint type are immutable Example Ferri inset stant range R 1 n ee JAI eos execute leona ae RURI ily Aao a A r 0 Instantiation and processing order Preprocessing items are processed by their category not in absolute declaration order Namely 1 data sources in the order in which they were added to the OPL model 2 all execute blocks and assert statements in declaration order For example if you write int sl 1 2 EEs aon S24 ab ab stich sale execute writeln s2 el vadd 3 gt ILOG OPL LANGUAGE REFERENCE MANUAL B M ILOG OPL writeln s1 s2 the result is aL 2 lL 2 Sp il Ay whereas if you write int sl 1 2 nE SA ae al bier lye execute writeln s2 Siada writeln s1 s2 the result is th 2 sp il 2 Shy Use the profiler feature to inspect the instantiation seq
67. ailable on cumulative function expressions IBM ILOG OPL LANGUAGE REFERENCE MANUAL 161 f lt hmax hmin lt f alwaysIn f u v hmin hmax alwaysIn f a hmin hmax Note that these constraints cannot be used in meta constraints The following expressions are available on cumulative functions dexpr int h heightAtStart a f dval dexpr int h heightAtEnd a f dval More information on these constraints and expressions is available in the OPL Language Quick Reference 142 IBM ILOG OPL LANGUAGE REFERENCE MANUAL State functions Some scheduling problems involve reasoning with resources whose state may change over time The state of the resource can change because of the scheduled activities or because of exogenous events yet some activities in the schedule may need a particular condition on the resource state to be true in order to execute For instance the temperature of an oven may change due to an activity that sets the oven temperature to a value v and a cooking activity may follow that requires the oven temperature to start at and maintain a temperature level v throughout its execution Furthermore the transition between two states is not always instantaneous and a transition time may be needed for the resource to switch from a state v to a state v CP Optimizer introduces the notion of state function which is used to describe the evolution of a given feature of the environment The possible evolut
68. allocation See Initialization and memory allocation for details Internally This initialization mode consists in initializing the data in the model file at the same time as it is declared Inline initializations can contain expressions to initialize data items such as stiches Wl its cSl Moria Jonr2p Jones Jos oroe Note If you choose to initialize data within a model file you will get an error message if you try to access it later by means of a scripting statement such as myData myArray inMod 1 2 Externally This initialization mode consists in specifying initialization subsequently as an OPL statement in a separate dat file see OPL Syntax in the Language Quick Reference This includes reading from a database as explained in Database initialization or from a spreadsheet as explained in Spreadsheet Input Output You declare external data using the ellipsis syntax However data initialization instructions cannot contain expressions since they are intended to specify data Data initialization instructions make it possible to specify sets of tuples in very compact ways Consider these types in a mod file Siereaiatey Wereoelbieie Si Vaelkeybhe Vp Wea ES Ia hp string City Providence Boston Mansfield tuple Ship string origy string dest See e Ship shipData and assume that the set of shipments is initialized externally in a separate dat file like this shipData lt
69. als using escape sequences Read The Black Bean Read The Black Bean Hello he said Hello he said c temp c tmp First line nSecond line nThird line First line Second line Third line When a string is converted to a number an attempt is made to parse it as a number literal If the string does not represent a valid number literal the conversion yields NaN IBM ILOG OPL LANGUAGE REFERENCE MANUAL 219 Automatic conversion to a string When a function or a method which expects a string as one of its arguments is passed a nonstring value this value is automatically converted to a string For example if the string method indexoOf is passed a number as its first argument this number is treated like its string representation Similarly operators which take string operands automatically convert nonstring operands to strings The conversion to a string uses the toString method of the given value All built in values have a toString method 2200 IBM ILOG OPL LANGUAGE REFERENCE MANUAL String properties There is a single read only string property String property string length Number of characters in string This is a read only property Examples abc length 3 length 0 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 221 String methods 222 B M Characters in a string are indexed from left to right The index of the first character in a string is 0 and the index of the l
70. amp denotes a fixed interval variable interval is absent amp L or interval is present amp s e Absent interval variables have special meaning Informally speaking an absent interval variable is not considered by any constraint or expression on interval variables it is involved in For example if an absent interval variable is used in a noOverlap constraint the constraint will behave as if the interval was never specified to the constraint If an absent interval variable a is used in a precedence constraint between interval variables a and b this constraint does not impact interval variable b Each constraint specifies how it handles absent interval variables The semantics of constraints defined over interval variables is described by the properties that fixed intervals must have in order the constraint to be true If a fixed interval amp is present and such that amp s e we will denote s amp its integer start value s e amp its integer end value e and amp its positive integer length defined as e amp s amp The presence status x amp will be equal to 1 For a fixed interval that is absent x amp 0 and the start end and length are undefined Until a solution is found it may not be known whether an interval will be present or not In this case we say that the interval is optional To be precise an interval is said to be absent when dom a L present when L dom a and optional in al
71. are therefore equivalent to Over diwe 2p Os maxints ever Lioet voi Outen hays Givens LE rr aia Osoi Decision variables in an array can be assigned item specific ranges as in dvar float transp o in Orig d in Dest in 0 cap o d which declares a two dimensional array of float variables where variable transp o d ranges over the set 0 cap o d LOG OPL LANGUAGE REFERENCE MANUAL 77 Expressions of decision variables 78 B M Shows how to declare and use decision variable expressions in the OPL language The keyword dexpr allows you to create reusable decision expressions Indeed if an expression has a particular meaning in terms of the original problem writing it as a decision expression dexpr makes the model more readable For example the scalableWarehouse mod example expresses the total fixed costs asa decision expression dexpr int TotalFixedCost sum w in Warehouses Fixed Open w dexpr float TotalSupplyCost sum w in Warehouses s in Stores SupplyCost s w Supply s w This way the two total cost expressions defined are shown in the Problem Browser along with their value You can also use arrays of decision expressions For example dexpr int slack i in r x i ylil This array is handled efficiently as only the definition is kept Not all expressions for each values of the indexes are created As a consequence you cannot change the definition of the dexpr for a p
72. art algorithms for linear programming mathematical integer programming and quadratic programming Within the IBM ILOG OPL product OPL as a modeling language has been redesigned to better accommodate IBM ILOG Script its associated script language 6 IBM ILOG OPL LANGUAGE REFERENCE MANUAL B M OPL the modeling language Presents the modeling language of IBM ILOG OPL namely the overall structure of OPL models the basic modeling concepts how data can be initialized internally as it is declared or externally in a dat file how to connect to read from and write to databases and spreadsheets expressions and relations constraints and formal parameters In this section Models Describes the overall structure of OPL models and gives an example of a simple model Data types Describes basic data types and data structures available for modeling data in OPL Data sources Describes data and database initialization spreadsheet input output data consistency and preprocessing Decision types Variables in an OPL application are decision variables dvar OPL also supports decision expressions that is expressions that enable you to reuse decision variables dexpr A specific syntax is available in OPL to dynamically collect elements into arrays Expressions Describes data and decision variable identifiers integer and float expressions aggregate operators piecewise linear functions continuous and discontinuous set
73. articular element of the array Using decision expressions is particularly useful and recommended if you plan to write objectives to be used with ILOG ODM Please refer to the ODM documentation ILOG OPL LANGUAGE REFERENCE MANUAL Dynamic collection of elements into arrays Discusses the all syntax explicit arrays appending arrays and dynamic initialization of decision variable arrays In this section Introduction Provides an overview of how elements are collected into arrays in OPL The all syntax Shows how to use the all syntax in the OPL language Explicit arrays Describes explicit arrays in OPL Appending arrays Shows how to concatenate arrays in OPL Initialization of decision variable arrays Shows how to initialize your decision variable arrays in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 79 Introduction Some expressions such as count and constraints such as allDifferent need arrays of variables or constants to be created In some models these expressions or constraints can be used in an aggregate statement for example in a forall statement and the exact content of the arrays depends on the iteration 80 IBM ILOG OPL LANGUAGE REFERENCE MANUAL The all syntax B M Then the all syntax allows you to dynamically collect some decision variables or constants into an array The syntax is similar to sum and forall it contains a series of possible generators an index and a set or a range in
74. ase initialization Describes how to connect to one or several relational databases how to read from such databases using traditional SQL queries and to write the results back to the connected database Spreadsheet Input Output Describes how to connect an MS Excel spreadsheet read from it and write the results to the connected spreadsheet Data consistency Defines the purpose of data consistency and describes data membership and assertions as ways to ensure consistency Preprocessing data Provides an overview of preprocessing operations in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 35 36 B M ILOG OPL LANGUAGE REFERENCE MANUAL Data initialization Defines internal versus external initialization describes how to initialize arrays tuples and sets and discusses memory allocation aspects of data initialization In this section Internal vs external initialization Defines these two kinds of data initialization Initializing arrays Describes the various ways in which you can initialize arrays Initializing tuples Describes the two ways of initializing tuples Initializing sets Describes the three ways of initializing sets Initialization and memory allocation Describes how memory is allocated to data initialization IBM ILOG OPL LANGUAGE REFERENCE MANUAL 37 Internal vs external initialization 38 B M In OPL you can initialize data internally or externally Your choice affects memory
75. ast character is string length 1 String methods string charAt index string charCodeAt index string indexOf substring index string lastIndexOf substring index string toLowerCase at the index end 1 If end is omitted the tail of string is returned Examples 0123456 substring 0 3 012 0123456 substring 2 4 23 0123456 substring 2 23456 Returns a one character string containing the character at the specified index of string If index is out of range an empty string is returned Examples abcdef charAt 0 a abcdef charAt 3 d abcdef charAt 100 Returns the ASCII code of the character at the specified index of string If index is out of range returns NaN Examples abcdef charCodeAt 0 97 abcdef charCodeAt 3 100 abcdef charCodeAt 100 NaN Returns the index in string of the first occurrence of substring String is searched starting at index If index is omitted st ring is searched from the beginning This method returns 1 if substring is not found Examples abcdabcd indexOf bc 1 abcdabcd indexOf bc 1 1 abcdabcd indexOf bc 2 5 abcdabcd indexOf bc 10 1 abcdabcd indexOf foo 1 abcdabcd indexOf BC 1 Returns the index in string of the last occurrence of substring when string is searched backwards starting at index If index is omitted string is searched from the end This method returns 1 if substring is not found Examp
76. atement the indexing set and array cells are initialized at the same time Note OPL does not parse the query it simply sends the string to the database system that has full responsibility for handling it As a consequence the syntax and the semantics of these queries are outside the scope of this book and users should consult the appropriate database manual for more information It is also possible to implement parameterized queries in OPL for example IBM ILOG OPL LANGUAGE REFERENCE MANUAL 55 56 B M Oils from DBRead db SELECT name FROM OilData WHERE quality gt oilQuality where oilQuality is any scalar OPL data element already initialized and whose type is expected in the SQL query In this case 0ilQuality should be a numeric type for example an integer Note Despite standardization Oracle does not support the question mark as a variable identifier Use lt parameter number gt instead Examples are 1 arg etc SQL encryption In OPL 3 Because all database instructions were in the model file the SQL statements were encrypted as well when the model was compiled In OPL4 and later To do the same in OPL 4 x where you write database instructions in data files you can define literal strings inside the model file which will be compiled and use them in the data file like this In the mod file string connectionString scott tiger TEST string myQuery select id from table Aner S
77. ay Create an empty array a 0 first Set the element 0 a l second Set the element 1 a 2 third Set the element 2 Arrays are internally represented as sparse objects which means that an array where only the element 0 and the element 10000 have been set occupies just enough memory to store these two elements not the 9999 which are between 0 and 10000 234 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Array constructor The array constructor has two distinct forms Array constructor new Array ength Returns a new array of length length with its elements from 0 to length 1 set to null If Length is not a number and its conversion to a number yields NaN the second syntax is used Examples new Array 12 gt an array a with length 12 and a 0 to a 11 containing null new Array 5 gt an array a with length 5 and a 0 to a 4 containing null new Array foo see second syntax new Array element1 Returns a new array a of length n with a 0 containing element1 a 1 elementn containing element2 and so on If no argument is given that is n 0 an empty array is created If n 1 and element1 is a number or can be converted to a number the first syntax is used Examples new Array 327 hello world gt an array a of length 2 with a 0 327 and a 1 hello world new Array gt an array with length 0 new Array 327 see first syntax IBM ILOG OPL LANGUAGE REFERENCE MANUAL 2
78. be defined as a set of integer triples see noOverlap in the OPL Language Quick Reference For the syntax and examples of the other constraints available on an interval sequence variable see first last prev and before in the OPL Language Quick Reference Note that there are similarly named constraints available for set operations in OPL Note that none of the constraints mentioned in this section can be used in a meta constraint IBM ILOG OPL LANGUAGE REFERENCE MANUAL 157 Cumulative functions 158 B M In scheduling problems involving cumulative resources also known as renewable resources the cumulated usage of the resource by the activities is usually represented by a function of time An activity usually increases the cumulated resource usage function at its start time and decreases it when it releases the resource at its end time pulse function For resources that can be produced and consumed by activities for instance the content of an inventory or a tank the resource level can also be described as a function of time production activities will increase the resource level whereas consuming activities will decrease it In these type of problems the cumulated contribution of activities on the resource can be represented by a function of time and constraints can be modeled on this function for instance a maximal or a Safety level CP Optimizer introduces the notion of the cumulative function expression which is a funct
79. below the line is empty or forms a single interval Some examples of semi convex piecewise linear functions are depicted in the following figure cost cost cost cost cost cost x x x x x x Example of semi convex piecewise linear functions 154 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Sequencing of interval variables An interval sequence variable is defined on a set of interval variables A Informally speaking the value of an interval sequence variable represents a total ordering of the interval variables of A Note that any absent interval variables are not considered in the ordering More formally an interval sequence variable p on a set interval variables A represents a decision variable whose possible values are all the permutations of the intervals of A Let A be a set of fixed intervals and n denote the cardinality of A A permutation 7 of A is a function 7 A 1 U 1 n such that if we denote length 7 a A x a then the number ot present intervals l Va A z a amp n a L 2 Va A x a gt x a lt length z 3 Va b E A x a Ax b Aa b gt x a m b Note that the sequence alone does not enforce any constraint on the relative position of intervals end points For instance an interval variable a could be sequenced before an interval variable b in a sequence p without any impact on the relative position between the start end points of a and b a could still be fixed to start a
80. constraint In fact ranges containing logical expressions can in turn appear in logical constraints It is important to note here that only linear constraints can appear as arguments of logical constraints extracted by IBM ILOG CPLEX That is quadratic constraints are not handled in logical constraints Similarly quadratic terms can not appear as arguments of logical expressions such as min max abs and piecewise Logical constraints for counting In many cases it is even unnecessary to allocate binary variables explicitly in order to gain the benefit of linear constraints within logical expressions For example optimizing how many items appear in a solution is often an issue in practical problems Questions of counting how many can be represented formally as cardinality constraints Suppose that your application includes three variables each representing a quantity of one of three products and assume further that a good solution to the problem means that the quantity of at least IBM ILOG OPL LANGUAGE REFERENCE MANUAL 123 124 B M two of the three products must be greater than 20 Then you can represent that idea in your application like this CeO 2 20 oe 20 Gel b 20 S 23 How are logical constraints extracted Logical constraints are transformed automatically into equivalent linear formulations when they are extracted by an IBM ILOG CPLEX algorithm This transformation involves automatic creation by
81. d and the constraint does not appear in the Problem Browser Constraint label within forall statement range Toe range r2 I H Ww dwar siete ALETE ZI akist Ou Se Constraints 7 cig se ueeubil ai aesl Eeen akiot 1e2 d lt Lab a lt aa Labels and variable size indexer Constraint labels with variable size indexer are forbidden For example this model generates an error message tuple RangeTuple dite eS wie JA SEENI RangeTuple RT lt l 2 bla gt IBM ILOG OPL LANGUAGE REFERENCE MANUAL 113 114 B M minimize 1 subject to COREL oil jo2 JOSS akio RA forali Cs inde rangeLabel 1 1 Write the following code instead tuple RangeTuple gave aed aiae Bs SEELE ey RangeTuple RT lt l 2 bla gt int s 1 2 constraint rangeLabel RT s minimize 1 subject to RonecuLik Koil jaar jose aliet 1380 Ota pi rangeLabel lt pl p2 p3 gt i 4 Note the difference in rangeLabel LOG OPL LANGUAGE REFERENCE MANUAL Compatibility between constraint names and labels OPL 4 x constraint names are deprecated in OPL 5 0 and later They are still supported to maintain the compatibility of your OPL 4 x models and automatically implemented as labels internally but they will be removed in future versions of IBM ILOG OPL It is therefore strongly recommended that you label constraints that are currently neither named nor
82. d upper bounds as in range Rows 1 10 which declares the range value 1 10 The lower and upper bounds can also be given by expressions as in inten By range Rows nt1 2 n 1 Once a range has been defined you can use it as an array indexer Whenever a range is empty i e its upper bound is less than its lower bound it is automatically normalized to 0 1 in other words all empty ranges are equal The range declaration An integer range is typically used as an array index in an array initialization expression range R 1 100 int A R A is an array of 100 integers as an iteration range range R 1 100 Foral a alot R q element of a loop as the domain of an integer decision variable ohyfetie ae al alot RE ILOG OPL LANGUAGE REFERENCE MANUAL The range float declaration A range float data type consists of a couple of float values specifying an interval It is typically used as the domain of a floating point decision variable range float X 1 0 100 0 eena EBOST 50 LN 28 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 23 Arrays Arrays are fundamental in many applications One dimensional arrays One dimensional arrays are the simplest arrays in OPL and vary according to the type of their elements and index sets A declaration of the form shite libs a lO 20 SO 20 declares an array of four integers a 1 a 4 whose values are 10 20 30 and 40 It is of cou
83. declaration stints Elks oll is oSl cect declares a two dimensional array a indexed by two integer ranges Indexed sets of different types can of course be combined as in aiinte 2 DEW ks 3 coos which is a two dimensional array whose elements are of the form a Monday 1 It is interesting to contrast multidimensional and one dimensional arrays of tuples Consider the declaration string Warehouses string Customers int transp Warehouses Customers that declares a two dimensional array transp This array may represent the units shipped from a warehouse to acustomer In large scale applications it is likely that a given warehouse delivers only to a subset of the customers The array transp is thus likely to be sparse i e it will contain many zero values The sparsity can be exploited by declarations of the form string Warehouses Sering Customers er tuple Route SEIEN Ge mabao Cie Route routes int transp routes This declaration specifies a set routes that contains only the relevant pairs warehouse customer The array transp can then be indexed by this set exploiting the sparsity present in the application It should be clear that for large scale applications this approach leads to substantial reductions in memory consumption You can initialize arrays by listing its values as in most of the examples presented so far See Initializing arrays As g
84. e on range Tools 1 nbTools range Operations 1 nbOps int Duration Operations int RequiredTool Operations dvar interval op o in Operations size Duration o pupilem tripleti abiete iwlkile aiiste tell2e alicke weUboes jhe I aolewe i UWieeNolsiicalon Sanaa Senes e oA ager roede jhe stateFunction machineTool with Transition constraints forall o in Operations ILOG OPL LANGUAGE REFERENCE MANUAL alwaysEqual machineTool op o RequiredTool o IBM ILOG OPL LANGUAGE REFERENCE MANUAL 167 Notations The main notations used throughout the scheduling section are defined here Vectors are denoted by capital letters for example Y The size of a vector Y is denoted Y If n Y the vector is denoted Y y Vy interval variable as boolean expression execution status of a integer expression start end length of a integer expression vector of interval variables interval sequence variable fo cumul function expression state function fixed interval P interval variable permutation Pee eee delay of a precedence vetar OF moam vtae of loni N or of i gers piecewise linear function R R vector of cumul function expressions Po type of interval a in sequence p integer matrix transition distance matrix set of functions set of all functions f Z Z 168 IBM ILOG OPL LANGUAGE REFERENCE MANUAL IBM ILOG Script for OPL Describes the structure and bui
85. e 2 0000 x 2 0000 signx 1 0000 y 2 0000 signy 1 0000 Figure The discontinuous piecewise linear function sign shows that the value of the sign function at the breakpoint is either 1 on the left hand slope or 1 on the right hand slope 94 IBM ILOG OPL LANGUAGE REFERENCE MANUAL B M For example this model takes this into account and sets the constraint x y on both values dvar Lloat ay Gwar Lloat sigqnuxy dvar float y dvar float signy maximize signx signy subject to x y signx piecewise 0 gt 0 2 gt 0 0 1 1 signy piecewise 0 gt 0 2 gt 0 0 1 1 This model solves with the following output Final solution with objective 2 signx 1 signy 1 x 0 y 0 Example 2 discontinuous cost The following piecewise function pilecewise 0 S10 S gt 10y 0 S207 S s20 0 represents a discontinuous cost Sy LON wisisligg This function is illustrated in Figure Discontinuous costs for the values summarized in Table A discontinuous cost function LOG OPL LANGUAGE REFERENCE MANUAL 95 96 B M A discontinuous cost function e p 10 20 unit Discontinuous costs A different behavior with the CP Optimizer engine Consider the following model l asing Cp Over aoe z in ee O dyar Int Ssignx hwnd aloe YF alia SILO LO ILOG OPL LANGUAGE REFERENCE MANUAL ovar int signy maximize signx signy SuUDJEc tco x y signx pi
86. e either absolute or relative If this path does not designate an existing file the file is looked up using a method which depends on the application in which the script is embedded typically a file with the name string is searched for in a list of directories specified in the application setup eval string Executes string as a program and returns the value of the last evaluated expression The program in string can use all the features of the language except that it cannot define functions in other words the function statement is not allowed in string Examples eval 2 3 gt 6 eval var i 0 for var j 0 j lt 100 j i i j i gt 4950 n 25 eval Math sqrt n gt 5 eval function foo x return x 1 gt error fail Stops the execution of the scripting block at the current statement reports an error and goes on Example execute b1 writeln A fail writeln B execute b2 writeln C gives AC as the output and reports an error line 4 Scripting runtime error fail called 258 IBM ILOG OPL LANGUAGE REFERENCE MANUAL abs OPL function 88 accessing value of an IBM ILOG Script property 185 accessing named ranges in Excel 62 aggregate operators 90 133 all OPL keyword 81 and logical constraint 122 arguments IBM ILOG Script keyword 188 arrays appending 83 constructor IBM ILOG Script 235 explicit 82 in IBM ILOG Script 233 initialization 40 methods IBM ILOG Script 237
87. e initialize once if present Its value is ignored If it has the form var variable expression then variable is declared as a local script variable and initialized as in the var statement Then execute statement repeatedly as long as condition is true If condition is omitted it is taken to be true which results in an infinite loop If condition gives a non Boolean value this value is converted to a Boolean value If present update is evaluated at each pass through the loop after statement and before condition Its value is ignored Example GUAGE REFERENCE MANUAL B M for var variable in expression statement break continue ILOG OPL LA for var i 0 i lt a length i sum sum afi prod prod ali Iterate over the properties of the value of expression for each property variable is set to a string representing this property and statement is executed once If the var keyword is present variable is declared as a local script variable as with the var statement For example the following function takes an arbitrary value and displays all its properties and their values function printProperties v for var p in v writeln p gt v p Properties listed by the for in statement include method properties which are merely regular properties whose value is a function value For example the call printProperties foo would display length gt 3 toString gt primitive
88. e of compound statements in OPL syntax Comments Explains the syntax of comments in OPL Identifiers Shows how to use identifies in OPL syntax IBM ILOG OPL LANGUAGE REFERENCE MANUAL 173 General A script comprises a sequence of statements An expression can also be used whenever a statement is expected in which case its value is ignored and only its side effect is taken into account You can put multiple statements or expressions on a single line if you separate them with a semi colon for example the following two scripts are equivalent Scriptt writeln Hello world x x 1 aag des gt lO mazee AR Te Script2s mel eE N REL eNA se ala e oe a Oy esa o Toake 174 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Compound statements B M A compound statement is a sequence of statements and expressions enclosed in curly brackets It can be used to perform multiple tasks whenever a single statement is expected for example in the following conditional statement the three statements and expressions in curly brackets are executed when the condition a gt b is true nkie ah gt Jo fl var c a a b bec The last statement or expression before a closing curly bracket does not need to be followed by a semicolon even if it is on the same line For example the following program is syntactically correct and is equivalent to the previous one aae Ge So 250 a ee Ser a ieee aby eee aa ILOG OPL LANGUAGE
89. e the with syntax will detect that the statement ink aedes 1 5 73 is not consistent with the statement IBM ILOG OPL LANGUAGE REFERENCE MANUAL 69 70 B M with origin in nodes destination in nodes frail AS lt S If you write Data found consistent keyword with the initialization of the set arcs1 will work properly because the with syntax will find that the statement Gintc mocks il 5 Ts is consistent with the statement with origin in nodes destination in nodes teil 5S Sor TS Initializing tuple sets referring to other sets To initialize tuple sets that refer to other sets with keys for data consistency you must use initialization expressions that provide only those key values as shown in Initializing tuple sets referring to other sets This is true if you initialize those tuple sets as internal data or as external data in dat files databases or spreadsheets Initializing tuple sets referring to other sets tuple node key int node_id SEINIR SErInNgRCOUNEEV node nodes lt 1 Paris France gt lt 5 Madrid Spain gt lt 7 New York USA gt r tuple arc node origin node destination arc arcsl with origin in nodes destination in nodes execute writeln arcs1 J ILOG OPL LANGUAGE REFERENCE MANUAL Assertions OPL provides assertions to verify the consistency of the model data This functionality enables you to avoid wrong resul
90. eEnd endBeforeStart startAtEnd startAtStart startBeforeEnd gt gt gt gt gt gt o startBeforeStart ILOG OPL LANGUAGE REFERENCE MANUAL 149 Constraints on groups of interval variables 150 B M The main purpose of a group constraint is to encapsulate a group of interval variables into one effective higher level interval Three interval grouping constraints are available span alternative and synchronize Span constraint The constraint span a bj bp states that the interval a spans over all present intervals from the set b1 bn That is interval a starts together with the first present interval from b1 bn and ends together with the last one Alternative constraint The constraint alternative a b b models an exclusive alternative between byj bn If interval a is present then exactly one of intervals by by is present and a starts and ends together with this chosen one The alternative constraint can also be specified by a non negative integer cardinality c alternative a b by In this case it is not 1 but c interval variables that will be selected among the set b1 by and those c selected intervals will have to start and end together with interval variable d Synchronize constraint The constraint synchronize a by b makes intervals b by start and end together with interval a if a is present More formally let a by
91. ecewise 0 gt 0 2 gt 0 0 1 1 x signy piecewise 0 gt 0 2 gt 0 0 1 1 y execute writeln signx signy Depending on which solving engine you write for you get a different result because CPLEX and CP Optimizer do not handle limit values in the same way If you comment out the using CP statement the model is solved by the CPLEX engine and the result is 2 because CPLEX handles symmetry in such a way that it interprets either limit as the discontinuity value However if you uncomment the using CP statement the model is solved by the CP Optimizer engine and the result is 0 because CP Optimizer considers the left limit as the discontinuity value IBM ILOG OPL LANGUAGE REFERENCE MANUAL 97 Set expressions 98 B M Set data can be initialized by set expressions as mentioned in Data types This section describes how these expressions are constructed and what functions are defined over sets Construction of set expressions Functions for sets Construction of set expressions Set expressions are constructed from previously defined sets and the set operations union inter diff and symdiff For instance mtr s1 CEL ST neS 2 pA oie int al sI inter s2 alae wi SIENOS A intr Yel il AIEE S2 int sd sl symdiff s2 initializes i to 1 uto 1 2 3 4 5 dto 2 3 and sd to 2 3 4 5 In addition set expressions can be constructed from ranges For instance the excerpt int s
92. el 2007 1 Highlight the range of cells you want to name then click the Name box at the left end of the Formula Bar 2 Type the name you want to assign to this range and press Enter 3 Save the spreadsheet file Additional information on named ranges Excel automatically updates expands a named range when a row is added somewhere within the range However one must careful adding rows at the end of a range as the range does not get automatically updated in that case It would have to be updated manually OPL allows blank rows in a named range If you are reading a set of strings it will consider the blank cells as having the value 0 If you are reading a set of strings then it inserts an empty string into the set For example s2 Monday Wednesday Thursday Friday This behavior is the same when you don t use named range but instead use explicit ranges like c1 C5 where C2 is empty With the Excel VBA one can name the first top left cell of a named range and access the whole range OPL does not support this When using sheetWrite to write to named ranges the size of the range does not have to match the size of the data you are writing to Excel If the set is smaller then only the top most cells will be filled If you try to write more data than the range can accommodate then you receive the error message Exception from IBM ILOG Concert excel range is not wide enough to write the set In this s
93. eneric arrays and As generic indexed arrays for details IBM ILOG OPL LANGUAGE REFERENCE MANUAL 25 Tuples Data structures in OPL can also be constructed using tuples that cluster together closely related data Declaring tuples For example the declaration tuple Point alot 3 8 tat Vy Borie jooubisie ak ation Wh aal Kal alapiless declares a tuple Point consisting of two fields x and y of type integer Once a tuple type T has been declared tuples arrays of tuples sets of tuples of type T tuples of tuples can be declared as in Point p lt 2 3 gt Roslin jaxosliote at alioy I 4 Sh Kal alarilssp TEONE joules lt p 2p 2 Soohe tuple Rectangle Rosle Lie Bolot wep These declarations respectively declare a point an array of three points a set of two points and a tuple type where the fields are points The various fields of a tuple can be accessed in the traditional way by suffixing the tuple name with a dot and the field name as in Boim jo lt 4 Seg Lot x o ks which initializes x to the field x of tuple p Note that the field names are local to the scope of the tuples i Note Multidimensional arrays are not supported in tuples Keys in tuple declaration As in database systems tuple structures can be associated with keys Tuple keys enable you to access data organized in tuples using a set of unique identifiers In Declaring a tuple using a single key nurses mod t
94. ense named ranges behave exactly the same way as regular ranges Format of the Excel data Here we must differentiate between simple types and tuples IBM ILOG OPL LANGUAGE REFERENCE MANUAL 63 64 B M Sets of simple types The engine reads data from left to right and top to bottom Data can therefore be read either horizontally vertically or from a rectangular zone Sets of tuples The data has to be formatted because the tuple schema has an arity As in databases and manual tables the data format is fixed width variable length Therefore tuple sets are read only line by line in Excel this is the same representation as in pure data files ILOG OPL LANGUAGE REFERENCE MANUAL Writing to a spreadsheet This section uses extracts from the oilSheet dat data file Publishing results to a spreadsheet can be performed using such instructions as a to SheetWrite sheet RESULT A2 A4 blend to SheetWrite sheet RESULT B2 D4 OPL then opens spreadsheets in read write mode This action may fail if another process is already using the x1s file The types of data elements supported for writing are just the same as for reading Cells in Microsoft Excel spreadsheets are filled from left to right and from top to bottom Excel names or named ranges can be accessed using the SheetWrite command using the following syntax SheetConnection sheetData C ILOG Files myExcelFile xls 1 prods to SheetWrite
95. ents as follows brontosaurus rat giraffe while a sort compareLength will reorder them as follows rat giraffe brontosaurus Transposes the elements of the array the first element becomes the last the second becomes the second to last and so on The elements are reversed in place no new array is created Example Suppose that the array a has been created with a new Array foo 12 hello true false Then a reverse changes a so that LANGUAGE REFERENCE MANUAL 237 a peoo T a 0 false a 1 true a 2 hello a 3 12 array toString Returns the string object Object 238 IBM ILOG OPL LANGUAGE REFERENCE MANUAL B M Object representation and functions In this section Introduction Provides an overview of the use of objects in IBM ILOG Script Defining methods Explains how methods are defined in IBM ILOG Script this as a keyword Describes the use of the this keyword in IBM ILOG Script Object constructor Provides a reference of object constructors in IBM ILOG Script User defined constructors Provides a reference of user defined constructors Built in methods Provides a reference of the built in methods of IBM ILOG Script ILOG OPL LANGUAGE REFERENCE Objects MANUAL 239 Introduction Objects are values which do not contain any predefined properties or methods except the toString method but where new ones can be added A new empty object can be created using
96. eric sets OPL supports generic sets which have an expressive power similar to relational database queries For example the declaration abe e iat at ai aae at oel S S iL jip initializes s with the set 1 4 7 10 A generic set is a conjunction of expressions of the form ILOG OPL LANGUAGE REFERENCE MANUAL bene condi ian where p is a parameter or a tuple of parameters s is a range or a finite set and condition is a Boolean expression These expressions are also used in forall statements and aggregate operators and are discussed in detail in Formal parameters The declaration string Resources Tocina MESES oo af Tasks res Resources 7 tuple Disjunction PS CrN EE EES E string second HDALS a bueveieakeyel Chis ES r in Resources ordered i j in res r is a more interesting example showing a conjunction of expressions and is explained in detail in Formal parameters Generic sets are often useful when you transform a data structure e g the data stored in a file into a data structure more appropriate for stating the model effectively Consider for example the declarations string Nodes int edges Nodes Nodes which describe the edges of a graph in terms of a Boolean adjacency matrix It may be important for the model to use a sparse representation of the edges because for instance edges are used to index an array The declaration tuple Edge Nodes 0
97. ersonKeys sortedDevTeam lt i j k gt lt i j k gt in devTeam execute writeln devTeam writeln sortedDevTeam The person tuple uses no keys tuple person string firstname string lastname string nickname The personKkeys tuple uses keys for the first and last names not for the nickname LOG OPL LANGUAGE REFERENCE MANUAL tuple personKeys key string firstname key string lastname string nickname The data shows that the team includes three people whose first name is David two people whose first name is Gregory and one person whose first name is Kevin As a consequence the statement sorted personKeys sortedDevTeam lt i j k gt lt i j k gt in devTeam lists the David tuples before the Gregory tuples which themselves appear before the Kevin tuple Within the David tuples David Doe Skinner comes before David Smith Lewis because a second sorting also takes place on the second field with the key lastname In contrast since there is no person with the same first name and last name no sort is ever done on the last field nickname The output of sortedDevTeam is displayed in the OPL IDE as lt David Atkinson Dave gt lt David Doe Skinner gt lt David Smith Lewis gt lt Gregory McNamara Mac gt lt Gregory Simons Greg gt lt Kevin Morgan Kev gt Sorted sets in piecewise linear functions In piecewise linear functions breakpoints must be
98. erwise The operator is the converse of Examples 12 12 true 12 12 1 false 12 12 1 true The operator lt returns true if xis less than y and false otherwise The operator lt returns true if x is less than or equal to y and false otherwise and so on Examples 1 lt Otrue 1 lt 1 false 1 lt 1 true The bitwise operations AND OR and XOR where x and y must be integers in the range 2 32 1 to 2 32 1 2147483647 to 2147483647 Examples 214 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 14 amp 98 1110 amp 1001 1000 14 915 1110 1001 1111 14 97 1110 1001 111 Bitwise NOT where x must be an integer in the range 2 32 1 to 2 32 1 2147483647 to 2147483647 Examples 14 1 1110 0001 Binary shift operations where x and y must be integers in the range 2 32 1 to 2 32 1 2147483647 to 2147483647 The operator lt lt shifts to the left gt gt shifts to the right maintaining the sign bit and gt gt gt shifts to the right shifting in zeros from the left Examples 9 lt lt 2 36 1001 lt lt 2 100100 9 gt gt 2 2 1001 gt gt 2 10 9 gt gt 2 2 1 11001 gt gt 2 1 11110 9 gt gt gt 2 1073741821 1 11001 gt gt gt 2 01 11110 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 215 216 IBM ILOG OPL LANGUAGE REFERENCE MANUAL IBM ILOG Script strings String representation and functions In this section Introduction Provides an overview of the u
99. es 249 for IBM ILOG Script objects 243 user defined in IBM ILOG Script 244 continue IBM ILOG Script keyword 194 conventions in models 10 conversion IBM ILOG Script of nonboolean value to a Boolean 229 of nonnumeric value to a number 210 of nonstring value to a string 220 costs discontinuous pwl 93 count OPL function 89 data assertions for consistency 71 consistency 67 initializing 37 input output to from a database 51 to from a spreadsheet 59 preprocessing 72 reading from an Excel spreadsheet 62 data files syntax for databases 52 data structures arrays 24 ranges 22 sets 29 data types arrays 24 floats 17 integers 16 limitations in tuples 28 piecewise linear functions 19 ranges 22 sets 29 stepwise functions 20 strings 18 databases connecting to 54 data input output 51 deleting elements 58 reading from 55 SQL encryption 56 supported 53 writing to 57 dates in IBM ILOG Script 247 constructor 249 functions 253 IBM ILOG OPL LANGUAGE methods 251 operators 254 DBExecute OPL keyword 57 DBRead OPL keyword 55 DBUpdate OPL keyword 58 decimal numbers 206 decision expressions 78 and tuple patterns tuple indices 28 decision variables 76 and integer ranges 22 arrays of initialization 84 definition 76 dynamic collection 81 reusable dexpr 78 declaration of constraints 103 of script variables inside a function definition 196 outside a function definition 196 of tuples using keys 26 default values
100. ession fat its end point An additional integer value dval can be specified at the construction of the expression which will be the value returned by the expression when the interval is absent Oherwise if no value is specified the expression will be equal to 0 when the interval is absent In the example above assuming both interval a and b to be present we would get heightAtStart a f 5 heightAtEnd a f 4 heightAtStart b f 2 heightAtEnd b f 1 Of course in general when using ranges for the height of elementary cumul function expressions the heightAtStart End expressions will not be fixed until all the heights have been fixed by the search More formally if an elementary cumul function expression f is based on an interval vari able we denote ivar f this interval variable Let f be a cumul function expression defined as f 30 6 fi where e E 1 1 where f are elementary cumul function expressions The contribution of an interval variable a to f is defined as f gt ivar fi a i fi and the expressions heightAtStart End are defined as follows e heightAtStart a f dval Fla s a if z a z moe dval otherwise Fonte fla e a if z a he ightAtEnd a f dval ial otherwiie Syntax and examples For the syntax and examples of use of a cumulative function see cumulFunction pulse step stepAtEnd and stepAtStart in the OPL Language Quick Reference Following are the constraints av
101. etton Eales Compatibility constraints The CP Optimizer engine supports allowed and forbidden assignments for OPL CP models See allowedAssignments and forbiddenAssignments in the Language Quick Reference Scheduling constraints This section lists the scheduling constraints available for OPL CP scheduling models and provides links to the reference documentation for these constraints For a more detailed description of these constraints please refer to the Scheduling section of this manual The following constraints are available for OPL CP scheduling models Precedence constraint endAtEnd Precedence constraint endAtStart Precedence constraint endBeforeEnd Precedence constraint endBeforeStart Precedence constraint startAtEnd Precedence constraint startAtStart Precedence constraint startBeforeEnd Precedence constraint startBeforeStart Interval grouping constraint alternative ft e eH e e oe He Interval grouping constraint span ILOG OPL LANGUAGE REFERENCE MANUAL Interval grouping constraint synchronize Interval presence constraint presenceOf Sequence constraint first Sequence constraint last Sequence constraint before Sequence constraint prev Sequence constraint noOverlap Cumulative or state function constraint alwaysIn State function constraint alwaysConstant State function constraint alwaysEqual gt gt gt gt gt gt gt gt gt State function
102. etween and as in minte te es multiline comment E The characters also start a comment that terminates at the end of the line on which they occur as in dvar int cost in 0 maxCost decision variable An OPL model consists of a sequence of declarations optional preprocessing instructions the model problem definition optional postprocessing instructions optional flow control main block The following chapters give more detail about these elements A simple model volsay mod A typical model is shown here dvar float Gas dvar float Chloride maximize 40 Gee 730 Chloride subject to ctMaxTotal Gas Chloride lt 50 ctMaxTotal2 3 Gas 4 Chloride lt 180 ILOG OPL LANGUAGE REFERENCE MANUAL ctMaxChloride Chloride lt 40 In this example there is only the declarative initial part and the model definition There is no preprocessing postprocessing or flow control IBM ILOG OPL LANGUAGE REFERENCE MANUAL 11 12 B M ILOG OPL LANGUAGE REFERENCE MANUAL Data types Describes basic data types and data structures available for modeling data in OPL In this section Basic data types Describes integers floats strings piecewise linear functions and stepwise functions in OPL Data structures Describes how the basic data types can be combined using arrays tuples and sets to obtain complex data structures IBM ILOG OPL LANGUAGE REFEREN
103. evcaps aaa naaa Ka cadscenas coueeracedsucesccbesteesees sacs 169 Language SUCIU E a a a a E a a a a E E aa va isasceaceeehizsseueieadievaatstbes 171 SYNA Ka a a NEL ede ec a aeai 173 Expressions in IBM ALOG Soriptsiiieninieien i RA E A i decid 179 Statements nna ean a a le eid ek eed ei eed 193 Builttin vallies and functions 3 c 8 esi eae Ee peed 201 NUMDEGRSiacccc cere tite eke Sadia i nae Reh ee eet nl Mie i i ees 203 IBM ILOG Script Stings cinri ianea n apsebesta bis atnesd izanden a e a raaa aaa a iioa 217 BM ILOG Schipt BOOle ans e e a a a a a a a a a e A ra A age REE AEEA 227 IBM ILOG Script arraySnnincnei ierta a an e a a a i e e oaa a a 233 ODjEC S ii osei lets ee Gn A EO eds hls eee ee 239 DEU teats ei genet EA E A adeateeed and tid dad ened ada peel eae es 247 The NUl Valg tose alta a Meek hin co tial abd sccidgcawuan tien cubed tig habe a as eaters ae 255 The undetinied Values 1 2 sci Monnet aah ait eines a a eee ade eeet ain eee 256 IBMHLOG Script funti Sisenen eedrakenen etn catia eee cen een eget be 257 Miscellaneous funGtonss 2 3 c2ccccecceaceecsecevensseshediaetadigesapiseicbas iraa aaae eaae A eenaa e i AE a A TETERE adsense 258 DIN E E E O E A E E ca ueiah tie en 259 ILOG OPL LANGUAGE REFERENCE MANUAL Language Reference Manual This manual provides reference information about IBM ILOG Optimization Programming Language the language part of IBM ILOG OPL Make sure you read How to use the documentation f
104. eyword key for data consistency when declaring tuples See Keys in tuple declaration Assertions use the keyword assert to ensure that some assertions on the data are respected 6B IBM ILOG OPL LANGUAGE REFERENCE MANUAL Data membership consistency The keyword with enables you to indicate that a given element of a tuple must be contained in a given set If you use it OPL checks the consistency of the tuple set at run time when initializing the set The syntax is tupletype tupleset with celll in setl cell2 in set Let s take an example You have a set of arcs between nodes Nodes are defined by a tuple set of tuples consisting of an origin node and a destination node The with syntax enables you to ensure that the origin and destination nodes do belong to a given set of nodes Compare Data found inconsistent keyword with and Data found consistent keyword with Data found inconsistent keyword with uate oes f Sp FS tuple arc Int Ori gins int destination arc arcs2 with origin in nodes destination in nodes Igi As lt 5 Isis execute writeln arcs2 Data found consistent keyword with ant neces 154 5 hs tuple arc Ane wonton int destination arc arcsl with origin in nodes destination in nodes il Bs lt 5 Poke execute writeln arcs1 7 If you write Data found inconsistent keyword with an error will be raised when the set arcs2 is initialized becaus
105. ferences the object created by the constructor When used in a nonmethod context this returns a reference to the global object The global object contains script variables declared at top level and built in functions and constructors ILOG OPL LANGUAGE REFERENCE MANUAL Object constructor Object constructor Syntax new Object Returns a new object with no properties IBM ILOG OPL LANGUAGE REFERENCE MANUAL 243 User defined constructors 244 B M In addition to the Object constructor any user defined function can be used as an object constructor User defined constructors six eet SSCS new function arg1 argn Creates a new object then calls function argl argn to initialize it Inside the constructor the keyword this can be used to make reference to the object being initialized For example the following program defines a constructor for cars function Car name year this name name this year year Tiis sterg Start Sicuiiep Now calling new Car Ford 1985 creates a new object with the properties name and year and a start method ILOG OPL LANGUAGE REFERENCE MANUAL Built in methods There is only one object built in method Built in method smiex sie SCSCSCSCSC C SC CSCS S S S S object toString Returns the string object Object This method can be overridden by assigning the toString property of an object IBM ILOG OPL LA
106. ferent types of expression Describes the syntax of several types of expression in OPL Script variable reference Provides a reference for the syntax of script variables in OPL Property access Provides a reference for the syntax used to access properties in OPL Assignment operators Provides a reference for the syntax of assignment operators in OPL Function calls Provides a reference for the shorthand syntax used with function calls in OPL Special keywords Lists special reserved keywords in OPL IBM ILOG OPL LANGUAGE REFERENCE MANUAL 179 Special operators Lists the special operators in OPL and their syntax Other operators Provides a reference of other operators used in OPL 180 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Literals Literals can represent the following Numbers for example 12 14 5 1 7e 100 Strings for example Ford Hello world n Booleans either true or false The null value null For further details about number and string literal syntax see Numbers and IBM ILOG Script strings IBM ILOG OPL LANGUAGE REFERENCE MANUAL 181 Operators The precedence of operators determines the order in which they are applied when an expression is evaluated You can override operator precedence using parentheses For a list of IBM ILOG Script operators see Operators 182 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Syntax of different types of expression This section gives the syntax of the
107. following A reference to a script variable Access to a property Assignment operators Special keywords Function calls Special operators Other operators Note For C C programmers The syntax of Script expressions is very close to the C and C syntax Expressions include assignments function calls property access and so on IBM ILOG OPL LANGUAGE REFERENCE MANUAL 183 Script variable reference Reference syntax of script variables six emer Sd variable Returns the value of variable See dentifiers for the syntax of script variables If variable does not exist an error is signalled This is not the same as referencing an existing script variable whose value is the undefined value which is legal and returns the undefined value When used in the body of a with statement a variable reference is first looked up as a property of the current default value 184 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Property access There are two ways of accessing a property value Property access syntax Sma ee o value name Returns the value of the name property of value or the undefined value if this property is not defined See dentifiers for the syntax of name Examples str length getCar name Because name must be a valid identifier this form cannot be used to access properties which do not have a valid identifier syntax For example the numeric properties of an array cannot be acce
108. fter the end of b This is because different semantics can be used to define how a sequence constrains the positions of intervals We will see later how the noOverlap constraint implements one of these possible semantics The sequence variable also allows associating a fixed non negative integer type with each interval variable in the sequence In particular these integers are used by the noOverlap constraint T p a denotes the fixed non negative integer type of interval variable a in the sequence variable p Constraints on sequence variables The following constraints are available on sequence variables first p a states that if interval a is present then it will be the first interval of the sequence p last p a states that if interval a is present then it will be the last interval of the sequence p before p a b states that if both intervals a and b are present then a will appear before b in the sequence p prev p a b states that if both intervals a and b are present then a will be just before b in the sequence p that is it will appear before b and no other interval will be sequenced between a and b in the sequence IBM ILOG OPL LANGUAGE REFERENCE MANUAL 155 156 B M The formal semantics of these basic constraints is shown in the following table before m a b gt T a lt T b r ma 1 Sequence relation semantics The no overlap constraint The no overlap constraint on an interva
109. g with a number the string is first converted to a number and the two numbers are compared numerically In all other cases the other argument is first converted to a string Examples 10 gt 2 gt false 10 gt 2 gt true 123 lt 2 gt false Hint Autocasting may cause unexpected behaviors LANGUAGE REFERENCE MANUAL 225 226 IBM ILOG OPL LANGUAGE REFERENCE MANUAL IBM ILOG Script Booleans Boolean representation and functions In this section Introduction Provides an overview of the use of Boolean literals in IBM ILOG Script Automatic conversion to Boolean Describes the automatic conversion of Booleans in functions Boolean methods Provides a reference of Boolean methods Logical operators Provides a reference of logical operators IBM ILOG OPL LANGUAGE REFERENCE MANUAL 227 Introduction There are two Boolean literals true which represents the Boolean value true and false which represents the Boolean value false When converted to a number true yields 1 and false yields 0 228 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Automatic conversion to Boolean B M When a function method or statement which expects a Boolean value as one of its arguments is passed a non Boolean value this value is automatically converted to a Boolean value as follows The number 0 yields false The empty string yields false The null value yields false The undefined value yields false
110. he arguments keyword described in Special keyword syntax return expression Returns the value of expression from the current function If expression is omitted returns the undefined value The return statement can only be used in the body of a function Defining a function name is operationally the same as assigning a specific function value to the variable name thus a function definition is equivalent to var name some function value The function value can be retrieved from the script variable and manipulated like any other type of value For example the following program defines a function add and assigns its value to the variable sum which makes add and sum synonyms for the same function Eunctiom a0d e 1 return atb sum add Without the keyword static the defined function is global and can be accessed from the whole application With the keyword static the function is local to the current program unit exactly as if name was declared with the keyword var var name some function value 198 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Default values B M Default value syntax with expression statement ILOG OPL Evaluate expression then execute statement with the value of expression temporarily installed as the default value When a reference to an identifier name in statement is evaluated this identifier is first looked up as a property of the default value if the default value does n
111. he nurse tuple is declared with the key name of type string 26 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Declaring a tuple using a single key nurses mod tuple nurse key string name INE SENLOLLE ys Ine Sue ltetGet sony int payRate Then supposing Isabelle must not work more than 20 hours a week just write NurseWorkTime lt Isabelle gt lt 20 leaving out the fields with no keys This is equivalent to NurseWorkTime lt Isabelle 3 1 16 gt lt 20 Using keys in tuple declarations has practical consequences in particular The key field can be used as a unique identifier for the tuple for example the field name in the nurses example in Declaring a tuple using a single key nurses mod In this example it means that there will be no two tuples with the same name in a set of tuples of the type nurse If a user inadvertently attempts to add two different tuples with the same name OPL raises an error Defining keys enables you to access elements of the tuple set by using only the value of the key field name in the nurses example Slicing is one of the features that benefit from it you can slice on the tuple set using only key fields You can also declare a tuple using a non singleton set of keys such as the shift tuple of the nurses example in Declaring a tuple using a set of keys nurses mod Declaring a tuple using a set of keys nurses mod tuple shift key string departmentName key string day
112. he scheduling problem An interval is characterized by a start value an end value and a size An important feature of interval variables is the fact that they can be optional that is one can decide not to consider them in the solution schedule This concept is crucial in applications that present at least some of the following features optional activities operations tasks that can be left unperformed with an impact on the cost examples include externalized maintenance or control tasks activities that can execute on a set of alternative resources machines manpower with possibly different characteristics speed calendar and compatibility constraints operations that can be processed in different temporal modes for instance in series or in parallel alternative modes for executing a given activity each mode specifying a particular combination of resources alternative processes for executing a given production order a process being specified as a sequence of operations requiring resources hierarchical description of a project as a work breakdown structure with tasks decomposed into sub tasks part of the project being optional with an impact on the cost if unperformed and so forth Formally an interval variable a is a variable whose domain dom a is a subset of f ole EF ex el l L f u s ss s 4 amp 5 EP An interval variable is said to be fixed if its domain is reduced to a singleton that is if
113. here between the start and the end of interval a the state of function f if defined must belong to the range Vmin Vmax where 0 lt Vmin Vmax Formally t E s a e D f f t Umin Umaz Syntax and examples For the syntax and examples of use of a state function see stateFunction Another example featuring a transition and the alwaysEqual constraint is shown below The following list includes the constraints available on a state function A full description and example for each syntax is available in the OPL Language Quick Reference alwaysEqual f s e v aligns aligne alwaysEqual f a v aligns aligne alwaysConstant f s e aligns aligne alwaysConstant f a aligns aligne alwaysNoState f s e alwaysNoState f a alwaysIn f u v hmin hmax alwaysIn f a hmin hmax Note that these constraints cannot be used in meta constraints Example with stateFunction transition and alwaysEqual A machine can be equipped with a tool among a set of n possible tools Each operation o executed on the machine needs a specific tool RequiredTool o The machine can process several operation simultaneously provided these operations are compatible with the tool currently installed on the machine Changing the tool installed on the machine needs some constant set up time which is supposed to be independent from the tools Hae mmwoolg ooer Eme IMoOjoSs 6 ag int setupTim
114. hmax Some of these expressions define a range hmin max of possible values for the actual height of the function when the interval variable a is present The actual height is an unknown of the problem CP Optimizer provides some integer expressions to control this height These expressions are based on the notion of the contribution of a given interval variable a to the possibly composite cumul function expression f This contribution is defined as the sum of all the elementary cumul function expressions based on a in f This contribution is a discrete function that can change value only at the start and at the end of interval a and is equal to 0 before the start of a For instance let a and b be two interval variables and a cumul function expression f defined by f pulse a 3 pulse a 2 stepAtEnd a 1 stepAtStart b 2 stepAtEnd b 3 The contribution of a to fis the function pulse a 3 pulse a 2 stepAtEnd a 1 and the contribution of b to fis the function stepAtStart b 2 stepAtEnd b 3 If interval a is present the expression heightAtStart a f returns the value of the contribution of a to f evaluated at the start of a that is it measures the contribution of interval a to cumul function expression f at its start point Similarly the expression heightAtEnd a f returns the value of the contribution of a to f evaluated at the end of a that is it measures the contribution of interval a to cumul function expr
115. hould expand business in Berlin In this context filtering means placing a condition on an iteration to limit the iteration loop See Formal parameters for more examples LOG OPL LANGUAGE REFERENCE MANUAL Constraint labels Explains why label constraints the benefits costs and limitations how to label constraints how to use indexed labels and how to deal with compatibility between constraint names and labels In this section Why label constraints Explains why attaching labels to your constraints is the recommended practice Labeling constraints Shows how to label constraints in OPL Using indexed labels Shows how to use indexed labels for your OPL constraints Labeled assert statements Shows how to label assertions in OPL Limitations to constraint labeling Explains what constraints cannot be labeled or at what cost they can be Compatibility between constraint names and labels Explains compatibility issues for constraint names between OPL 4 x and subsequent versions IBM ILOG OPL LANGUAGE REFERENCE MANUAL 107 Why label constraints You can identify constraints by attaching labels to them It is the recommended practice but it has a performance cost Benefits Constraint labels enable you to benefit from the expand feature in the IDE Problem Browser to find which constraints are tight in a given application or to find dual variable values in linear programs See Understanding the Problem Browser in Getting
116. ibly conditionalize it why identify constraints by a label and why use constraints for filtering purposes In this section Modeling constraints Shows how to define modeling constraints in OPL Conditional constraints Shows how to define conditional constraints in OPL Filtering with constraints Describes the process of using constraints to filter decision variables or aggregates IBM ILOG OPL LANGUAGE REFERENCE MANUAL 103 Modeling constraints 104 B M Constraints passed to the algorithm and which as such define the optimization problem usually apply to decision variables that is they are Boolean expressions of some decision variables To be taken into account by the solving algorithm constraints must be stated using the optimization instruction constraints or subject to as in Stating constraints by means of an optimization instruction Stating constraints by means of an optimization instruction minimize sum p in Products insideCost p inside p outsideCost p outside p subject to forall r in Resources sum p in Products consumption p r inside p lt capacityl r foraline in Products inside p outside p gt demand p Note 1 Optimization instructions require an objective function of type integer or float 2 That objective function must be defined before the constraints Otherwise a warning message is displayed ILOG OPL LANGUAGE REFERENCE MANUAL Conditional constraints
117. icit slicing forall c in connections sum lt p c gt in routes trans lt p c gt lt limit In this constraint the tuple lt p c gt contains one new parameter p and uses the previously defined parameter c Since the value of c is known OPL uses it to index the set routes avoiding a complete scan of the set routes In this example slicing is said to be implicit because the formal parameter c is used to declare iteration in both the forall and sum loops You can also use a constant as a tuple item for example lt p 2 gt for implicit slicing In OPL 4 0 and later versions models tend to be more readable when explicit slicing is used Besides there is no performance advantage in using implicit slicing over explicit slicing More about implicit slicing You should be aware of the following this statement int array i in setl sum i in set2 1 gt 1 1 0 is exactly equivalent to aiioe cuase fa aie eee Celis shi Sei al Sal 2 alee that is the two i on either side of the equal sign are not linked This is called scope hiding because the second i hides the first one in a nested scope ILOG OPL LANGUAGE REFERENCE MANUAL In contrast this statement cE enas y lt i i Seti Clsumis2 gt ani sete iy sys codes implicit slicing which is equivalent to aLigte tliareenys al lio rS Se Cerelanl S abioy ee 8 Sj aly al Se al 2 alg cs In other words there is no im
118. imizer this is captured by the notion of a boolean presence status associated with each interval variable Logical relations can be expressed between the presence of interval variables for example to state that whenever interval a is present then interval b must also be present Another aspect of scheduling is the allocation of scarce resources to time intervals The evolution of a resource over time can be modelled by two types of variables The evolution of a disjunctive resource over time can be described by the sequence of intervals that represent the activities executing on the resource For that CP Optimizer introduces the notion of an interval sequence variable Constraints and expressions are available to control the sequencing of a set of interval variables The evolution of a cumulative resource often needs a description of how the accumulated usage of the resource evolves over time For that purpose CP Optimizer provides the concept of the cumulative function expression that can be used to constrain the evolution of the resource usage over time The evolution of a resource of infinite capacity the state of which can vary over time is captured in CP Optimizer by the notion of the state function The dynamic evolution of a state function can be controlled with the notion of transition distance and constraints are available for specifying conditions on the state function that must be satisfied during fixed or variable intervals
119. interval Let f be a fixed state function we will denote f 3 vi liella e Vi l n s Z e Z v E Zt 8 lt e e vi ln 1 e i lt 3 4 We denote D f Uien s e the definition domain of f that is the set of points where the state function is associated a state For a fixed state function f and a point t D f we will denote s f t e f t the unique interval of the function that contains t and f t the value of this interval s f t e f t si ei t si e f t v tE si For instance in the example of the oven introduced previously we would have 200 1 ae 200 150 and e f 200 250 144 IBM ILOG OPL LANGUAGE REFERENCE MANUAL A state function can be associated with a transition distance The transition distance defines the minimal distance that must separate two consecutive states in the state function More formally if M v v represents a transition distance matrix between state v and state v the transition distance means that Vi l n 1 e M vi vipi lt Si The transition distance matrix M must satisfy the triangular inequality For instance in the example of the oven the state function depicted in the previous figure is consistent with the following transition distance 0 50 60 M 20 0 20 40 30 10 Constraints on state functions If fis a state function a an interval variable v Vmin Vmax non negative integers and alg
120. ion OPL keyword 61 SheetRead OPL keyword 62 shorthand operators 186 sign function 93 slicing explicit implicit 134 using key fields 26 slopes in piecewise linear functions 91 sorted sets 31 sorted tuple sets 32 sparsity and multidimensional arrays 25 and one dimensional arrays 24 and sets 48 special numbers 209 special ordered sets not supported 29 specialized constraints 127 spreadsheets accessing named ranges 62 connecting to 61 data input output 59 reading from 62 writing to 65 SQL requests encryption 56 statements 193 conditional 194 in IBM ILOG Script for OPL 174 last 175 static IBM ILOG Script keyword 198 steopwise functions stepFunction 20 stepFunction OPL keyword 20 string constraints 120 string OPL keyword 18 strings 18 217 automatic conversion to 220 functions 224 length 199 methods 222 operators 225 properties 221 structs in C tuples in OPL 26 sum OPL keyword 90 symdiff OPL keyword 98 syntax in IBM ILOG Script 173 accessing property values 185 assignment operators 186 conditional statements 194 default values 199 expressions 183 REFERENCE MANUAL 263 function definition 198 identifiers 177 loops 194 other operators 191 reference to a script variable 184 shorthand 187 special keywords 188 special operators 189 variable declaration 196 then See if then else 105 this IBM ILOG Script keyword 242 244 this IBM ILOG Script keyword 188 tuple indices 28 tuple pat
121. ion that represents the sum of individual contributions of intervals A panel of elementary cumul function expressions is available to describe the individual contribution of an interval variable or a fixed interval of time which cover the main use cases mentioned above pulse for usage of a cumulative resource step for resource production consumption When the elementary cumulative function expressions that define a cumul function expression are fixed and thus so are their related intervals the expression is fixed CP Optimizer provides several constraints over cumul function expressions These constraints allow restricting the possible values of the function over the complete horizon or over some fixed or variable interval For applications where the actual quantity of resource that is used produced or consumed by intervals is an unknown of the problem expressions are available for constraining these quantities Cumul function expressions Let F denote the set of all functions from Z to Zt A cumul function expression fis an expression whose value is a function of Frana thus whose domain dom f is a subset of Ft Letu Y Zand h Rmin hmar zt and a be an interval variable we consider the following elementary cumul function expressions illustrated in the following figure pulse u v h step u h pulse a h pulse a hmin Nmax stepAtStart a h stepAtStart a hmin Pmax stepAtEnd a h and stepAtEnd a hmin max
122. ion of this feature is constrained by interval variables of the problem The main difference between state functions and cumulative functions is that interval variables have an incremental effect on cumul functions increasing or decreasing the function value whereas they have an absolute effect on state functions requiring the function value to be equal to a particular state or in a set of possible states Informally speaking a state function is a set of non overlapping intervals over which the function maintains a particular non negative integer state In between those intervals the state of the function is not defined typically because of an ongoing transition between two states For instance for an oven with three possible temperature levels identified by indexes 0 1 and 2 we could have start 0 end 100 state 0 start 150 end 250 state 1 start 250 end 300 state 1 start 320 end 420 state 2 start 460 end 560 state 0 Constraints are available to restrict the evolution of a state function These constraints allow you to specify That the state of the function must be defined and should remain equal to a given non negative state everywhere over a given fixed or variable interval alwaysE qual 4 That the state of the function must be defined and should remain constant no matter its value everywhere over a given fixed or variable interval alwaysConstant That intervals requiring the sta
123. ith variable sizes forall iterations with variable sizes orsali a alin IPiaocliveies p alin Mieake jol s In forall iterations with variable sizes the second formal parameter o iterates on sets of potentially different sizes depending on the value of the formal parameter p To use indexed labels 1 Declare the constraint array that will receive the labeled constraints constraint ctSupply Products Cities 2 Add the indexing expressions to the label ctSupply p o The following shows the full code extract Labeling constraints with indexed labels constraint ctSupply Products Cities constraint ctDemand Products Cities minimize Sumi in Reutes Costll Lnans 1 subject to PONS ULI jo ain ieo clwwoics a alin eae jal 110 IBM ILOG OPL LANGUAGE REFERENCE MANUAL B M ctSupply p o sum d in Dest p Trans lt p o d gt Supply l lt p 0 gt cowed jo ain Picoclovweics a C aia Desecho ctDemand p d Sumi o alin Okeho d Trans lt p o d gt Demand lt p d gt ILOG OPL LANGUAGE REFERENCE MANUAL 111 Labeled assert statements Assertions can be labeled When you label a constraint that is part of an assert statement and if the assertion fails the context of the failing assertions appears in the Issues output window For example ante vals il 2 Sie assert forall ll is aime vallis eE SA 3 E Scripting log 7 Solutions Conficts Relaxa
124. its value If the string does not represent a valid integer NaN is returned Leading white space characters are ignored If parseInt encounters a character that is not a digit in the specified base it ignores it and all succeeding characters and returns the integer value parsed up to that point If base is omitted it is taken to be 10 unless string starts with 0x or 0x in which case it is parsed in base 16 or with 0 in which case it is parsed in base 8 Examples parselnt 123 123 parselnt 123 123 parselnt 123 45 123 parselnt 1001010010110 2 4758 parselnt a9 16 169 parselnt Oxa9 169 parselnt 010 8 parselnt 123 poodles 123 parselnt a lot of poodles NaN parseFloat string Parses string as a floating point number and return its value If the string does not represent a valid number NaN is returned Leading white space characters are ignored The string is parsed up to the first unrecognized character If no number is recognized the function returns NaN Examples parseFloat 3 14e 15 3 14e 15 parseFloat 3 14e 15 poodles 3 14e 15 parseFloat a fraction of a poodle NaN 224 IBM ILOG OPL LANGUAGE REFERENCE MANUAL String operators B M String operators string1 string2 string string2 string string2 string1 lt string2 string lt string2 string1 gt string2 string gt string2 ILOG OPL Returns a string containing the concatenation of string
125. l other cases ILOG OPL LANGUAGE REFERENCE MANUAL Intensity and size Sometimes the intensity of work is not the same during the whole interval For example let s consider a worker who does not work during weekends his work intensity during weekends is 0 and on Friday he works only for half a day his intensity during Friday is 50 For this worker 7 man days of work will span for longer than just 7 days In this example 7 man days represents what we call the size of the interval that is what the length of the interval would be if the intensity function was always at 100 To model such situations you can specify a range for the size of an interval variable and an integer stepwise intensity function F For a fixed present interval amp the following relation will be enforced at any solution between the start end size sz of the interval and the integer granularity G by default the intensity function is expressed as a percentage so the granularity G is 100 _ Por sza lt dt lt sz a 1 s y v s a G That is the length of the interval will be at least long enough to cover the work requirements given by the interval size taking into account the intensity function However any over estimation is always strictly less than one work unit If no intensity is specified it is supposed to be the constant full intensity function Vt F t 100 so in that case sz a l a Note that the size is not defined for
126. l sequence variable p states that the sequence defines a chain of non overlapping intervals any interval in the chain being constrained to end before the start of the next interval in the chain This constraint is typically useful for modelling disjunctive resources More formally the condition for a permutation value 71 for sequence p to satisfy the noOverlap constraints is defined as noOverlap 7 lt Ya b A r a V 72 b v x a lt r b amp ela lt s b If a transition distance matrix M is specified it defines the minimal non negative distance that must separate two consecutive intervals in the sequence More formally if T p a denotes the non negative integer type of interval a in the sequence variable p noOverlap t M amp Ya b E A 7r a V a2 b v x a lt z b ela MIT r a T 7 b lt s b A sequence variable together with a no overlap constraint using it are illustrated in this figure ILOG OPL LANGUAGE REFERENCE MANUAL p sequence on a iet s first p az prev p 23z a 9 az Absent before p a a gt ag intervals a3 a a a a 4s ef oe gt t noOverlap p t r a3 ag As a jH as Example of sequence variable and no overlap constraint Syntax and examples For syntax and examples of use of the sequence interval variable see sequence in the OPL Language Quick Reference For the syntax and examples of use of the no overlap constraint which needs to
127. les abcdabcd lastIndexOf bc 5 abcdabcd lastIndexOf bc 5 5 abcdabcd lastIndexOf bc 4 1 abcdabcd lastIndexOf bc 0 1 abcdabcd lastIndexOf foo 1 abcdabcd lastIndexOf BC 1 Returns string converted to lowercase Examples ILOG OPL LANGUAGE REFERENCE MANUAL B M sv eet Po Hello World toLowerCase hello world string toUpperCase string split separator string toString ILOG OPL string toUpperCase Returns string converted to uppercase Examples Hello World toUpperCase HELLO WORLD Returns an array of strings containing the substrings of string which are separated by separator See also the array method join Examples first name last name age split gt an array a such that length is 3 a 0 is first name a 1 is last name and a 2 is age If string does not contain separator an array with one element containing the whole string is returned Examples hello split gt an array a such that a length is 1 and a 0 is hello Returns the string itself LANGUAGE REFERENCE MANUAL 223 String functions String functions String fromCharCode code Returns a single character string containing the character with the given ASCII code Examples String fromCharCode 65 gt A writeln String fromCharCode 0x30 gt o parselnt string base Parses string as an integer written in the given base and returns
128. linear expressions can be extracted What can be extracted from a model with logical constraints The table below lists the logical constraints that CPLEX can extract ILOG OPL LANGUAGE REFERENCE MANUAL Logical AND Logical OR Logical NOT Imply Different from Equivalence All those constructs accept as their arguments other linear constraints or logical constraints so you can combine linear constraints with logical constraints in complicated expressions in your application Which nonlinear expressions can be extracted Some expressions are easily recognized as nonlinear for example a function such as SS yell However other nonlinearities are less obvious such as absolute value as a function Ina very real sense MIP is a class of nonlinearly constrained problems because the integrality restriction destroys the property of convexity which any linear constraints otherwise might possess Because of that characteristic certain although not all nonlinearities are capable of being converted to a MIP formulation and thus can be solved by IBM ILOG CPLEX The following nonlinear expressions are accepted in an OPL model min and minl the minimum of several numeric expressions max and max1 the maximum of several numeric expressions abs the absolute value of a numeric expression piecewise the piecewise linear combination of a numeric expression A linear constraint can appear as a term in a logical
129. lly a script variable reference but it can be any expression Example new ctors i arg Invokes constructor ctors i Returns a string representing the type of value as follows Array object Boolean boolean Date date Function function Null object Number number Object object String string Undefined undefined Deletes the global script variable variable This does not mean that the value in variable is deleted but that it is removed from the global environment Example myVar Hello world Create the global variable myVar delete myVar writeln myVar Signals an error because myVar is undefined If variable is a local variable an error is signalled if variable is not a known variable nothing happens The whole expression returns true For C C programmers The delete operator has a radically different meaning in IBM ILOG Script in C it is used to delete objects not script variables and properties Remove the property name from the object value If value does not contain the name property this expression does nothing If the property does exist but cannot be deleted an error is signalled If value is not an object an error is signalled The whole expression returns the true value Evaluates expressionl and expression2 sequentially and returns the value of expression2 The value of expressionl is ignored REFERENCE MANUAL 189 The most common use for this operator is inside for
130. loops where it can be used to evaluate several expressions where a single expression is expected for var i 0 j 0 i lt 10 itt j 2 ewretelinn G ie Use enics as pigas 4 ai 190 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Other operators Other operators are described in detail in the section dedicated to the data type they operate on Other operator syntax Arithmetic operators These operators perform the usual arithmetic operations In addition the operator can be used to concatenate strings See Numeric operators and String operators Equality operators These operators can be used to compare numbers and strings see Numeric operators and String operators For other types of values such as dates arrays and objects the operator is true if and only if X and Y are the exact same value For example new Array 10 new Array 10 false var a new Array 10 a a true Relational operators These operators can be used to compare numbers and strings See Numeric operators and String operators Bitwise operators See Numeric operators Logical operators See Logical operators condition X Y IBM ILOG OPL LANGUAGE REFERENCE MANUAL 191 192 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Statements A statement can be a conditional statement a loop statement a local script variable declaration a function definition or a default value In this section Conditional statement Provides
131. lope F t of F on the segment t ti 1 is equal to s 41 That is Vt ti tiza P t F t siqi t ti Note that the point tj41 is not included in the segment if t tj44 then F is discontinuous at point t s represents the height of the step positive or negative at t The value of F t is equal to the the value of the leftmost extremity of the segment immediately to the right of the discontinuity Formally this is given by ifi An 1 then F ti F ti42 si 2 ti ti 2 else if i 1 then F t F ti 1 s ti tia sia Otherwise function has form slope step slope and i 1 else if to gt t then F t vo 83 t to else F t vo s ti to s2 For a complete description of the OPL syntax of a piecewise linear function see piecewise and pwlFunction in the OPL Language Quick Reference A stepwise function is a special case of the piecewise linear function where all slopes are equal to 0 and the domain and image of F are integer A stepwise function F t is defined by a tuple F stepwise V T where IBM ILOG OPL LANGUAGE REFERENCE MANUAL 141 142 B M e V is a vector of n 1 function values v Z for F e T is a vector of n values t Z for F such that Yi ti lt ti44 The function is defined everywhere on o0 00 and the function value at a point t is given by e Yt lt t F t e Vi l n 1 Vt ti ti 1 F
132. lt in values and functions of the scripting language In this section Language structure Presents the structure of the IBM ILOG Script language for OPL the language constructs the elements from which expressions can be constructed and the possible types of statement Built in values and functions Presents the built in values and functions of the IBM ILOG Script language for OPL numbers strings Booleans arrays objects dates the null and undefined values functions IBM ILOG OPL LANGUAGE REFERENCE MANUAL 169 170 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Language structure Presents the structure of the IBM ILOG Script language for OPL the language constructs the elements from which expressions can be constructed and the possible types of statement In this section Syntax What composes a scripting statement compound statements comments identifiers Expressions in IBM ILOG Script Expressions are a combination of literals script variables special keywords and operators Statements A statement can be a conditional statement a loop statement a local script variable declaration a function definition or a default value IBM ILOG OPL LANGUAGE REFERENCE MANUAL 171 172 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Syntax What composes a scripting statement compound statements comments identifiers In this section General Provides a general overview of OPL syntax Compound statements Explains the us
133. ly the keyword DBExecute enables you to carry out administration tasks on data tables whereas the keyword DBUpdate modifies the contents of data tables The OPL result publisher will iterate on the items in the set result and bind the component values to the SQL statement parameters in the declared order l Note OPL supports the same element types for reading as for database publishing IBM ILOG OPL LANGUAGE REFERENCE MANUAL 57 58 B M Updating existing rows To update existing rows in a database instead of adding new ones use an SQL update statement For example to multiply by 2 the blends for Super 1 Add the following lines in the mod file tuple Result2 float blend Float ay Sering only string gas Result2 result2 lt 2 blend o Super a Super o0 Super gt o in Oils 2 Write an SQL update statement like this result2 to DBUpdate db UPDATE Result SET blend a WHERE oil AND gas See also Getting the data elements from an IloOplModel instance in the Language User s Manual for details about data publishers and postprocessing Deleting elements It is also possible to delete elements from a database For instance the instructions mod file string NamesToDelete i aCe scabies e NamesToDelete to DBUpdate db delete from PEOPLE where NAME delete from the relation table PEOPLE all the tuples whose names are in NamesToDelete l Note
134. mber representations and functions In this section Introduction Provides an overview of how numbers are expressed in OPL Decimal numbers Explains the use of decimal numbers in OPL Hexadecimal numbers Shows how hexadecimal numbers are used in OPL Octal numbers Explains the use of octal numbers in OPL Special numbers Explains three special numbers used in OPL Automatic conversion to a number Describes the automatic conversion of numbers in OPL functions Number methods Provides a reference for the number method in OPL Numeric functions Provides a reference for numeric functions in the OPL language IBM ILOG OPL LANGUAGE REFERENCE MANUAL 203 Numeric constants Provides a reference for numeric constants in OPL Numeric operators Provides a reference for numeric operators in OPL 204 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Introduction Numbers can be expressed in decimal base 10 hexadecimal base 16 or octal base 8 There are also special numbers Note For C C programmers Numbers have the same syntax as C and C integers and doubles They are internally represented as 64 bit double precision floating point numbers IBM ILOG OPL LANGUAGE REFERENCE MANUAL 205 Decimal numbers A decimal number consists of a sequence of digits followed by an optional fraction followed by an optional exponent The fraction consists of a decimal point followed by a sequence of digits the exponent consist
135. method toString substring gt primitive method substring charAt gt primitive method charAt etc The only properties which are not listed by for in loops are the numeric properties of arrays Exit the current while for or for i n loop and continue the execution at the statement immediately following the loop This statement cannot be used outside a loop Example while i lt a length if a i foo foundFoo true break i i 1 Execution continues here Stop the current iteration of the current while for or for inloop and continue the execution of the loop with the next iteration This statement cannot be used outside a loop Example for var i 0 i lt a length i if a i lt 0 continue writeln A positive number afi NGUAGE REFERENCE MANUAL 195 Declaration of script variables Declaration syntax for script variables var decl1 decin Declares each script variable as a local variable If an expression is provided it is evaluated and its value is assigned to the variable as its initial value Otherwise the variable is set to the undefined value where each decli has the form Examples variable expression var x var name Joe var average atb 2 sum message Hello Inside a function definition Script variables declared with var are local to the function and they hide any global variables with the same names they have the same status a
136. nal schedule For absent intervals they are just ignored dvar interval a optional IsOptional in StartMin EndMax size SZ in SZMin SZMax intensity F Where int IsOptional StartMin EndMax SZ SZMin SZMax stepFunction F maxint 2 1 lt StartMin lt maxint 2 1 maxint 2 1 lt EndMax lt maxint 2 1 0 lt SZ lt maxint 2 1 0 lt SZMin lt maxint 2 1 0 lt SZMax lt maxint 2 1 Examples For examples of using interval see the CP keywords interval optional size and intensity in the OPL Language Quick Reference Display of interval variable domain The domain of an interval variable is displayed as shown in this example A1 0 1 10 990 5 10 5 990 gt 25 1000 After the name of the interval variable here A1 the first range here 0 1 represents the domain of the boolean presence status of the interval variable Thus 0 1 represents an optional interval variable whose status has still not been fixed 0 an absent interval variable and 1 a present interval variable The remaining fields describe the position of the interval variable it is omitted if the interval variable is absent as this information is not relevant in this case Thus an absent interval variable is displayed as A1 0 When the interval variable is possibly present the first range in the remaining fields represents the domain of the interval start ILOG OPL LANGUAGE REFERENCE MANUAL
137. nd tuple patterns in dexpr dexpri floaty fal alia tel caae subject to Pore ia70 C a ag C SS 5 ee Ee eleoaone GENE SV lt elp oC S abil ej Sack subject to Foran alg We y fal JS 3 a 8 Performance and memory consumption If you choose to label constraints in large models use tuple indices instead of tuple patterns to avoid increasing the performance and memory cost See Constraint labels ILOG OPL LANGUAGE REFERENCE MANUAL Sets Definition Sets are non indexed collections of elements without duplicates OPL supports sets of arbitrary types to model data in applications If T is a type then T or alternatively setof T denotes the type set of T For example the declaration int setine 7 setof Precedence precedences declares a set of integers and a set of precedences Sets may be ordered sorted or reversed By default sets are ordered which means that Their elements are considered in the order in which they have been created Functions and operations applied to ordered sets preserve the order See Sorted and ordered sets for details Operations on sets The following operations are allowed on sets See OPL functions in Language Quick Reference for more information about functions For the functions on sets the index starts at 0 Operations allowed on sets union inter diff symdiff set function set1 set2 first last elt function set
138. neralize this initialization to any number of dimensions Specifying pairs An array can also be initialized by specifying pairs index value as in the declaration mod file niin ARDENA 2a6R fe SONG ne 277 a Monday aim Tuesday 2 ILOG OPL LANGUAGE REFERENCE MANUAL Wednesday 3 Mavinnwiemckeye gs A eieiei e Sip aene ticen E GO Meunday ar 7 l Note 1 When the initialization is specified by index value pairs the delimiters and must be used instead of and 2 The ordering of the pairs can be arbitrary These two forms of initialization can be combined arbitrarily as in mod file sigue eidky oF isos coor Hee eee aeabllicy a a 2 40 50 60 te LO 2O SO Internally You can initialize arrays internally that is in the mod file using the same syntax as in dat files Here the array items may be expressions that are evaluated during initialization The syntax for pairs is not available for internal initialization In preprocessing instructions Arrays can also be initialized in the preprocessing instructions as in range R 1 8 int a R execute ie ue Ay lie al alto IR ff tal Sra odes te which initializes the array in such a way that a 1 2 a 2 3 andsoon See Preprocessing data As generic arrays OPL also supports generic arrays that is arrays whose items are initialized by an ex
139. next prev elt function set elt int nextc prevc elt function set elt int item elt function set int ord int function set elt Initializing sets A set can be initialized in various ways The simplest way is by listing its values explicitly For example tuple Precedence int before imeat Eer ILOG OPL LANGUAGE REFERENCE MANUAL 29 30 B M Precedence precedences lt 1 2 gt See Initializing sets for details ILOG OPL LANGUAGE gire lt 3 45i5 REFERENCE MANUAL Sorted and ordered sets Sets can be either sorted or ordered An ordered set is a set which elements are arranged in the order in which they were added to the set Note that this is how sets are created by default For example Hiner Sul W352 sibs and ordered int Sl 3 2 5 are equvalent A sorted set is a set in which elements are arranged in their natural ascending order For strings the natural order is the lexicographic order The natural order also depends on the system locale To specify the descending order you add the keyword reversed For example sorted int sortedS 3 2 5 and ordered int orderedS 2 3 5 are equvalent and iterating over sortedS or ordereds will have the same behavior This section shows the effect of the sorted property on simple sets tuple sets and sets used in piecewise linear functions Simple sets The code sample Sorted sets enables yo
140. ng algn two boolean values The constraint alwaysEqual f a v algng algne specifies that whenever a is present state function f must be defined everywhere between the start and the end of interval a and be constant and equal to non negative value v over this interval If algn is true it means that interval a is start aligned with f Interval a must start at the beginning of the interval where fis maintained in state s If algng is true it means that interval a is end aligned with f Interval a must end at the end of the interval where fis maintained in state s More formally vt s a e a t D f A f t v alna gt s a s f s a The constraint alwaysConstant f a algng algne specifies that whenever a is present state function f must be defined everywhere between the start and the end of interval a and be constant over this interval More formally dv Z alwaysEqual f a v algn algne The constraint alwaysNoState f a specifies that whenever a is present state function f cannot provide any valid state between the start and the end of interval a Asa consequence any interval constrained with alwaysEqual or alwaysConstant on this function and thus requiring the function to be defined cannot overlap interval a Formally s a e a 0 D f 0 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 165 166 B M The constraint alwaysIn f a Vmin Vmax Specifies that whenever a is present everyw
141. ng point numbers OPL also has a predefined float constant infinity to represent the IEEE infinity symbol Declarations of floats are similar to declarations of integers The declaration lets EIS SoBe declares a float whose value is 3 2 The value of the float can be specified by an arbitrary expression ILOG OPL LANGUAGE REFERENCE MANUAL 17 Strings 18 B M Shows how to declare strings in the OPL language OPL supports a string data type The excerpt string Tasks masonry carpentry plumbing ceiling Maroyene INGU AP a En a Minrahiovclonwiey Yo aca dE Noaroen maving hy defines and initializes a set of strings Strings can appear in tuples and index arrays Strings are manipulated in the preprocessing phase via ILOG Script See IBM ILOG Script for OPL for details on the scripting language The OPL parser supports the following escape sequences inside literal strings Escape sequences inside literal strings b backspace t tab n newline f form feed r carriage return double quote backslash ooo octal character 000 xXX hexadecimal character XX To continue a literal string over several lines you need to escape the new line character first line second line ILOG OPL LANGUAGE REFERENCE MANUAL Piecewise linear functions B M Shows how to declare piecewise linear functions in the OPL language Piecewise linear functions are typically used
142. nt 0 function NextNumber count count l return count When this file is loaded the function NextNumber becomes visible to the whole application while count remains local to the loaded program unit and is visible only inside it It is an error to declare the same local variable twice in the same scope For example the following program is incorrect because res is declared twice function max x y aie oe gt yy NAL TOS A R else var res y Error return res ILOG OPL LANGUAGE REFERENCE MANUAL 197 Function definitions Function definition syntax static Defines a function name with the given parameters and body A function definition can only take place at the top level function definitions cannot be nested function name v1 wy VN When the function is called the script variables v1 vn are set to the corresponding argument values then the statements are executed If a return statement is reached the function returns the specified value otherwise after the statements are executed the function returns the undefined value statements The number of actual arguments does not need to match the number of parameters if there are fewer arguments than parameters the remaining parameters are set to the undefined value if there are more arguments than parameters the excess arguments are ignored Independently of the parameter mechanism the function arguments can be retrieved using t
143. nt a F lt a Vv vt s a e a F t 0 For syntax and examples of these constraints see forbidEnd forbidExtent and forbidStart in the OPL Language Quick Reference Note that none of these constraints can be used in meta constraints ILOG OPL LANGUAGE REFERENCE MANUAL Precedence constraints between interval variables B M Precedence constraints are common scheduling constraints used to restrict the relative position of interval variables in a solution For example a precedence constraint can model the fact that an activity a must end before activity b starts optionally with some minimum delay z If one or both or the interval variables of the precedence constraint is absent then the precedence is systematically considered to be true therefore it does not impact the schedule More formally the semantics of the relation TC 4 b z on a pair of fixed intervals amp b and for a value z depending on the constraint type TC is given in the following table ra Aa gt Sa 2 SO end Be foreStart lt s b end Be foreEnd A e a 2 lt e b startAtStart A gt s a 2 s8 b startAtEnd A gt s a 2 e b endAtStart A gt e a 2 s b endAtEnd A gt e a 2 e b Precedence relations semantics For syntax and examples see the following functions described in the OPL Language Quick Reference Note that none of these constraints may be used in a meta constraint endAtEnd endAtStart endBefor
144. nterval amp is simply presenceOf amp ox amp The truth value of this constraint can be used in arithmetical expressions and thereby restricted by logical constraints This constraint can be used in meta constraints to indicate for example that there may be two optional intervals a and b if interval a is present then b must be present as well This is modelled by the constraint presenceOf a gt presenceOf b OPL formulation The constraint to express that the interval variable must be present presenceOf a where dvar interval a For an example of the presenceOf constraint see presenceOf in the OPL Language Quick Reference ILOG OPL LANGUAGE REFERENCE MANUAL Expressions on interval variables Integer and numerical expressions are available to access or evaluate different attributes of an interval variable These expressions can be used for example to define a term for the cost function or to connect interval variables to integer and floating point expressions The integer expressions are startOf endOf lengthOf and sizeOf and they provide access to the different attributes of an interval variable Special care must be taken for optional intervals as an integer value dval must be specified which represents the value of the expression when the interval is absent If this value is omitted it is supposed to be 0 For the syntax of integer expressions see endOf lengthOf sizeOf and startOf in the OPL Language
145. o 01 1DB without a user name and password 2 It is possible to connect to several databases within the same model 54 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Reading from a database In OPL database relations can be read into sets or arrays For instance these instructions from the model file tuple gasType string name float demand float price float octane float lead tuple oilType string name float capacity float price float octane float lead And these instructions from the data file GasData from DBRead db SELECT FROM GasData OilData from DBRead db SELECT FROM OilData Together illustrate how to initialize a set of tuples from the relation 0ilData in the database db In this example the DBRead instruction inserts an element into the set for each tuple of the relations Important conventions adopted by OPL 1 If read into a set the resulting set must be a set of integers floats or strings or a set of tuples whose elements are integers floats or strings 2 If read into an array the resulting array must be an array of integers floats or strings or an array of tuples whose elements are integers floats or strings 3 In the case of tuples the columns of the SQL query result are mapped by position to the field of the OPL tuples For instance in the above query the column name has been mapped to the field name and so on 4 When initializing an array with a DBRead st
146. of statements in IBM ILOG Script 199 delimiters and internal initialization tuples 45 curly brackets 175 for comments 176 for tuples 45 quotes 218 228 semi colon 174 dexpr OPL keyword 78 diff OPL keyword 98 discontinuous piecewise linear functions 93 discrete constraints 119 data 119 variables 119 dvar OPL keyword vs var 76 efficient models 107 133 134 else See if then else 105 else IBM ILOG Script keyword 194 encryption of SQL statements 56 equivalence logical constraint 122 errors tuples with same names 26 Excel accessing named ranges 62 Excel spreadsheet what data can be read 62 execute IBM ILOG Script block for preprocessing 72 expressions 179 REFERENCE MANUAL G Boolean 100 counting 89 float 88 in IBM ILOG Script for OPL 174 in logical constraints 122 integer 88 set 98 syntax 183 external data 38 and memory allocation 50 sets 47 filtering formal parameters 130 in tuples of parameters 134 with constraints 106 first OPL function 98 float constraints 118 float OPL keyword 17 floats 17 expression 88 functions in OPL 88 for IBM ILOG Script keyword loop syntax 194 forall statements and constraint labels 113 formal parameters basic 130 filter expressions 130 tuples 133 function calls 187 function definitions 198 function IBM ILOG Script keyword 198 functions 257 card 98 first 98 float 88 for dates 253 for strings 224 item 98 last 98 miscellaneous 2
147. of two sets A and B is A union symbol B A intersection symbol B described in Expressions For example the declarations intr il il Sikes ant s2 ina 5h int i sl inter s2 abe sf til A telly aliglicese ce ani US tsi unten Ao ipa bine cl il AGR SA abe Gel Sil eyygielbinie ala kp initialize i to 1 u to 1 2 3 5 7 9 dto 2 3 and sd to 2 3 4 5 It is also possible to initialize a set from a range expression For example the declaration IBM ILOG OPL LANGUAGE REFERENCE MANUAL 47 48 B M int s asSet 1 10 initializes s to 1 2 10 It is important to point out at this point that sets initialized by ranges are represented explicitly unlike ranges As a consequence a declaration of the form int a asSet 1 100000 creates a set where all the values 1 2 100000 are explicitly represented while the range range s 1 100000 represents only the bounds explicitly More about internal initialization of sets When writing the assignment s2 s1 you add one element to s1 that element is also added to s2 If you do not want this write sl ili in s2 For example compare the statements in Initializing sets in the model file Initializing sets in the model file If you write int sl 1 2 int sl 1 2 int s2 s1 int s2 i i in sl execute int s2 s1 execute s2 add 3 writeln s1 s2 add 3 writeln s1 As gen
148. oil gas blend a VALUES LOG OPL LANGUAGE REFERENCE MANUAL Supported databases Supported databases in the Working Environment document provides a list of the databases to which you can connect your OPL model to read and write data The table below gives the syntax of the string you must use to connect to each of the supported databases See The oil database example in IDE Tutorials for details on how to customize the oil database example for connection to a different database Database connection strings Database Connection String Name DB2 username password database The client configuration will find the server MS SQL userName password database dbServer ODBC dataSourceName userName password Oracle 9 and userName password dbinstance later OLE DB lt user gt lt password gt lt database name gt lt server name gt IBM ILOG OPL LANGUAGE REFERENCE MANUAL 53 Connection to a database In OPL database operations all refer to a database connection Here are two examples from the 0i1DB example for declaring connections See Supported databases for more connection strings DBConnection db odbc oilDB user passwd and DBConnection db access oilDB mdb The first example uses the ODBC data source 011DB declared by the system to connect to the database The connection db should be viewed as a handle on the database Note 1 The user and passwd parameters are optional you can connect t
149. operands is a string the other operand is converted to a string if none of the operands is a string the operands are both converted to numbers For example ho true Jerue 3 true 4 For comparison operators such as and gt the conversion to a number takes precedence over the conversion to a string In other words if at least one of the operands is a number the other operand is converted to a number If both operands are strings the comparison is made on strings For example MALO Ss UW alse MALOU Ss 2 exer ILOG OPL LANGUAGE REFERENCE MANUAL Number methods There is only one number method Number method number toString Returns a string representing the number as a literal For example 14 3e2 toString 1430 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 211 Numeric functions Note For C C programmers Most of the numeric functions are wrap ups for standard math library functions Numeric functions Sma fet Math abs x Returns the absolute value of x Math max x y Math max x y returns the larger of x and y Math min x y Math max x y returns the smaller of x and y Math random Returns a pseudo random number between 0 inclusive and 1 exclusive Math ceil x Math ceil x returns the smallest integer value greater than or equal to x x Math round x Math round x returns the nearest integer value to x Math sqrt x Returns the square root of x Math atan2 y
150. or details of prerequisites conventions documentation formats and other general information In this section Why an Optimization Programming Language OPL is a modeling language for combinatorial optimization that aims at simplifying the solving of these optimization problems OPL the modeling language Presents the modeling language of IBM ILOG OPL namely the overall structure of OPL models the basic modeling concepts how data can be initialized internally as it is declared or externally in a dat file how to connect to read from and write to databases and spreadsheets expressions and relations constraints and formal parameters IBM ILOG Script for OPL Describes the structure and built in values and functions of the scripting language Copyright IBM Corp 1987 2009 5 Why an Optimization Programming Language Describes the reasons why OPL provides a modeling language to solve your optimization problems Linear programming integer programming and combinatorial optimization problems arise in a variety of application areas which include planning scheduling sequencing resource allocation design and configuration In this context OPL is a modeling language for combinatorial optimization that aims at simplifying the solving of these optimization problems As such it provides support in the form of computer equivalents for modeling linear quadratic and integer programs and provides access to state of the
151. orms initialization Instead of GasType gas Gasolines execute POr vart i cu cesvata 4 gas g name g the same can be expressed with the syntax for generic indexed arrays as GasType gas Gasolines g name g g in gasData Likewise this syntax Initializing indexed arrays transp4 mod float Cost Routes execute INITIALIZE for var t in TableRoutes Cost Routes get t p Connections get t o t d t cost is equivalent to ILOG OPL LANGUAGE REFERENCE MANUAL float eCosit Routes M AKEP KE ou d gt gt bacoOsias mtsinuloableRoutess p Note 1 It is recommended to use generic arrays or generic indexed arrays whenever possible since they make the model more explicit and readable 2 If an index is met more than once no warning is issued and the latest value set for this index is the one kept For example int n 5 Cimer s i ee Ie sorted int s2 asSet 1l n reversed int s3 asSet 1 n aioli sell n into kz anil IES Ss n Mazin r t apa ah al CENS maxl n i i maxl n i i execute writeln X writeln x writeln x gives out S ee lt gt SD SEY NO Wd Pe SEA From a database Reading database columns to a tuple array 0i1DB2 dat is more efficient since no data is duplicated Reading database columns to a tuple array 0i1DB2 dat Gasolines Gas from DBRead db SELECT name name demand price octane lead FROM GasData
152. ot have such a property name is treated as a regular variable For example the following program displays The length is 3 because the identifier length is taken as the length property of the string abc with abc writeln The length is length You can nest with statements in this case references to identifiers are looked up in the successive default values from the innermost to the outermost with statement LANGUAGE REFERENCE MANUAL 199 200 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Built in values and functions Presents the built in values and functions of the IBM ILOG Script language for OPL numbers strings Booleans arrays objects dates the null and undefined values functions In this section Numbers Number representations and functions IBM ILOG Script strings String representation and functions IBM ILOG Script Booleans Boolean representation and functions IBM ILOG Script arrays Array representation and functions Objects Object representation and functions Dates Date representation and functions The null value Explains the use of the null value The undefined value Explains the use of the undefined value IBM ILOG OPL LANGUAGE REFERENCE MANUAL 201 IBM ILOG Script functions Describes the use of functions in IBM ILOG Script Miscellaneous functions Provides a reference of miscellaneous functions in IBM ILOG Script 202 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Numbers Nu
153. ou to write discontinuous piecewise linear functions This is the case when in the syntax of a piecewise linear function with slopes and break points two successive breakpoints are identical and the value associated with the second one is considered to be a step instead ofa slope The CPLEX and the CP Optimizer engines behave differently with respect to what limit they consider as the discontinuity value Because CPLEX allows either of these limits note that the anchor point used to ground the breakpoints and slopes must not reside at the discontinuity Otherwise the piecewise linear function would not be uniquely defined Behavior with the CPLEX engine Example 1 the sign function The following piecewise function plecewilse 0 gt 0 2 gt 0 0 1 1 x has a slope of 0 up to breakpoint 0 then a step of 2 at this break point then a slope of 0 It takes the value 1 at point 1 This piecewise represents the function sign which returns the sign 1 or 1 of its argument as represented in The discontinuous piecewise linear function sign Q IBM ILOG OPL LANGUAGE REFERENCE MANUAL 93 The discontinuous piecewise linear function sign Then this model over Tloet 2s ever EL tOet eronay dva CEOE dvar float signy maximize x subject to x 2 signx piecewise 0 gt 0 2 gt 0 0 1 1 x VY 328 signy piecewise 0 gt 0 2 gt 0 0 1 1 y gives the following output Final solution with objectiv
154. plicit slicing outside tuple patterns See also Modeling tips in the Language User s Manual IBM ILOG OPL LANGUAGE REFERENCE MANUAL 135 136 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Scheduling Describes how to model scheduling problems in OPL In this section Introduction Introduces the scheduling topic Piecewise linear and stepwise functions Describes piecewise linear and stepwise functions as related to scheduling Interval variables Describes a basic building block of scheduling the interval Unary constraints on interval variables Describes unary constraints on interval variables Precedence constraints between interval variables Describes precedence constraints between interval variables Constraints on groups of interval variables Describes constraints that act to encapsulate a group of intervals together A logical constraint between interval variables presenceOf The presence constraint on intervals Expressions on interval variables Describes the integer and numerical expressions available on interval variables IBM ILOG OPL LANGUAGE REFERENCE MANUAL 137 Sequencing of interval variables Describes a basic building block of scheduling the interval sequence Cumulative functions Describes the cumulative function State functions Describes the state function Notations The main notations used throughout the scheduling section are defined here 138 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Introd
155. pression These generic arrays may significantly simplify the modeling of an application The declaration IBM ILOG OPL LANGUAGE REFERENCE MANUAL 41 42 B M alinue ella alioh Gl sil atariles declares an array of 10 elements such that the value of a i is i 1 Generic arrays can of course be multidimensional as in Sime a Shia 5 SOS Set Oso lOy Worl xP os which initializes element m i j to10 i j Generic arrays are useful in performing some simple transformations For instance generic arrays can be used to transpose matrices in a simple way as in inte M DLI Osi 555 suave ei ia Da2 fal a Datel sealfah sy F More generally speaking generic arrays can be used to permute the indices of arrays in simple ways As generic indexed arrays To have more flexibility when initializing arrays in a generic way OPL enables you to control the index value in addition to the item value as described earlier in As generic arrays To illustrate the syntax the same examples can be expressed as follows gne utils ALO f abel 3 ak ak ih 2 VIL Ig He MO tO IOoo1O fa 8 3 8 MO ise dpa ai 110 Is This syntax is close to the syntax used for initializing arrays in dat files by means of indices delimited by and as explained in Specifying pairs Using this syntax is an efficient means of initializing arrays used to index data The oi1DB mod example contains an execute block that perf
156. pressions f related with a cumul function expression f are fixed that is their domain is reduced to a singleton f the value of the cumul function expression f is fixed and equal to the function f gt f t Constraints on cumul function expressions The following constraints can be expressed on a cumul function expression f Let Y zZ 7 and h Amin mar Z and a be an interval variable always n f u v hmin Pmax means that the values of function f must remain in the range Amin hmaxl everywhere on the interval u v alwaysin f a hmin Pmax means that if interval a is present the values of function f must remain in the range hmin hmax between the start and the end of interval variable a f lt hmnax means that function f cannot take values greater than hay It is semantically equivalent to alwaysIn f o0 20 0 hmar f Amin means that function f cannot take values lower than hmin It is semantically equivalent to alwaysIn f 00 00 hin 00 More formally alwaysIn f u v hminsdmaz Vt u v f t Amin Amaz alwaysIn f a hmin hmaz amp vt s a e a F t S Amins hmaz ILOG OPL LANGUAGE REFERENCE MANUAL Expressions on cumulative functions The following elementary cumul function expressions are based on an interval variable a pulse a h pulse a hmin Rmax StepAtStart a h stepAtStart a hmin hmax StepAtEnd a h and stepAtEnd a hmin
157. ral see Operators in the Language Quick Reference ILOG OPL LANGUAGE REFERENCE MANUAL Piecewise linear functions Piecewise linear functions are important in many applications They are often specified by giving a set of slopes a set of breakpoints at which the slopes change and the value of the functions at a given point Consider for instance a transportation problem in which the transportation cost between two locations o and d depends on the size of the shipment ship o d The piecewise linear expression The piecewise linear expression piecewise 10 gt 100 20 gt 200 40 0 0 ship o d describes the piecewise linear function of ship o d depicted in A Piecewise linear function The function has slopes 10 20 and 40 breakpoints 100 and 200 and evaluates to 0 at point O 40 3000 shiplo d 100 200 A Piecewise linear function In other words the piecewise linear expression is equivalent to the expression 10 ship o d when ship o d lt 100 equivalent to LO es OO sp 20 Silaaljos fo kell aL when IBM ILOG OPL LANGUAGE REFERENCE MANUAL _ 91 92 B M 100 lt ship o d lt 200 and equivalent to HO 100 a 20 200 a AQ aaae e 200 otherwise By default OPL assumes that a piecewise linear function evaluates to zero at the origin so that the above piecewise linear function could actually be written as piecewise 10 gt 100 20 gt 200 40 ship o d
158. rates the functionality ordered often useful in practical applications T can be one of the types int float string ora tuple type Important This ordering does not refer to the ordering associated with type T but to the order of the items within the set ILOG OPL LANGUAGE REFERENCE MANUAL Tuples of parameters OPL allows tuples of formal parameters to appear in aggregate operators forall statements and generic sets The code sample Tuple of formal parameters states precedence constraints between tasks The constraint declaration requires explicit accesses to the fields of the tuple to state the constraints In addition the field before is accessed twice An alternate way to state the same constraint is to use a tuple of formal parameters as shown in the last line of Tuple of formal parameters precluding the need to access the tuple fields explicitly The tuple lt p in Prec gt in the forall quantifier contains two components that are successively given the values of the fields of each tuple in Prec Tuple of formal parameters int minTime 7 60 int maxTime 9 60 string Tasks Make dinner Have dinner Clean post dinner tuple Precedence string pre SErINGEPOS E Precedence Prec lt Make dinner Have dinner gt lt Have dinner Clean post dinner gt ant Duretaon Tasks 20 60 10 dvar int Start Tasks in minTime maxTime subject to forall p in Prec Start p post gt Start p
159. ries or both Other company product or service names may be trademarks or service marks of others Acknowledgement The language manuals are based on and include substantial material from The OPL Optimization Programming Language by Pascal Van Hentenryck 1999 Massachusetts Institute of Technology Table of contents Language Reference Manual csseecccceeeseeeeeeeeeeeseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeseeeeeeeeeseeees 5 Why an Optimization Programming Language cccssccssseeesseeessseeeeseeessseeseseeeeeeseeseeeeeeeees 6 OPL the modeling language a e ceed rae rea raea E ae e ae aee r ae iaoa esateeweuedetesezedenunersscuerscunes 7 MOG SIS ies E ate ane erence le ce ea di at suet cabelas av eal 9 Building a model r a e a r E a a ava acu aa aa e a Ea a OESTE 10 Data TYPOS ET TE A E A N 13 Basic data type Sinna n EA A a a N A a a 15 Data structures i220 ieee eatin a ee a ed ed e a s 21 Data SOUICES jis dia eee HEA ee es a a aL ee et i ee 35 Data initialization gerir katxieedni ni ied at einen wiih aint dietitian 37 Database initialiZation s see Avie aah hid eee el a aaa i Ania eda ees 51 Spreadsheet InpuUt OutpUlt c2 tanneeention ih eens een atne ee 59 Datta CONSISTGNGY EET AE T EETA 67 Prepr cessing dat ctir aa aa aa Aaaa d aae A auzseshacddessnbecasheadhcaigesutaeeuacceaacaettane 72 Decisi n ypas lee ee e ae el Ne a ie A 75 Decision variables r niki hadi ads eal aad el aid Le cate eee 7
160. rse possible to define arrays of other basic types For instance the instructions rane etka o O AO SiO A float ANARA ale2e Bose Biot AS string d 1 2 Monday Wednesday declare arrays of natural numbers floats and strings respectively The index sets of arrays in OPL are very general and can be integer ranges and arbitrary finite sets In the examples so far index sets were given explicitly but it is possible to use a previously defined range as in range R 1 4 mae aR Op 20 30 ACs The declaration tag DENS 10 20 30 40 90 G0 TOI describes an array indexed by a set of strings its elements are a Monday a Sunday Arrays can also be indexed by finite sets of arbitrary types This feature is fundamental in OPL to exploit sparsity in large linear programming applications as discussed in detail in Exploiting sparsity in the Language User s Manual For example the declaration tuple Edges int orig int dest Boge Edges 4 lt 1 735 lt 144 gt a1 5 gt 5 int a Edges HOR ZO SOs defines an integer array a indexed by a finite set of tuples Its elements are a lt 1 2 gt a lt 1 4 gt and a lt 1 5 gt Tuples are described in detail in Tuples 24 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Multidimensional arrays OPL supports the declaration of multidimensional arrays see Data initialization about the ellipsis syntax For example the
161. s it must have the same width length as the array to be filled OPL automatically determines whether the data must be read line by line or column by column When facing a square zone a two dimensional array with x x as dimensions the engine reads the data line by line Only tuples with integer float and string components are supported Accessing named ranges in Excel IBM ILOG OPL supports the convention of names which are a word or string of characters used to represent a cell range of cells formula or constant value and that can be used in other formulas Thus you can use easy to understand names such as Nutrients to refer to hard to understand ranges such as B4 J15 or IncreasedProtein to refer to a constraint You can then substitute these names in formulas for the range of cells or constraint ILOG OPL LANGUAGE REFERENCE MANUAL Excel named ranges can be accessed using the SheetRead command using the following syntax SheetConnection sheetData C ILOG Files myExcelFile xls 1 prods from SheetRead sheetData Product The SheetRead command is normal and in this example the Excel name Product replaces the normal syntax of say C13 072 To create named ranges in Excel 2003 1 Highlight the range of cells you want to name then choose Insert gt Name gt Define from the main menu 2 Type the name you want to assign to this range and click OK 3 Save the spreadsheet file To create named ranges in Exc
162. s function arguments For example in the following program the script variables sum and res are local to the average function as well as the arguments a and b when average is called the global variables with the same names if any are temporarily hidden until exit from the function function average a b var sum atb var res sum 2 return res Script variables declared with var at any place in a function body have a scope which is the entire function body This is different from local variable scope in C or C For example in the following function the variable res declared in the first branch of the if statement is used in the other branch and in the return statement function max x y ae oe gt Ww i VAE EGOS EK else res y return res Outside a function definition At the same level as function definitions script variables declared with var are local to the current program unit A program unit is a group of statements which is considered a whole the exact definition of a program unit depends on the application in which the script is 196 IBM ILOG OPL LANGUAGE REFERENCE MANUAL B M embedded Typically a script file loaded by the application is treated as a program unit In this case variables declared with var at the file top level are local to this file and they hide any global variables with the same names For example suppose that a file contains the following program var cou
163. s of an e or E followed by an optional or sign and a sequence of digits A decimal number must have at least one digit Here are some examples of decimal number literals 15 sam 4e100 25 5 25e 10 206 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Hexadecimal numbers A hexadecimal number consists of a 0x or 0x prefix followed by a sequence of hexadecimal digits which include digits 0 9 and the letters a f or A F For example OSRIR 0x0 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 207 Octal numbers An octal number consists of a 0 followed by a sequence of octal digits which include the digits 0 7 For example 0123 0777 208 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Special numbers B M There are three special numbers NaN Not A Number Infinity positive infinity and Infinity negative infinity The special number NaN is used to indicate errors in number manipulations For example the square root function Math sqrt applied to a negative number returns NaN There is no representation of NaN as a number literal but the global script variable NaN contains its value The NaN value is contagious and a numeric operation involving NaN always returns NaN A comparison operation involving NaN always returns false even the NaN NaN comparison Examples of NaN Math sqrt 1 NaN Math sqrt NaN NaN NaN 3 NaN NaN NaN false NaN lt 3 false NaN gt 3 false The special numbers Infinity
164. se of strings in IBM ILOG Script Automatic conversion to a string Explains how strings are automatically converted in functions String properties Provides a reference for the properties of strings String methods Provides a reference for string methods String functions Provides a reference of string functions String operators Provides a reference of string operators IBM ILOG OPL LANGUAGE REFERENCE MANUAL 217 Introduction A string literal is zero or more characters enclosed in double or single quotes Note For C C programmers Except for the use of single quotes string literals have the same syntax as in C and C Here are examples of string literals My name is Hal My name is Hal Hi there he said nga Hello world n In these examples the first and second strings are identical The backslash character can be used to introduce an escape sequence which stands for a character which cannot be directly expressed in a string literal Escape sequences in strings Escape sequence standsfor OOOO SS Backslash character y Double quote xhh The character whose ASCII code is hh where hh is a sequence of two hexadecimal digits ooo The character whose ASCII code is 000 where ooo is a sequence of one two or three octal digits Here are examples of string literals using escape sequences 218 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Examples of string liter
165. sheetData Product The SheetWrite command is normal and in this example the Excel name Product replaces the normal syntax of say C13 072 For more information on named ranges see Accessing named ranges in Excel IBM ILOG OPL LANGUAGE REFERENCE MANUAL _ 65 66 B M ILOG OPL LANGUAGE REFERENCE MANUAL Data consistency Defines the purpose of data consistency and describes data membership and assertions as ways to ensure consistency In this section Purpose Provides an overview of data consistency issues in OPL Data membership consistency Explains the use of the with keyword to ensure data consistency Assertions Explains the use of assertions with regard to data consistency IBM ILOG OPL LANGUAGE REFERENCE MANUAL 67 Purpose For an optimization problem to give relevant solutions it is fundamental that you provide good quality data to your projects In particular it may be interesting to check that the data is consistent If the project data is not consistent the solving engine may find a wrong solution or no solution and you may think that the model is erroneous and therefore waste time trying to improve it OPL offers several ways to check the consistency of the data used by your projects In particular Data membership consistency use the keyword with to ensure that cells of a given tuple in a tuple set correctly belong to a given set of possible values Note You can also use the k
166. so possible and desirable for larger problems to index arrays of decision variables by finite sets For example the excerpt tuple Route CREVO City dest Route routes 2 dvar int transp routes in 0 1007 declares an array of decision variables transp that is indexed by the finite set of tuples routes Genericity can be used to initialize the domain of the variables For example the excerpt tuple Route Caty Oele City dest Route routes ILOG OPL LANGUAGE REFERENCE MANUAL B M int capacity routes o 3 7 olyetie tiae caineal ahicl imowices atic O5 a zejoevouliciy se 2 declares an array of decision variables indexed by the finite set routes such that variable transp r ranges over 0 capacity r The array capacity is also indexed by the finite set routes Note that decision variables can be declared to range over a user defined range For example the excerpt range Capacity 0 limitCapacity dvar int transp Orig Dest in Capacity declares an array of integer variables ranging over Capacity Decision variables can of course be declared individually as in dvar int averageDelay in 0 maxDelay For convenience OPL proposes the types float int and boolean to define the domain of a decision variable The declarations dvar int x non negative integer decision variable dvar float y non negative decision variable dvar boolean z boolean decision variable
167. ssed this way myArray 10 Illegal syntax For these properties use the second syntax value name Same as the previous syntax except that this time name is an evaluated expression which gives the property name Examples str length Same as str length getCar getPropertyName myArray 10 myArray i 1 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 185 Assignment operators The equals operator can be used to assign a new value to a script variable or a property Assignment operator syntax variable expression In scripting all objects are assigned by reference except strings numbers and Booleans which are assigned by value See the ECMA standard for details Example x ytl The whole expression returns the value of expression value name expression Assigns the value of expression to the given property value name expression If value does not have such a property then if it is either an array or an object the property is created otherwise an error is signalled Example car name Ford myArray i myArray i 1 The whole expression returns the value of expression In addition shorthand operators are also defined 186 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Function calls Syntactic shorthand Same as xX but returns the initial value of x instead of its new value function argl Calls function with the given arguments and returns the result of the call Examples
168. t viy e Vt gt tn P t vast For a complete description of the OPL syntax of a stepwise linear function see stepwise and stepFunction in the OPL Language Quick Reference Examples The following piecewise and stepwise function are depicted in the diagram below A V shape function with value 0 at x 10 slope 1 before x 10 and slope s afterwards pwlFunction F1 piecewise 1 gt 10 s 10 0 An array of V shaped functions indexed by i in 1 n with value 0 at TTi slope U i before T i and slope V i afterwards T U and V are data integer arrays pwlFunction F i in 1 n piecewise U i gt T i V i T i 0 A stepwise function with value 0 before 0 100 on 0 20 value 60 on 20 30 and value 100 later on stepFunction F2 stepwise 0 gt 0 100 gt 20 60 gt 30 100 A stepwise function with value 0 everywhere except on intervals 7i 7i 5 for i in 0 51 where the value is 100 stepFunction F3 stepwise i in 0 51 p in 0 1 100 p gt 7 i 5 p 0 ILOG OPL LANGUAGE REFERENCE MANUAL S F3 20 30 x 5 7 12 14 19 21x Examples of piecewise linear and stepwise functions IBM ILOG OPL LANGUAGE REFERENCE MANUAL 143 Interval variables 144 B M Informally speaking an interval variable represents an interval of time during which something happens a task an activity is carried out and whose position in time is an unknown of t
169. te of the function to be defined cannot overlap a given fixed or variable interval alwaysNoState That everywhere over a given fixed or variable interval the state of the function if defined must remain within a given range of non negative states Vmin Vmax alwaysIn Additionally the two first constraints can be complemented to specify that the given fixed or variable interval should have its start and or end point synchronized with the start and or end point of the interval of the state function that maintains the required state This is the notion of start and end alignment which is particularly useful for modelling parallel batches For instance in the oven example above all interval variables that would require an oven IBM ILOG OPL LANGUAGE REFERENCE MANUAL 163 temperature of level 1 and specify a start and end alignment if executed over the interval 150 250 would have to start exactly at 150 and end at 250 This is depicted in the following figure where a and az are two start and end aligned interval variables a3 is start aligned only and a is not aligned at all dl 0 100 200 300 400 500 600 State function and interval variable alignments State functions and transition distance A state function fis a decision variable whose value is a set of non overlapping intervals each interval s e being associated a non negative integer value vj that represents the state of the function over the
170. terns in decision expressions 28 tuple sets external initialization 38 referring to other sets with keys 70 sorted 31 tuple sets sorted 32 tuple OPL keyword 26 tuples 26 and data consistency 69 data types 28 initialization 45 keys in declaration 26 limitations 28 of parameters 133 filtering 134 undefined value 256 union OPL keyword 98 updating a database 57 values and functions IBM ILOG Script 233 values in IBM ILOG Script and functions Booleans 227 dates 247 decimal numbers 206 hexadecimal numbers 207 numbers 203 objects 239 special numbers 209 strings 217 null 255 undefined 256 values in IBM ILOG Script assignment operators 186 default 199 of properties accessing 185 IBM ILOG OPL LANGUAGE values in ILOG Script and functions octal numbers 208 var IBM ILOG Script keyword 196 variables See script variables while IBM ILOG Script keyword loop syntax 194 with IBM ILOG Script keyword 199 with OPL keyword 69 REFERENCE MANUAL
171. tions amp Engine log la Statistics Profiler Se 3 errors 0 warnings 0 others Description Resource Path Location Type amp Errors 3 items gS Model assertion ct failed i 2 Projecti mod Project 7 26 7 33 C ILOG OPL6 1 projects Project1 Projecti mod OPL Problem Marker Model assertion ct failed i 3 Projecti mod Projecti 7 26 7 33 C ILOG OPL6 1 projects Project1 Projecti mod OPL Problem Marker Model assertion failed Projecti mod Project1 7 1 7 33 C ILOG OPL6 1 projects Project1 Project1 mod OPL Problem Marker Labeled assert 112 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Limitations to constraint labeling Not all constraints can be labeled Limitations exist with respect to forall statements and to variable size indexer Labels and forall statements You can label only constraints that are not nested within a forall statement leaf constraints However you can label a forall constraint if it is at the root level of constraints For example in the code sample Constraint label within forall statement the constraint Hels ieoreetilll ae aliqy s il amoa eyilil 5 alin 122 gt lt p Sh Sr e can also be written OSE UL IL Cay aka Weil aoee ula alist ie wreils KE S aarg e In both cases the model executes correctly However if you execute EOE wll al alin xeil y CELS Yeo we lil 5 alia se2 d fat J 5 i lt Le the IDE reports Element ct1 has never been use
172. ts due to incorrect input data In their simplest form assertions are simply Boolean expressions that must be true otherwise they raise an execution error For instance it is common in some transportation problems to require that the demand matches the supply The declaration int demand Customers int supply Suppliers eset assert sum s in Suppliers supply s sum c in Customers demand c makes sure that the total supply by the suppliers meets the total demand from the customers This assertion can be generalized to the case of multiple products as in int demand Customers Products int supply Suppliers Products eats is assert Oval save pe SAUCES sum s in Suppliers supply s p sum c in Customers demand c p This assertion verifies that the total supply meets the total demand for each product The use of assertions is highly recommended since they make it possible to detect errors in the data input early avoiding tedious inspection of the model data and results Assertions can be labeled See Labeled assert statements IBM ILOG OPL LANGUAGE REFERENCE MANUAL 71 Preprocessing data 72 B M You can preprocess data before the optimization model is created by using IBM ILOG Script JavaScript syntax encapsulated in execute blocks OPL provides script integration with the modeling language All declared model elements are available for scripting via their name The functionality avail
173. u to see the difference between the union of ordered sets and the union of sorted sets Sorted sets Ae S Ss Ay ela aie S2 al Dis int orderedS sl union s2 sorted int sortedS sl union s2 execute writeln ordered union orderedsS writeln sorted union sortedS The statement int orderedS sl union s2 returns ordered union 3 5 1 4 2 ILOG OPL LANGUAGE REFERENCE MANUAL 31 32 B M while the statement sorted int sortedS sl union s2 returns sorted union i 2 3 4 5 Sorted tuple sets When a tuple set uses no keys the entire tuple except set and array fields is taken into account for sorting For tuple sets with keys sorting takes place on all keys in their order of declaration In other words it is not possible to sort a tuple set on one or more given column s only The code extract below Sorted tuple sets declares a team of people who are defined by their first name last name and nickname then prints the list of team members first in the creation order then in alphabetical order Sorted tuple sets tuple person string firstname string lastname string nickname tuple personKeys key string firstname key string lastname string nickname person devTeam KDewiakelt VAE EL VEVEN n E Derre Wiper WS ens lt Sregorys SSmo E Tupari WiSimlici e VEES Eeyan oea VET lt Gregory McNamara Mac gt sorted p
174. uction ILOG OPL and ILOG CP Optimizer introduce a set of modelling features for applications dealing with scheduling over time In OPL and CP Optimizer time points are represented as integers but the possible very wide range of time points means that time is effectively continuous A consequence of scheduling over effectively continuous time is that the evolution of some known quantities over time for instance the instantaneous efficiency speed of a resource or the earliness tardiness cost for finishing an activity at a given date t needs to be compactly represented in the model To that end CP Optimizer provides the notion of piecewise linear and stepwise functions Most scheduling applications consist in scheduling in time some activities tasks or operations that have a start and an end time In CP Optimizer this type of decision variable is captured by the notion of the interval variable Several types of constraints are expressed on and between interval variables to limit the possible positions of an interval variable forbidden start end or extent values to specify precedence relations between two interval variables to relate the position of an interval variable with one of a set of interval variables spanning synchronization alternative An important characteristic of scheduling problems is that time intervals may be optional and whether to execute a time interval or not is a possible decision variable In CP Opt
175. uence of your model See Profiling the execution of a model in IDE Tutorials See IBM ILOG Script for OPL for details on the scripting language and its extensions for OPL Lazy instantiation It is important to be aware from OPL 5 2 onwards that during the process declared elements are instantiated on demand when referenced for the first time See Data preprocessing in Migration from OPL 3 x CP projects for migration aspects LANGUAGE REFERENCE MANUAL 73 74 B M ILOG OPL LANGUAGE REFERENCE MANUAL Decision types Variables in an OPL application are decision variables dvar OPL also supports decision expressions that is expressions that enable you to reuse decision variables dexpr A specific syntax is available in OPL to dynamically collect elements into arrays In this section Decision variables Describes what decision variables are in OPL Expressions of decision variables Describes decision variable expressions in OPL Dynamic collection of elements into arrays Discusses the all syntax explicit arrays appending arrays and dynamic initialization of decision variable arrays IBM ILOG OPL LANGUAGE REFERENCE MANUAL 75 Decision variables 76 B M Shows how to declare and use decision variables in the OPL language A decision variable is an unknown in an optimization problem It has a domain which is a compact representation of the set of all possible values for the
176. x converts rectangular coordinates x y to polar coordinates r a by computing a as an arc tangent of y x in the range pi to pi x Math log x Math log x computes the natural logarithm of x Math pow x y Math pow x y computes x raised to the power y x Math cos x Math cos x returns the trigonometric function cosine of a radian argument Math tan x Math tan x returns the trigonometric function tangent of a radian argument iK Math sin x Math sin x returns the trigonometric function sine of a radian argument cos i i Math floor x Math floor x returns the greatest integer value less than or equal to x x 212 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Numeric constants The following numeric constants are defined Numeric constants Napier s constant e and the base of natural logarithms approximately 2 718 The natural logarithm of 10 approximately 2 302 The natural logarithm of 2 approximately 0 693 IBM ILOG OPL LANGUAGE REFERENCE MANUAL 213 Numeric operators l Note For C C programmers The numeric operators are the same as in C and C Numeric operators The usual arithmetic operations Examples 3 4 2 7 2 100 120 20 4 7 1 28 46 51 2 Negation Examples 142 142 Returns the floating point remainder of dividing x by y Examples 12 52 12 5 52 5 The operator returns true if x and y are equal and false oth
177. xpressions are equivalent to a wol SRE Se CQ Jo which is itself equivalent to el ogol 5k Wi Fe ws Jo ILOG OPL LANGUAGE REFERENCE MANUAL Constraints Specifies the constraints supported by OPL and discusses various subclasses of constraints to illustrate the support available for modeling combinatorial optimization applications In this section Introduction Provides an overview of the use of constraints in OPL Using constraints Explains how to apply a constraint to a decision variable and possibly conditionalize it why identify constraints by a label and why use constraints for filtering purposes Constraint labels Explains why label constraints the benefits costs and limitations how to label constraints how to use indexed labels and how to deal with compatibility between constraint names and labels Types of constraints Describes constraint classification depending on their operand type IBM ILOG OPL LANGUAGE REFERENCE MANUAL 101 Introduction Constraints are a subset of Boolean expressions The availability of certain constraints depends on their context The contexts can be Data initialization when declared data is assigned Optimization model a constraints block a subject to block An expression that filters an iteration for aggregation or generation 102 IBM ILOG OPL LANGUAGE REFERENCE MANUAL Using constraints Explains how to apply a constraint to a decision variable and poss
Download Pdf Manuals
Related Search
Related Contents
Sunbeam HS9500 User's Manual 3D GeoModeller Tutorial Case Study J Ficha producto HP 920 Black Officejet Ink Cartridge Dahle Personal Shredder 20090 MDCMS - User Manual Copyright © All rights reserved.
Failed to retrieve file