Modeling and problem solving with
Xpress-Mosel
FICO Xpress Training
S. Heipcke
Xpress Team, FICO
http://www.fico.com/xpress

The material in this presentation is the property of Fair Issac Corporation, is provided for the recipient only, andshall not be used, reproduced, or disclosed without Fair Isaac Corporation’s express consent.
c 2010 Fair Issac Corporation.

Introduction, Xpress overview

c 2010 Fair Issac Corporation.

Topics» Introduction to Xpress» Modeling with Mosel:» Linear and Mixed Integer Programming (LP and MIP)
» Accessing data sources» Programming language features» Embedding models in applications

c 2010 Fair Issac Corporation.

Aims» At the end of the course you will
» be familiar with optimization methods and theterminology used to describe them
» be confident about formulating optimization models
and understanding the solution» know how use Xpress to model and solve problems» be able to embed a model in a application

c 2010 Fair Issac Corporation.

Other materials» Not a replacement for the reference manuals!
» Focuses on areas that are of practicalimportance» Does not try to be exhaustive» Pointers to reference material at the end of
every chapter

c 2010 Fair Issac Corporation.

Overview of Xpressc 2010 Fair Issac Corporation.

Overview of Xpress» Optimization algorithms» enables you to solve different classes of problems» built for speed, robustness and scalability» Modeling interfaces» enables you to provide your problem in the mostsuitable way for your application» built for ease of use and interfacingc 2010 Fair Issac Corporation.

Optimization algorithms

Optimizer
Simplex

MIP

Primal & Dual

Branch & Cut

Barrier
LP

QCQP

c 2010 Fair Issac Corporation.

MIP

MIQP

SLP
MIQCQPNLP MINLP

Modeling interfaces» Mosel» formulate model and develop optimization methods
using Mosel language / environment» BCL» build up model in your application code using
object-oriented model builder library» Optimizer» read in matrix files» input entire matrix from program arraysc 2010 Fair Issac Corporation.

Mosel» A modeling and solving environment» integration of modeling and solving» programming facilities» open, modular architecture» Interfaces to external data sources (e.g. ODBC,
host application) provided» Language is concise, user friendly, high level» Best choice for rapid development anddeploymentc 2010 Fair Issac Corporation.

Mosel:Components and interfaces» Mosel language: to implement problems andsolution algorithms⇒ model or Mosel program» Mosel Model Compiler and Run-time Libraries:
to compile, execute and access models from a
programming language⇒ C/C++, C#, Java, or VB programc 2010 Fair Issac Corporation.

Mosel:Components and interfaces» Mosel Native Interface (NI): to provide new or
extend existing functionality of the Mosel
language⇒ module» Xpress-IVE: graphical user interface,
representation of the problem matrix, solution
status/progress graphs, and result display

c 2010 Fair Issac Corporation.

Mosel Libraries» Embed Mosel models directly in yourapplication» Access the solution within your application» Compiled models are platform independent» Enjoy benefits of structured modelinglanguage and rapid deployment whenbuilding applications» Available for C, Java, C#, and VB

c 2010 Fair Issac Corporation.

Xpress-IVE» Visual Studio style visual development
environment for optimization & modelbuilding with Mosel» Mosel model editor & compiler» Real time graphs show optimization
performance» Browse solution values in entity treec 2010 Fair Issac Corporation.

Mosel and Optimizer Consoles» Stand-alone command line executables withtext interfaces» Useful for simple deployment usingbatch/script files» Available for all platforms supported by Xpressc 2010 Fair Issac Corporation.

Why use modeling software?

c 2010 Fair Issac Corporation.

Why use modeling software?

Model
Problemconception

Computational
problem instanceInterpretation& analysis

Computational
solution instanceHumanc 2010 Fair Issac Corporation.

Model solution

ComputerWhy use modeling software?

» Developing a working model is the difficult bit» Important to have software that helps» speed to market» verify correctness» maintenance & modification» algorithmic considerations» execution speedc 2010 Fair Issac Corporation.

Xpress modeling software» The concepts we describe – how to formulate
and solve problems – apply to all modelingsoftware» In this course we will use the Xpress-IVE
development environment with theXpress-Mosel language because it is» easy to understand and learn» easy to use

c 2010 Fair Issac Corporation.

Xpress-IVE demonstration

c 2010 Fair Issac Corporation.

Xpress-IVE demonstration» Models: new, saving, opening, switching
start a new model
open an existing model
save current modelshow list of available modules» Bars: editor, entity, info, output (run)switch between window layouts

c 2010 Fair Issac Corporation.

Xpress-IVE demonstration» Editor: colors, auto-complete, tool tips
copy selection
cut selection
paste selection
go to next / last line with same indentation
go to previous / next cursor position (line)
undo / redo last editor commandc 2010 Fair Issac Corporation.

Xpress-IVE demonstration» Compile, runcompile current model
execute current model
open run options dialog
pause execution
interrupt execution
search for the N best solutions
start infeasibility repair

c 2010 Fair Issac Corporation.

Xpress-IVE demonstration» Output bar: log, stats, matrix, graphs, tree
» Viewing solution values» Problem and matrix export and import
generate BIM fileexport the problem matrix
optimize an imported matrix

c 2010 Fair Issac Corporation.

Xpress-IVE demonstration» Search, bookmark
searchdelete bookmarks» Helphelp
model generation wizzard & example models
module generation wizzard

c 2010 Fair Issac Corporation.

Xpress-IVE demonstration» Debugger
set/delete breakpoint at cursor
define conditional breakpoint
start/stop debugger
step over an expression
step into an expression
run up to the cursor
show debugger options dialog» Profiler
start the profilerc 2010 Fair Issac Corporation.

Reference material» The manual Getting Started with Xpress
introduces first time or occasional users tomodeling with Mosel and BCL, or the direct
Optimizer interface» The Evaluators Guide and Advanced
Evaluators Guide provide a quick
walk-through of the Getting Started examples
and some more advanced featuresc 2010 Fair Issac Corporation.

The material in this presentation is the property of Fair Issac Corporation, is provided for the recipient only, andshall not be used, reproduced, or disclosed without Fair Isaac Corporation’s express consent.
c 2010 Fair Issac Corporation.

Modeling with Mosel

c 2010 Fair Issac Corporation.

Overview» Modeling basics» Accessing data sources» Advanced modeling topics» Programming language
features» Mosel modules and packages

c 2010 Fair Isaac Corporation.

Modeling basics» A first model» Data structures and loops» Model building stylec 2010 Fair Issac Corporation.

Topics» Definition of decision variables and constraints» Solving with Xpress-Optimizer» Solution output

c 2010 Fair Issac Corporation.

Example: Chess problem» A joinery makes two different sizes of
boxwood chess sets.
» The small set requires 3 hours of machining ona lathe, and the large set requires 2 hours.
There are 4 lathes with skilled operators whoeach work a 40 hour week.
» The small chess set requires 1 kg of boxwood,and the large set requires 3 kg. Only 200 kg of
boxwood can be obtained per week.

c 2010 Fair Issac Corporation.

Example: Chess problem» Each of the large chess sets yields a profit of$20, and one of the small chess sets has a
profit of $5.
» How many sets of each kind should be madeeach week so as to maximize profit?

c 2010 Fair Issac Corporation.

Chess problem:
Mathematical formulation» xl – quantity of large chess sets madexs – quantity of small chess sets mademax z = 5 · xs + 20 · xls.t.

3 · xs + 2 · xl ≤ 160(= 4 · 40) (lathe time)
xs + 3 · xl ≤ 200
xs, xl ≥ 0

c 2010 Fair Issac Corporation.

(wood)

Chess problem:
Graphical solutionxl
120
optimal solution
80

40
z=2000z=160040

80
time

c 2010 Fair Issac Corporation.

120

160
z=400

200

240

280

xs
z=1200

z=800

wood

Chess problem:
Model Chess 1

model "Chess 1"
uses "mmxprs"! Use Xpress-Optimizer for solving

declarations
xs: mpvar
xl: mpvar
end-declarations! Number of small chess sets
! Number of large chess sets

3*xs + 2*xl <= 160
xs + 3*xl <= 200! Constraint: limit on working hours! Constraint: raw mat. availability

maximize(5*xs + 20*xl)! Objective: maximize total profit

end-model

c 2010 Fair Issac Corporation.

Starting and ending a Mosel model

model "Chess 1"...
end-model

c 2010 Fair Issac Corporation.

Preamble» uses statement: Say we will use theXpress-Optimizer library, so that we can solve
our problem» Options:» noimplicit: force all objects to be declared» explterm: Use ’;’ to mark line ends
uses ’mmxprs’
options noimplicit
options explterm

c 2010 Fair Issac Corporation.

Decision variables» mpvar means mathematical programming
variable or decision variable» Decision variables are unknowns: they have novalue until the model is run, and the optimizer
finds values for the decision variables

c 2010 Fair Issac Corporation.

Decision variables» In optimization problems, decision variables
are often just called variables» In computer programs, a variable can be used
to refer to many different types of objects» For instance, in Mosel models, a program
variable can be used to refer to a decisionvariable, as well as integers, reals, etc.

c 2010 Fair Issac Corporation.

Bounds on decision variables» Variables can take values between 0 andinfinity by default» Other bounds may be specified
x <= 10y(1) = 25.5y(2) is_freez(2,3) >= -50z(2,3) <= 50

c 2010 Fair Issac Corporation.

Constraints» Have type linctr – linear constraint
declarations
Wood: linctr
Inven: array(1..10) of linctr
end-declarations

c 2010 Fair Issac Corporation.

Constraints» The ‘value’ of a constraint entity is a linear
expression of decision variables, a constraint
type, and a constant term
» Set using an assignment statement
Wood := xs + 3*xl <= 200

c 2010 Fair Issac Corporation.

Objective function» An objective function is just a constraint withno constraint typedeclarations
MinCost: linctr
end-declarations
MinCost := 10*x(1) + 20*x(2) + 30*x(3) + 40*x(4)c 2010 Fair Issac Corporation.

Optimization &matrix generation» Generate the matrix and solve the problem:
minimize(MinCost)
maximize(5*xs + 20*xl)» Load the matrix:
loadprob(MinCost)» Matrix export:
exportprob(0, "explout", MinCost)

c 2010 Fair Issac Corporation.

Viewing the solution» Can access and manipulate the solution values
within the model
writeln(’Solution: ’, getobjval)
writeln(’xs = ’, getsol(xs))
writeln(’xl = ’, getsol(xl))
write(’Wood: ’, getact(Wood), ’ ’)
writeln(getslack(Wood))» Solution values of constraints
activity value + slack value = RHS

c 2010 Fair Issac Corporation.

Project work [C-1]:
Chess problem» Execute the model chess1.mos.
» Add printing of the solution values.
» Is the solution realistic/desirable?
» Constrain the variables to take integer values
only.
» Add output of constraint activity and slack
values.

c 2010 Fair Issac Corporation.

Project work [C-1]:
Chess problem» Executing model chess1.mos with IVE:
» double click on the model file to start IVE or open thefile from within IVE» click on the run button:» Model execution from the command line:
mosel -c "exe chess1.mos"

» or:
mosel
exe chess1.mosquit

c 2010 Fair Issac Corporation.

Solution:
Completed model Chess 1
model "Chess 1 (completed)"
uses "mmxprs"
declarations
xs,xl: mpvar
end-declarations! Use Xpress-Optimizer for solving! Decision variables

Profit:= 5*xs + 20*xl
Time:=
3*xs + 2*xl <= 160
Wood:=
xs + 3*xl <= 200
xs is_integer; xl is_integer! Name the objective function! and the constraints

maximize(Profit)! Objective: maximize total profit! Integrality constraints

writeln("Solution: ", getobjval) ! Print objective function value
writeln("xs: ", getsol(xs), " xl: ", getsol(xl)) ! Print sol. val.s
write("Time: ", getact(Time)) ! Constraint activity
writeln(" ", getslack(Time))! and slack
end-model

c 2010 Fair Issac Corporation.

Solution analysis» What happens if machines operate 35 insteadof 40 hours?
xl120
optimal solution
80

40
z=2000z=1600
40

80
time

120

160
z=400

200

240

280

z=800

wood

» Calculate spare capacity: getslack,getactivity
c 2010 Fair Issac Corporation.

xsz=1200LP solution analysis» What is the cost of an extra unit of wood/extra
working hour?
xl120
optimal solution
80

40
z=2000z=1600
40

80
time

120

160
z=400

» Reduced cost: getrcost

c 2010 Fair Issac Corporation.

200

240

280

xs
z=1200

z=800

wood

LP solution analysis» What is the cost of producing an additional
unit of each product?
xl
120
optimal solutions
80

40

z=2000
40

80
time

120
z=400

160

200
z=800

240
z=1200

280
wood

xs
z=1600» Dual values (’shadow prices’): getdual» Increase price of xl to reach break even pointc 2010 Fair Issac Corporation.

Solution analysis» Limit the amount of xl.
xl
120
optimal solution
80
xl=50
40
z=2000z=160040

80
time

c 2010 Fair Issac Corporation.

120

160
z=400

200

240

280

xs
z=1200

z=800

wood

Extending the example:
Model Chess 2
uses "mmxprs"
options explterm
declarations
Allvars: set of mpvar;
DescrV: array(Allvars) of string;
xs,xl: mpvar;
end-declarations! Use ’;’ to mark line ends

! Set of variables! Descriptions of variables

DescrV(xs):= "Small"; DescrV(xl):= "Large";
Profit:= 5*xs + 20*xl;
Time:=
3*xs + 2*xl <= 160;
Wood:=
xs + 3*xl <= 200;xs is_integer; xl is_integer;! Objective function! Constraints

maximize(Profit);
writeln("Solution: ", getobjval);
forall(x in Allvars) writeln(DescrV(x), ": ", getsol(x));

c 2010 Fair Issac Corporation.

Data structures» Set: unordered collection of objects of thesame type» used as index sets
» special type range sets (= interval of integers)» Array: multidimensional table of objects ofthe same type» used for data, decision variables, constraints» may be dynamic or staticc 2010 Fair Issac Corporation.

Arrays and loops:
Model Chess 3
uses "mmxprs"
declarations
R = 1..2
DUR, WOOD, PROFIT: array(R) of real
x: array(R) of mpvar
end-declarations! Index range! Coefficients! Array of variables

DUR:: [3, 2]
WOOD:: [1, 3]
PROFIT :: [5, 20]! Initialize data arrayssum(i in R) DUR(i)*x(i) <= 160
sum(i in R) WOOD(i)*x(i) <= 200
forall(i in R) x(i) is_integer
maximize(sum(i in R) PROFIT(i)*x(i))
writeln("Solution: ", getobjval)! Constraint definitionc 2010 Fair Issac Corporation.

Data declaration

declarationsNWEEKS = 20
DATA_DIR = ’c:/data’
NPROD: integer
SCOST: real
DIR: string
IF_DEBUG: boolean
PRODUCTS = {"P1", "P2", "P4"}
S: set of integer
R: range
COST: array(1..3,1..4) of real
end-declarations

c 2010 Fair Issac Corporation.

! Integer constant! String constant! Integer variable! Real variable! String variable! Boolean variable! Constant set of string! Variable set of integer! Range of integers! Array of real

Data initialization

NPROD:= 50
SCOST:= 5.4
DIR:= ’c:/data’
IF_DEBUG:= true
S:= {10, 0, -5, 13}
R:= 1..NPROD
COST:: [11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34]

c 2010 Fair Issac Corporation.

Summations» Sum up an array of variables in a constraint
Ctr1:= sum(p in 1..10) (RES(p)*buy(p) + sell(p)) <= 100
Ctr2:= sum(p in PRODUCTS) (buy(p) + sum(r in 1..5) make(p,r)) <= 100
Ctr3:= sum(p in 1..NP) (2*CAP(p)*buy(p)/10 +SCAP(p)*sell(p)) <= MAXCAP

c 2010 Fair Issac Corporation.

Loops» Use a loop to assign an array of constraints
forall(t in 2..NT)Inven(t):= bal(t) = bal(t-1) + buy(t) - sell(t)c 2010 Fair Issac Corporation.

Loops» Use do/end-do to group several statements
into one loop
forall(t in 1..NT) do
MaxRef(t):= sum(i in PRODUCTS)
use(i,t) <= MAXREF(t)Inven(t):= store(t) = store(t-1) + buy(t) - use(t)end-doc 2010 Fair Issac Corporation.

Loops» Can nest forall statements
forall(t in 1..NT) do
MaxRef(t):= sum(i in 1..NI) use(i,t) <= MAXREF(t)forall(i in 1..NI)Inven(i,t):= store(i,t) = store(i,t-1) + buy(i,t) - use(i,t)
end-doc 2010 Fair Issac Corporation.

Conditions» May include conditions in sums or loops
forall(c in 1..10 | CAP(c)>=100.0)
MaxCap(c):=sum(i in 1..10, j in 1..10 | i<>j)
TECH(i,j,c)*x(i,j,c) <= MAXTECH(c)c 2010 Fair Issac Corporation.

Mosel statements» Can extend over several lines and use spaces» However, a line break acts as an expression
terminator» To continue an expression, it must be cut after
a symbol that implies continuation (e.g. + - , )c 2010 Fair Issac Corporation.

Model building style» You should aim to build a model with sectionsin this order» constant data: declare, initialize» all non-constant objects: declare» variable data: initialize / input / calculate» decision variables: create, specify bounds» constraints: declare, specify» objective: declare, specify, optimize

c 2010 Fair Issac Corporation.

Model building style» In both LP and MIP it is very important todistinguish between» known values» data, parameters, etc.
» and unknown values» decision variables» All constraints must be linear expressions of
the variables

c 2010 Fair Issac Corporation.

Model building style» Suggestion: name objects as follows» known values (data) using upper case
» unknown values (variables) using lower case» constraints using mixed caseso that it is easy to distinguish between them,and see that constraints are indeed linearc 2010 Fair Issac Corporation.

Model building style» Variables are actions that your model willprescribe» Use verbs for the names of variables» this emphasizes that variables represent ‘what to do’decisions» Indices are the objects that the actions are
performed on» Use nouns for the names of indicesc 2010 Fair Issac Corporation.

Model building style» Using named index sets/ranges» improves the readability of a model» makes it easier to apply the model to different sizeddata sets» makes the model easier to maintain» may speed up your modelc 2010 Fair Issac Corporation.

Model building style» Try to include ‘Min’ or ‘Max’ in the name ofyour objective function» An objective function called ‘Obj’ is not very
helpful when taken out of context!

c 2010 Fair Issac Corporation.

Model building style» Comments are essential for a well written
model» Always use a comment to explain what eachparameter, data table, variable, and constraint
is for when you declare it» Add extra comments to explain any complex
calculation etc.

c 2010 Fair Issac Corporation.

Model building style» Comments in Mosel:
declarations
PRODUCTS = 1..NP! Set of products
TIMES = 1..NT! Set of time periods
make: array(PRODUCTS, TIMES) of mpvar! Amount of p produced in time t
sell: array(PRODUCTS, TIMES) of mpvar! Amount of p sold in time t
end-declarations(! And here is a multi-line
comment !)forall(t in TIMES)

c 2010 Fair Issac Corporation.

Accessing data sources» The initializations block» Dynamic arrays» Run-time parameters» Using other data sources

c 2010 Fair Issac Corporation.

Topics» Text files» ODBC» Sparse datac 2010 Fair Issac Corporation.

Separation of problem logic anddata» Typically, the model logic stays constant once
developed, with the data changing each run» Editing the model can create errors, expose
intellectual property, and is impractical forindustrial size data
» It makes good sense to fix the model andobtain data from their sourcec 2010 Fair Issac Corporation.

Data input from file: Chess 4
uses "mmxprs"
declarations
PRODS = 1..2
! Index range
DUR, WOOD, PROFIT: array(PRODS) of real ! Coefficients
x: array(PRODS) of mpvar! Array of variables
end-declarations
initializations from "chess.dat"
DUR WOOD PROFIT
end-initializations! Read data from file! chess.dat: PROFIT: [5 20]!
DUR: [3 2]!
WOOD: [1 3]! Constraint definition

sum(i in PRODS) DUR(i)*x(i) <= 160
sum(i in PRODS) WOOD(i)*x(i) <= 200
forall(i in PRODS) x(i) is_integer
maximize(sum(i in PRODS) PROFIT(i)*x(i))
writeln("Solution: ", getobjval)

c 2010 Fair Issac Corporation.

Data file chess.dat» Every data item/table has a label, its identifier» Single line comments (marked with ’!’)! Data file for ’chess4.mos’
DUR:
[3 2]
WOOD:
[1 3]
PROFIT: [5 20]

c 2010 Fair Issac Corporation.

Sparse data format» Every data entry specified with its index tuple» Can read data from one labeled data source
into several Mosel data tables at once
» data tables must have identical indicesinitializations from ’chess.dat’[DUR, WOOD, PROFIT] as ’ChessData’
end-initializations

c 2010 Fair Issac Corporation.

Sparse data format» Format of data file with several data values in
one labeled data range (use a * for a missing
data value)! chess.dat
ChessData: [(1) [3 1 5]
(2) [2 3 20]]

c 2010 Fair Issac Corporation.

Writing data out to text files» You can write out values in an analogous way
to reading them in using initializations
to» To write out the solution values of variables,or other solution values (slack, activity, dual,
reduced cost) you must first put the values
into a data tablec 2010 Fair Issac Corporation.

Writing data out to text files

declarations
x_sol: array(PRODS) of real
end-declarations
forall(i in PRODS)
x_sol(i) := getsol(x(i))
initializations to ’result.dat’
x_sol
end-initializations

c 2010 Fair Issac Corporation.

Free format text files

fopen("result.dat", F_OUTPUT+F_APPEND)
forall(i in PRODS)
writeln(i, ": ", getsol(x(i))
fclose(F_OUTPUT)

c 2010 Fair Issac Corporation.

Project work [C-2]:
Arrays and index sets

» Modify the model chess4.mos to use indicesof type string.
» Execute this new model chess4s.mos withdata set chess2.dat.
» Output the solution values to file sol.dat
using initializations to.
» Modify the models further to read thecontents of the index set from file(chess5.mos, chess5s.mos).

c 2010 Fair Issac Corporation.

Dynamic arrays» Mosel provides a user friendly and efficientmeans of modeling mathematicalprogramming problems» Objects such as dynamic arrays and variable
index sets, together with efficient loops andsums, allow large scale models to be written
easily, and execute quicklyc 2010 Fair Issac Corporation.

Dynamic arrays» Dynamic array: indexing sets not known at
declaration, or array explicitly marked
dynamic» Initialize dynamic data arrays from text files orusing ODBC
» data must use sparse format» this is so Mosel can work out the values of the indices» reading in the data array initializes both the index
values and the data values at the same timec 2010 Fair Issac Corporation.

Dynamic arrays ofdecision variables» An entry of a dynamic array is only created
when a value is assigned to it» Decision variables don’t get created, because
you don’t assign values to them
» To create decision variables in a dynamic array,use the create procedurec 2010 Fair Issac Corporation.

Dynamic arrays ofdecision variables

declarations
TIME: range! = set of contiguous integers
COST: array(TIME) of realuse: array(TIME) of mpvar
end-declarations(...)! Read in COST data etc

forall(t in TIME | exists(COST(t)))
create(use(t))

c 2010 Fair Issac Corporation.

Dynamic arrays ofdecision variables» Note: if you declare decision variables after
reading in the data, then decision variables
will be created for all combinations of theindex set elements that exist at that time
» Do not use create in this case» Define decision variables before reading indata if you want to use create to control
exactly which elements get createdc 2010 Fair Issac Corporation.

Dynamic arrays» Use dynamic arrays» to size data tables automatically when the data isread in» to initialize the index values automatically when thedata is read in» to conserve memory when storing sparse data
» to eliminate index combinations without using
conditions each timec 2010 Fair Issac Corporation.

Dynamic arrays» Don’t use dynamic arrays» when you can use an ordinary (static) array instead» when storing dense data, and you can size the datatable and initialize the indices in some other way(dynamic arrays are slower and use more memory
than a static array when storing dense data)c 2010 Fair Issac Corporation.

Data input from file:
Chess 4 completed
uses "mmxprs"
parameters
FILENAME="chess.dat"
end-parameters! Name of the data filedeclarations
PRODS = 1..2
! Index range
DUR, WOOD, PROFIT: array(PRODS) of real ! Coefficients
x: array(PRODS) of mpvar! Array of variables
end-declarations
initializations from FILENAME
DUR WOOD PROFIT
end-initializations! Read data from filesum(i in PRODS) DUR(i)*x(i) <= 160! Constraint definition
sum(i in PRODS) WOOD(i)*x(i) <= 200
forall(i in PRODS) x(i) is_integer
maximize(sum(i in PRODS) PROFIT(i)*x(i))

c 2010 Fair Issac Corporation.

Run-time parameters» Parameters» a special type of constant» default value may be overriden at run-timeparameters
DATA_DIR = ’c:/data’
DEBUG = true
NUM_RECORDS = 1000
end-parametersc 2010 Fair Issac Corporation.

Run-time parameters» The value in the model is used by default» A different value may be given at run-time» In IVE, an alternative value may be set in the Build 
Options dialogue» When running a Mosel model from an application, analternative value can be set in the parameters stringc 2010 Fair Issac Corporation.

Run-time parameters» A parameters section must come at the topof the model» after any uses or options statements» before any other statements

c 2010 Fair Issac Corporation.

Run-time parameters» Parameters are especially useful for passing
directories/paths into the model» all files referenced in the model should use a
directory parameter» otherwise, Mosel may not be able to find the filewhen the model is deployed (the default path differs
when run from an application)» use ’+’ to join stringsc 2010 Fair Issac Corporation.

Run-time parameters» Specifying directory paths» preferably use ’/’ as directory separator
parameters
DIR = ’.’
end-parameters
fopen(DIR+’/cap.dat’, F_INPUT)...
fclose(F_INPUT)...
initializations from DIR+’/cost.dat’...

c 2010 Fair Issac Corporation.

Project work [C-3]:
Run-time parameters» In models chess5.mos and chess5s.mosturn the data file name into a run-timeparameter.
» Re-run your model chess5s.mos with thelarger data set chess3.dat without changing
the filename in the model.

c 2010 Fair Issac Corporation.

Project work [C-3]:
Run-time parameters» Setting runtime parameters within IVE:
» select menu Build  Options or click on the button» check Use model parameters to activate theparameter input field and enter the new value(s)» Runtime parameters from the command line:
mosel -c "exe chess5s.mos DATAFILE=’chess3.dat’"

» or:
mosel
exe chess5s.mos DATAFILE=’chess3.dat’quit

c 2010 Fair Issac Corporation.

Using other data sources» The initializations block can work withmany different data sources and formats
thanks to the notion of I/O drivers» I/O drivers for physical data files:
mmodbc.excel, mmoci.oci, mmetc.diskdata» Other drivers available, e.g. for data exchange
in memory» Change of the data source = change of the I/Odriver, no other modifications to your modelc 2010 Fair Issac Corporation.

Data transfer using ODBC

» First, must check ODBC driver for your chosendata source (external to Xpress)» Start  Settings  Control Panel  Administrative
Tools  Data Sources (ODBC)» Check that data source is defined, and note its name(the data source name, DSN)

c 2010 Fair Issac Corporation.

Data transfer using ODBC

» Next, identify specific data source – a databaseor spreadsheet» note its location (path)» the data must be in a table in a database, or a named
range in a spreadsheet

c 2010 Fair Issac Corporation.

Data transfer using ODBC

» Now, in your model» use the mmodbc module (requires licence)» use the odbc driver in initializations blocks, or» write out the corresponding SQL commands:» set up an ODBC data connection to the specific data
source» input data using SQL statements» disconnectc 2010 Fair Issac Corporation.

Reading data via ODBC

» Excel spreadsheet (’ChessData’ = range in the
spreadsheet):initializations from ’mmodbc.odbc:chess.xls’[DUR, WOOD, PROFIT] as ’ChessData’
end-initializations» Access database (’ChessData’ = data table):
initializations from ’mmodbc.odbc:debug;chess.mdb’[DUR, WOOD, PROFIT] as ’ChessData’
end-initializations

c 2010 Fair Issac Corporation.

Data export to a databaseinitializations to ’mmodbc.odbc:debug;chess.mdb’
x_sol as ’ChessSol’
end-initializations» Before every new run, delete the data fromthe previous run in the destination range/table» Otherwise the new results will either beappended to the existing ones or, if ’PRODS’
has been defined as key field in a database,the insertion will failc 2010 Fair Issac Corporation.

Special notes for data export to
Excel» Make sure the ’Read Only’ option is disabledin the ODBC data source set-up options» Define the destination range in the
spreadsheet, with one line of column
headings, one line of dummy data, and noother data
» Excel does not support the full range of ODBC
functionality (commands like ’update’ or’delete’ will fail)⇒ preferably use direct connection (excel
driver)c 2010 Fair Issac Corporation.

Data exchange with MS Excel» Software-specific driver excel for MS Excel» use mmodbc module (requires licence)» use the excel driver (instead of odbc) ininitializations blocks» no driver setup required (works with standard Excel
installation)» simply replace "mmodbc.odbc:" by"mmodbc.excel:skiph;" in the preceding
examplesc 2010 Fair Issac Corporation.

Data exchange with Oracle» Software-specific driver oci for Oracle
databases» use mmoci module (requires licence)» setup: Oracle’s Instant Client package must be
installed on the machine running the Mosel model» in initializations blocks replace"mmodbc.odbc:" by "mmoci.oci:" in thepreceding examples» supports SQL statements (replace the prefix SQL by
OCI)

c 2010 Fair Issac Corporation.

SQL» The I/O driver odbc generates automaticallythe SQL commands required to connect to the
database/spreadsheet» For advanced uses module mmodbc also
defines most standard SQL commands directly
for the Mosel language

c 2010 Fair Issac Corporation.

Project work [C-4]:
ODBC» Check that the ODBC DSN for Excel is set up on
your computer» Re-run your model chess5.mos with the Excel
file chess.xls

c 2010 Fair Issac Corporation.

Summary» We have seen that it is possible to completely
separate the data and the model» The model specifies the logic of the problem,without any reference to its size
» The model can be applied to any data
instance, simply by providing data files

c 2010 Fair Issac Corporation.

Reference material» Refer to the Mosel User Guide for a detailed
introduction to working with Mosel.
» The book Applications of optimization with
Xpress-MP provides a large collection of
examples models from different application
areas.
» See the whitepaper Using ODBC and otherdatabase interfaces with Mosel for further
detail on data handling.

c 2010 Fair Issac Corporation.

Advanced modeling topics» MIP variable types» Modeling with binary variables

c 2010 Fair Issac Corporation.

Topics» MIP variable types» Modeling with binary variables

c 2010 Fair Issac Corporation.

MIP variable types» Binary variables» can take either the value 0 or the value 1 (do/ don’t
do variables)» model logical conditions
x(4) is_binaryc 2010 Fair Issac Corporation.

MIP variable types» Integer variables» can take only integer values» used where the underlying decision variable really
has to take on a whole number value for the optimal
solution to make sensex(7) is_integerc 2010 Fair Issac Corporation.

MIP variable types» Partial integer variables» can take integer values up to a specified limit andany value above that limit» computational advantages in problems where it isacceptable to round the LP solution to an integer if
the optimal value of a decision variable is quite large,
but unacceptable if it is smallx(1) is_partint 5

c 2010 Fair Issac Corporation.

! Integer up to 5, then continuous

MIP variable types» Semi-continuous variables» can take either the value 0, or a value between somelower limit and upper limit» help model situations where if a variable is to be
used at all, it has to be used at some minimum levelx(2) is_semcont 6

c 2010 Fair Issac Corporation.

! A ’hole’ between 0 and 6, then continuous

MIP variable types» Semi-continuous integer variables» can take either the value 0, or an integer value
between some lower limit and upper limit» help model situations where if a variable is to be
used at all, it has to be used at some minimum level,
and has to be integerx(3) is_semint 7

c 2010 Fair Issac Corporation.

! A ’hole’ between 0 and 7, then integer

MIP variable types» Special Ordered Sets of type one (SOS1)» an ordered set of variables at most one of which cantake a non-zero value» single choice among several possibilities» Special Ordered Sets of type two (SOS2)» an ordered set of variables, of which at most two canbe non-zero, and if two are non-zero these must be
consecutive in their ordering» e.g. approximation of non-linear functions with apiecewise linear function

c 2010 Fair Issac Corporation.

SOS definition» WEIGHT array determines the ordering of thevariables:
MYSOS:= sum(i in IRng) WEIGHT(i)*x(i) is_sosX

where is_sosX is either is_sos1 or is_sos2

c 2010 Fair Issac Corporation.

SOS definition» Alternative: set S of set members, linear
constraint L with ordering coefficients (=reference row entries):
makesos1(S,L); makesos2(S,L)» must be used if the coefficient WEIGHT(i) of an
intended set member is zero

» Note: the ordering coefficients must all be
distinct (or else they are not doing their job ofsupplying an order!)c 2010 Fair Issac Corporation.

Logical conditions» Projects A, B, C, D
» Binary variables a, b, c, d
» do at most 3 projects: a + b + c + d ≤ 3» must do D if A done: d ≥ a» can only do C if both A and B done:c ≤ (a + b) / 2
c ≤ a, c ≤ b

c 2010 Fair Issac Corporation.

Disjunctions» Either5 ≤ x ≤ 10or
80 ≤ x ≤ 100

c 2010 Fair Issac Corporation.

Disjunctions» Introduce a new variable:
ifupper: 0 if 5 ≤ x ≤ 10; 1 if 80 ≤ x ≤ 100
x ≤ 10 + (100 − 10) · ifupper [1]x ≥ 5 + (80 − 5) · ifupperc 2010 Fair Issac Corporation.

[2]

Disjunctions

P» Either 5 ≤ i Aixi ≤ 10
Por 80 ≤ i Aixi ≤ 100
X

Aixi ≤ 10 + 90 · ifupperiXic 2010 Fair Issac Corporation.

Aixi ≥ 5 + 75 · ifupperAbsolute values» Two variables
x1, x2with0 ≤ xi ≤ U [1. i]want
y = |x1 − x2|

c 2010 Fair Issac Corporation.

Absolute values» Introduce binary variables
d1, d2
to meand1 : 1 if x1 − x2 is the positive value
d2 : 1 if x2 − x1 is the positive valuec 2010 Fair Issac Corporation.

Absolute values» MIP formulation of y = |x1 − x2|
0 ≤ xi ≤ U[1.i]
0 ≤ y − (x1 − x2) ≤ 2 · U · d2 [2]0 ≤ y − (x2 − x1) ≤ 2 · U · d1 [3]d1 + d2 = 1

c 2010 Fair Issac Corporation.

[4]

Project work [C-5]:
Logical constraints» Take a look at the capital budgeting model incapbgt.mos: the objective is to determine themost profitable choice among 8 possible
projects, subject to limited resources(personnel and capital)» Formulate the following additional
constraints:» P1 can only be done if P2 is done
» P1 can only be done if P3 and P6 are done
» It is not possible to do both P5 and P6» Either P1 and P2 must be done or P3 and P4 (but not
both pairs).
c 2010 Fair Issac Corporation.

Solution! p1 can only be done if p2 is donex(2) >= x(1)! p1 can only be done if p3 and p6 are done(x(3) + x(6))/2 >= x(1)! It is not possible to do both p5 and p6
x(5) + x(6) <= 1
! Either p1 and p2 must be done or p3 and p4 (but not both pairs).
x(1) = x(2); x(3) = x(4)x(1) + x(2) = 2 - (x(3) + x(4))

c 2010 Fair Issac Corporation.

Programming language features» Selections» Loops» Functions and procedures» Data structures» Programming solution algorithms

c 2010 Fair Issac Corporation.

Mosel:A programming environment» Selections» Loops» Set operations» Subroutines» Data structuresc 2010 Fair Issac Corporation.

Selections» if
if A >= 20 thenx <= 7
elif A <= 10 thenx >= 35else
x = 0
end-if» casecase A of-1000..10 : x >= 35
20..1000 : x <= 7
12, 15 :
x = 1
else
x = 0
end-casec 2010 Fair Issac Corporation.

Loops» forall [do]» while [do]» repeat untilc 2010 Fair Issac Corporation.

Example: Prime numbers» Implements the ‘Sieve of Eratosthenes’.
SNumbers = {2, . . . , L}n := 2
repeatwhile (n 6 ∈SNumbers) n := n + 1
SPrime := SPrime ∪ {n}i := nwhile (i ≤ L)
SNumbers := SNumbers\{i}i := i + n
until SNumbers = {}c 2010 Fair Issac Corporation.

Example: Prime numbers

model Prime
parameters
LIMIT=100
end-parameters
declarations
SNumbers: set of integer
SPrime: set of integer
end-declarations! Search for prime numbers in 2..LIMIT! Set of numbers to be checked! Set of prime numbers

SNumbers:={2..LIMIT}
writeln("Prime numbers between 2 and ", LIMIT, ":")

c 2010 Fair Issac Corporation.

Example: Prime numbers

n:=2
repeatwhile (not(n in SNumbers)) n+=1
SPrime += {n}! n is a prime number
i:=nwhile (i<=LIMIT) do! Remove n and all its multiples
SNumbers-= {i}i+=n
end-dountil SNumbers={}
writeln(SPrime)
writeln(" (", getsize(SPrime), " prime numbers.)")end-model

c 2010 Fair Issac Corporation.

Operations on sets
» Set operators include» union: +» intersection: *» difference: -» Logical expressions using sets include» subset: Set1 <= Set2
» superset: Set1 >= Set2
» equals: Set1 = Set2
» not equals: Set1 <>Set2» element of: ’Oil5’ in Set1
» not element of: ’Oil5’ not in Set1

c 2010 Fair Issac Corporation.

Functions and procedures» Similar structure as model, including thedeclarations blocks» Terminated by end-function or
end-procedure» Function defines returned with its returnvalue» forward declaration» Overloading possible (each version with adifferent number or types of arguments)

c 2010 Fair Issac Corporation.

Example: Quick Sort algorithm

1. Choose a middle value v for partitioning(here: v = (min + max) / 2)
2. Divide the list into two parts ‘left’ (allelements x < v) and ‘right’ (all elements x > v)
3. Repeat from 1. for lists ‘left’ and ‘right’c 2010 Fair Issac Corporation.

Example: Quick Sort algorithm
model "Quick Sort"
parameters
LIM=50end-parameters! Declare procedures that are defined later
forward procedure qsort(L:array(range) of integer)
forward procedure qsort(L:array(range) of integer, s,e:integer)
declarations
T:array(1..LIM) of integer
end-declarations! Generate randomly an array of numbers
forall(i in 1..LIM) T(i):=round(.5+random*LIM)
writeln(T)time:=gettime
qsort(T)writeln(T)c 2010 Fair Issac Corporation.

! Sort the array! Print the sorted arrayExample: Quick Sort algorithm! Swap the positions of two numbers in an arrayprocedure swap(L:array(range) of integer, i,j:integer)k:=L(i)
L(i):=L(j)L(j):=k
end-procedure! Start of the sorting processprocedure qsort(L:array(r:range) of integer)
qsort(L,getfirst(r),getlast(r))
end-procedurec 2010 Fair Issac Corporation.

Example: Quick Sort algorithm! Sorting routine
procedure qsort(L:array(range) of integer, s,e:integer)v:=L((s+e) div 2)
i:=s; j:=erepeatwhile(L(i)<v) i+=1
while(L(j)>v) j-=1
if i<j thenswap(L,i,j)
i+=1; j-=1
end-ifuntil i>=j
if j<e and s<j then qsort(L,s,j); end-if
if i>s and i<e then qsort(L,i,e); end-if
end-procedure
end-model

c 2010 Fair Issac Corporation.

Data structures» array» set

c 2010 Fair Issac Corporation.

Data structures» array» set» list» record

c 2010 Fair Issac Corporation.

Data structures» array» set» list» record» ... and any combinations thereof, e.g.,
S: set of list of integer
A: array(range) of set of realc 2010 Fair Issac Corporation.

List» Collection of objects of the same type
» May contain the same element several times» Order of list elements is specified byconstruction» Handling: cuthead, splittail, reverse...
declarations
L: list of integer
M: array(range) of list of string
end-declarations
L:= [1,2,3,4,5]
M:: (2..4)[[’A’,’B’,’C’], [’D’,’E’], [’F’,’G’,’H’,’I’]]

c 2010 Fair Issac Corporation.

Record» Finite collection of objects of any type
» Each component of a record is called a ’field’
and is characterized by its name and its typedeclarations
ARC: array(ARCSET:range) of record
Source,Sink: string! Source and sink of arc
Cost: real
! Cost coefficient
end-record
end-declarations
ARC(1).Source:= "B"
ARC(3).Cost:= 1.5

c 2010 Fair Issac Corporation.

User types» Treated in the same way as the predefined
types of the Mosel language» New types are defined in declarations
blocks by specifying a type name, followed by=, and the definition of the typedeclarations
myreal = real
myarray = array(1..10) of myreal
COST: myarray
end-declarations

c 2010 Fair Issac Corporation.

User types» Typical uses
» shorthand for repetitions in declarations» naming records
declarationsarc = record
Source,Sink: string! Source and sink of arc
Cost: real
! Cost coefficient
end-record
A: arc
ARC: array(ARCSET:range) of arc
end-declarations

c 2010 Fair Issac Corporation.

Summary: Language features» Data structures: array, set, list, record» Selections: if-then-[elif-then]-[else], case» Loops: forall-[do], while-[do], repeat-until» Operators:» standard arithmetic operators» aggregate operators (sum, prod, and, or, min, max,
union, intersection)» set operators» Subroutines: functions, procedures(forward declaration, overloading)c 2010 Fair Issac Corporation.

Mosel:A solving environment» No separation between ‘modeling statements’and ‘solving statements’» Programming facilities for pre/postprocessing,algorithms» Principle of incrementality» Not solver-specific» Possibility of interaction with solver(s)c 2010 Fair Issac Corporation.

Solving: Variable fixing heuristic» Solution heuristic written with Mosel» Program split into several source files

c 2010 Fair Issac Corporation.

Solving: Variable fixing heuristic(main file)model Cocouses "mmxprs"
include "fixbv_pb.mos"include "fixbv_solve.mos"
solution:=solve
writeln("The objective value is: ", solution)
end-model

c 2010 Fair Issac Corporation.

Solving:(model)Variable fixing heuristic

declarations! Range of factories (f)RF=1..2
RT=1..4! Range of time periods (t)(...)
openm: array(RF,RT) of mpvar
end-declarations(...)
forall(f in RF,t in 1..NT-1) Closed(f,t):= openm(f,t+1) <= openm(f,t)
forall(f in RF,t in RT) openm(f,t) is_binaryc 2010 Fair Issac Corporation.

Solving: Variable fixing heuristic(algorithm)
function solve:realdeclarations
osol: array(RF,1..2) of realbas: basis
end-declarations
setparam("XPRS_PRESOLVE",0)! Set Mosel comparison tolerance
setparam("zerotol", 5.0E-4)
maximize(XPRS_LPSTOP,MaxProfit) ! Solve the root LP
savebasis(bas)! Save the basis
forall(f in RF, t in 1..2) do! Fix some binary variablesosol(f,t):= getsol(openm(f,t))
if osol(f,t) = 0 thensetub(openm(f,t), 0.0)
elif osol(f,t) = 1 thensetlb(openm(f,t), 1.0)
end-ifend-doc 2010 Fair Issac Corporation.

Solving: Variable fixing heuristic(algorithm)

maximize(XPRS_CONT,MaxProfit)! Solve modified problem
solval:=getobjval! Save solution value
forall(f in RF, t in 1..2)! Reset variable bounds
if((osol(f,t) = 0) or (osol(f,t) = 1)) thensetlb(openm(f,t), 0.0)
setub(openm(f,t), 1.0)
end-ifloadbasis(bas)! Load previously saved basis
setparam("XPRS_MIPABSCUTOFF", solval) ! Set cutoff value
maximize(MaxProfit)! Solve original problem
returned:= if(getprobstat=XPRS_OPT, getobjval, solval)
end-function

c 2010 Fair Issac Corporation.

Mosel modules and packages

c 2010 Fair Issac Corporation.

Mosel:A modular environment» Open architecture:» possibility to define language extensions via
packages or modules without any need to modify thecore of the Mosel language

c 2010 Fair Issac Corporation.

Mosel:A modular environment» Package = library written in the Mosel
language» making parts of Mosel models re-usable» deployment of Mosel code whilst protecting yourintellectual property» similar structure as models (keyword model isreplaced by package), compiled in the same way» included with the uses statement» definition of new types, subroutines, symbols» see examples in the Mosel User Guidec 2010 Fair Issac Corporation.

Mosel:A modular environment» Module = dynamic library written in C
» modules of the Mosel distribution:» solver interfaces:
Xpress-Optimizer (LP, MIP, QP), SLP, SP, CP» database access: ODBC, OCI» system commands; model handling; graphics» write your own modules for» connecting to external software» time-critical tasks» defining new types, subroutines, operators, I/O
drivers, control parameters, symbols

c 2010 Fair Issac Corporation.

Some highlights
of module features» Interaction with external programs during
their execution (callback functions)» Access to other solvers and solving paradigms(NLP, CP)» Implementation of graphical applications(mmive, XAD)

c 2010 Fair Issac Corporation.

Module mmxprs:
Using callback functions

uses "mmxprs"
declarations
x: array(1..10) of mpvar
end-declarations
public procedure printsol
writeln("Solution: ", getsol(Objective)))
forall(i in 1..10) write("x(", i, ")=", getsol(x(i)), ""writeln
end-procedure
setcallback(XPRS_CB_INTSOL, "printsol")c 2010 Fair Issac Corporation.

Module mmxslp:
Solving an NLP by SLP» What is the greatest area of a polygon of N
sides and a diameter of 1?

c 2010 Fair Issac Corporation.

Module mmxslp:
Solving an NLP by SLP

model "Polygon"
uses "mmxslp"
declarations
N=5
area: gexp
rho, theta: array(1..N) of mpvar
objdef: mpvar
D: array(1..N,1..N) of genctr
end-declarations
forall(i in 1..N-1) do! Initialization of SLP variables
rho(i) >= 0.1; rho(i) <= 1
SLPDATA("IV", rho(i), 4*i*(N + 1 - i)/((N+1)^2))
SLPDATA("IV", theta(i), M_PI*i/N)
end-doc 2010 Fair Issac Corporation.

Module mmxslp:
Solving an NLP by SLP

forall(i in 1..N-2, j in i+1..N-1) ! Third side of all triangles
D(i,j):= rho(i)^2 + rho(j)^2 rho(i)*rho(j)*2*cos(theta(j)-theta(i)) <= 1
! Vertices in increasing orderforall(i in 2..N-1) theta(i) >= theta(i-1) +.01
theta(N-1) <= M_PI

! Boundary conditions

area:=! Objective: sum of areas(sum(i in 2..N-1) (rho(i)*rho(i-1)*sin(theta(i)-theta(i-1))))*0.5
objdef = area; objdef is_free
SLPloadprob(objdef)
SLPmaximize
writeln("Area = ", getobjval)
end-model

c 2010 Fair Issac Corporation.

Module kalis:
Constraint Programming» Example: jobshop scheduling» schedule the production of a set of jobs on a set ofmachines. Every job is produced by a sequence oftasks, each of these tasks is processed on a different
machine. A machine processes at most one job at atime.

» Implementation with high-level modelingobjects (tasks and resources)c 2010 Fair Issac Corporation.

Module kalis:
Constraint Programming

model "Job Shop"
uses "kalis"declarations
JOBS = 1..NJ
MACH = 1..NM
RES: array(JOBS,MACH) of integer
DUR: array(JOBS,MACH) of integer
res: array(MACH) of cpresource
task: array(JOBS,MACH) of cptask
end-declarations...

! Set of jobs
! Set of resources! Resource use of tasks! Durations of tasks! Resources! Tasks! Initialize the data

HORIZON:= sum(j in JOBS, m in MACH) DUR(j,m)

c 2010 Fair Issac Corporation.

Module kalis:
Constraint Programming
forall(j in JOBS) getend(task(j,NM)) <= HORIZON! Setting up the resources (capacity 1)
forall(m in MACH)
set_resource_attributes(res(m), KALIS_UNARY_RESOURCE, 1)! Setting up the tasks (durations, resource used)
forall(j in JOBS, m in MACH)
set_task_attributes(task(j,m), DUR(j,m), res(RES(j,m)))! Precedence constraints between the tasks of every job
forall (j in JOBS, m in 1..NM-1)
setsuccessors(task(j,m), {task(j,m+1)})! Solve the problem & print solution
if cp_schedule(getmakespan)<>0 thenwriteln("Total completion time: ", getsol(getmakespan))
end-ifend-model

c 2010 Fair Issac Corporation.

Module mmive:
Drawing user graphs
model "Schedule"
uses "mmive", "mmsystem"
declarations
MACHINES=6; JOBS=6
graphs, colors: array(1..MACHINES) of integer
labels: array(1..JOBS) of integer
curmachine, curjobs, n1, n2, n3: integer
end-declarations
colors:: [IVE_WHITE, IVE_YELLOW, IVE_CYAN, IVE_RED, IVE_GREEN,
IVE_MAGENTA]
fopen("schedule.dat", F_INPUT)
forall (i in 1..MACHINES) dographs(i):= IVEaddplot("Machine "+i, IVE_BLUE)labels(i):= IVEaddplot("Jobs for machine "+i, Color(i))
end-doc 2010 Fair Issac Corporation.

Module mmive:
Drawing user graphs

forall (i in 1..MACHINES) do! Read machine no. & no. of jobs
readln(n1, n2)writeln("Machine ", n1, " Jobs:", n2)curmachine:= n; curjobs:= n2forall(j in 1..curjobs) doreadln(n1, n2, n3)! Read job no., start & finish times
writeln("On machine ", curmachine, " job ", n1," starts at ", n2, " and finishes at ", n3)
IVEdrawarrow(graphs(curmachine), n2, curmachine, n3, curmachine)
IVEdrawlabel(labels(n1), (n2+n3)/2, curmachine,"Job "+n1+"\r starts: "+n2+"\r ends: "+n3)
end-doend-doIVEzoom(0, 0, 30, 7)
fclose(F_INPUT)
end-model

c 2010 Fair Issac Corporation.

Module mmive:
Drawing user graphsc 2010 Fair Issac Corporation.

c 2010 Fair Issac Corporation.

And also» Working with several models in parallel,possibly in a heterogeneous distributed
architecture (module mmjobs)» see whitepaper Multiple models and parallel solving
with Mosel» Combining different solvers» see whitepaper Hybrid MIP/CP solving with
Xpress-Optimizer and Xpress-Kalis

c 2010 Fair Issac Corporation.

Reference material» The modules of the Mosel distribution are
documented in the Mosel Language Reference
Manual (with separate manuals for solver
modules mmxslp and kalis)» The Mosel Native Interface User Guide
explains how to write your own modules.

c 2010 Fair Issac Corporation.

The material in this presentation is the property of Fair Issac Corporation, is provided for the recipient only, andshall not be used, reproduced, or disclosed without Fair Isaac Corporation’s express consent.
c 2010 Fair Issac Corporation.

Embedding Mosel models

c 2010 Fair Issac Corporation.

Embedding models in applications

c 2010 Fair Issac Corporation.

What is the Mosel API?

» The Mosel language allows you to formulate
optimization problems, and develop
optimization methods (i.e., use the Optimizer
to solve them), as a Mosel model» The Mosel API (also Mosel libraries) allows you
to embed Mosel models in an application

c 2010 Fair Issac Corporation.

Programming environments» The Mosel API is available for C/C++, Java, .NET
and VB» We use Java in the slides, but the functionality
applies to all languages, and similar
applications can be developed in otherlanguagesc 2010 Fair Issac Corporation.

Mosel libraries» Model Compiler Library» compiles to a virtual machine» binary format architecture independent» Runtime Library» load and run binary (models)» access to Mosel internal database (data, solution
values, ...)

c 2010 Fair Issac Corporation.

Generating a
deployment template» With Xpress-IVE: select Deploy  Deploy or
click the deploy buttonc 2010 Fair Issac Corporation.

Generating a
deployment template» Choose the application language:c 2010 Fair Issac Corporation.

Generating a
deployment template» Clicking on the Next button will open a new
window with the resulting code
» Use the Save as button to set the name andlocation of the new file.

c 2010 Fair Issac Corporation.

Mosel library functions» General:
XPRM(), XPRM.getVersion, XPRM.license, ...

» Model handling:
XPRM.compile, XPRM.loadModel, XPRMModel.run, XPRMmodel.getResult,
XPRMModel.getExecStatus, XPRMModel.reset, ...

» Solution information:
XPRMModel.getObjectiveValue, XPRMModel.getProblemStatus,
XPRMMPVar.getSolution, XPRMLinCtr.getActivity, ...

c 2010 Fair Issac Corporation.

Mosel library functions» Accessing model objects:
XPRMModel.findIdentifier» Arrays:
XPRMArray.getDimension, XPRMArray.getIndexSets,
XPRMArray.getFirstIndex, XPRMArray.nextIndex, XPRMArray.get, ...

» Sets:XPRMSet.getSize, XPRMSet.getFirstIndex, XPRMSet.isFixed, ...

» Handling of modules:
XPRM.findModule, XPRM.setModulesPath, XPRMModule.parameters, ...

c 2010 Fair Issac Corporation.

Project work [C-6]:
Model deployment» Use IVE to generate a Java program thatcompiles and runs model chess5.mos» Modify the program so that the model
execution uses the data file chess4.dat.
» Check the problem status and output theobjective value.

c 2010 Fair Issac Corporation.

Solution

import com.dashoptimization.*;public class chessc{
public static void main(String[] args) throws Exception{
int result;
XPRMModel model;
XPRM xprm;// Initialize Mosel
xprm = new XPRM();// Load compiled model (.BIM file)model = xprm.loadModel("chess5.bim");c 2010 Fair Issac Corporation.

Solution// Run model
model.execParams = "DATAFILE=chess4.dat";
model.run();System.out.println("Model execution returned: " +model.getResult());// Check problem status and retrieve the optimal solution value
if (model.getProblemStatus()==XPRMModel.PB_OPTIMAL)
System.out.println("Objective value: " +model.getObjectiveValue());
model.reset();}}c 2010 Fair Issac Corporation.

Extending the example» Retrieving detailed solution information andmodel data
XPRMModel model;
XPRMSet prods;
XPRMArray profit, ax;
XPRMMPVar x;
int[] idx = new int[1];double val;// Retrieve solution values and problem data
prods = (XPRMSet)model.findIdentifier("PRODS");
profit = (XPRMArray)model.findIdentifier("PROFIT");ax = (XPRMArray)model.findIdentifier("x");c 2010 Fair Issac Corporation.

Extending the example// Get the first entry of array ’ax’// (we know that the array is dense and has a single dimension)idx = ax.getFirstIndex();do{x = ax.get(idx).asMPVar();// Get a variable from ’ax’
val = profit.getAsReal(idx);// Get the corresponding value
System.out.println(prods.get(idx[0]) + ": " + x.getSolution() +"\t (profit: " + val + ")");// Print the solution value} while(ax.nextIndex(idx));// Get the next index

c 2010 Fair Issac Corporation.

Extending the example» Data exchange in memory with hostapplication
public class chessio{
static int NP = 4;// Input data
static final double[] dur= {3, 2, 2, 3};
static final double[] wood
= {1, 2, 3, 6};
static final double[] profit = {5,12,20,40};// Array for solution values
static double[] solution = new double[NP];public static void main(String[] args) throws Exception{
int result;
XPRMModel model;
XPRM xprm;

c 2010 Fair Issac Corporation.

Extending the example
xprm = new XPRM();// Initialize Mosel
xprm.compile("chess5ioj.mos");// Compile + load model
model = xprm.loadModel("chess5ioj.bim");// Associate Java objects with
xprm.bind("DUR", dur);
xprm.bind("WOOD", wood);// names in Mosel
xprm.bind("PROFIT", profit);
xprm.bind("xsol", solution);model.execParams = "NP="+NP;// Set runtime parametersmodel.run();// Run the model
if (model.getProblemStatus()==model.PB_OPTIMAL){// Check problem status and display the solution
System.out.println("Objective: " + model.getObjectiveValue());
for(int i=0;i<NP;i++)System.out.println("x(" + (i+1) + "): " + solution[i] +"\t (profit: " + profit[i] + ")");}
model.reset();}}c 2010 Fair Issac Corporation.

Summary» Mosel libraries allow you to embed model
programs directly in your application» Access the solution directly in yourapplication, as alternative to using ODBC
» Enjoy benefits of structured modelinglanguage and rapid deployment whenbuilding applications

c 2010 Fair Issac Corporation.

Summary» May choose to work with compiled models
rather than model source files – provides
protection against the user viewing / changing
the model» Compiled models are platform independentc 2010 Fair Issac Corporation.

Reference material» You will find it helpful to refer to the Mosel
Libraries Reference Manual» The part ’Working with the Mosel libraries’ of
the Mosel User Guide documents examples fordifferent programming language interfacesc 2010 Fair Issac Corporation.

The material in this presentation is the property of Fair Issac Corporation, is provided for the recipient only, andshall not be used, reproduced, or disclosed without Fair Isaac Corporation’s express consent.
c 2010 Fair Issac Corporation.

Summary and further information

c 2010 Fair Issac Corporation.

Summaryc 2010 Fair Issac Corporation.

Summary» Have seen:» FICO Xpress product suitec 2010 Fair Issac Corporation.

Summary» Have seen:» FICO Xpress product suite» solvers

c 2010 Fair Issac Corporation.

Summary» Have seen:» FICO Xpress product suite» solvers» modeling interfacesc 2010 Fair Issac Corporation.

Summary» Have seen:» FICO Xpress product suite» solvers» modeling interfaces» development environment

c 2010 Fair Issac Corporation.

Summary» Have seen:» Modeling with Mosel» formulating Linear and Mixed Integer Programming(LP and MIP) problems

c 2010 Fair Issac Corporation.

Summary» Have seen:» Modeling with Mosel» formulating Linear and Mixed Integer Programming(LP and MIP) problems» accessing data sources

c 2010 Fair Issac Corporation.

Summary» Have seen:» Modeling with Mosel» formulating Linear and Mixed Integer Programming(LP and MIP) problems» accessing data sources» programming language featuresc 2010 Fair Issac Corporation.

Summary» Have seen:» Modeling with Mosel» formulating Linear and Mixed Integer Programming(LP and MIP) problems» accessing data sources» programming language features» language extensions (modules and packages)c 2010 Fair Issac Corporation.

Summary» Have seen:» Modeling with Mosel» formulating Linear and Mixed Integer Programming(LP and MIP) problems» accessing data sources» programming language features» language extensions (modules and packages)» Embedding models in applications for deploymentc 2010 Fair Issac Corporation.

Further information» Xpress website:
http://www.fico.com/xpress» Examples database:
http://examples.xpress.fico.com» Whitepapers, documentation:
http://optimization.fico.com

c 2010 Fair Issac Corporation.

The material in this presentation is the property of Fair Issac Corporation, is provided for the recipient only, andshall not be used, reproduced, or disclosed without Fair Isaac Corporation’s express consent.
c 2010 Fair Issac Corporation.

www.fico.com/xpress

The material in this presentation is the property of Fair Issac Corporation, is provided for the recipient only, andshall not be used, reproduced, or disclosed without Fair Isaac Corporation’s express consent.
c 2010 Fair Issac Corporation.