Quick reference

FICO Xpress Optimization
R

Mosel Language
Quick reference

Last update 29 August, 2017www.fico.com

Make every decision countTM

This material is the confidential, proprietary, and unpublished property of Fair Isaac Corporation. Receipt or possession of thismaterial does not convey rights to divulge, reproduce, use, or allow others to use it without the specific written authorizationof Fair Isaac Corporation and use must conform strictly to the license agreement.
The information in this document is subject to change without notice. If you find any problems in this documentation, please
report them to us in writing. Neither Fair Isaac Corporation nor its affiliates warrant that this documentation is error-free, nor
are there any other warranties with respect to the documentation except as may be provided in the license agreement.
©2009–2017 Fair Isaac Corporation. All rights reserved. Permission to use this software and its documentation is governedby the software license agreement between the licensee and Fair Isaac Corporation (or its affiliate). Portions of the program
may contain copyright of various authors and may be licensed under certain third-party licenses identified in the software,
documentation, or both.
In no event shall Fair Isaac Corporation or its affiliates be liable to any person for direct, indirect, special, incidental, or
consequential damages, including lost profits, arising out of the use of this software and its documentation, even if Fair Isaac
Corporation or its affiliates have been advised of the possibility of such damage. The rights and allocation of risk between
the licensee and Fair Isaac Corporation (or its affiliates) are governed by the respective identified licenses in the software,
documentation, or both.
Fair Isaac Corporation and its affiliates specifically disclaim any warranties, including, but not limited to, the implied warranties
of merchantability and fitness for a particular purpose. The software and accompanying documentation, if any, provided
hereunder is provided solely to users licensed under the Fair Isaac Software License Agreement. Fair Isaac Corporation and its
affiliates have no obligation to provide maintenance, support, updates, enhancements, or modifications except as required tolicensed users under the Fair Isaac Software License Agreement.
FICO and Fair Isaac are trademarks or registered trademarks of Fair Isaac Corporation in the United States and may be
trademarks or registered trademarks of Fair Isaac Corporation in other countries. Other product and company names herein
may be trademarks of their respective owners.
FICO R Xpress Mosel
Last Revised: 29 August, 2017

How to Contact the Xpress Team
Information, Sales and Licensing
USA, CANADA AND ALL AMERICASEmail: XpressSalesUS@fico.com
WORLDWIDE
Email: XpressSalesUK@fico.com
Tel: +44 207 940 8718
Fax: +44 870 420 3601
Xpress Optimization, FICO
FICO HouseInternational Square
Starley Way
Birmingham B37 7GN
UK

Product Support
Email: Support@fico.com(Please include ’Xpress’ in the subject line)
Telephone:
NORTH AMERICA
Tel (toll free): +1 (877) 4FI-SUPP
Fax: +1 (402) 496-2224
EUROPE, MIDDLE EAST, AFRICA
Tel: +44 (0) 870-420-3777
UK (toll free): 0800-0152-153
South Africa (toll free): 0800-996-153
Fax: +44 (0) 870-420-3778
ASIA-PACIFIC, LATIN AMERICA, CARIBBEAN
Tel: +1 (415) 446-6185
Brazil (toll free): 0800-891-6146

For the latest news and Xpress software and documentation updates, please visit the Xpress website at
http://www.fico.com/xpress or subscribe to our mailing list.

Mosel Quick Reference

FICO Xpress Optimization
R

Mosel Language
Quick reference
29 August, 2017

Contents
1

2

3
4

5
6

Contents

Mathematical Programming basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.1
Decision variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3
Objective function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.4
Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.5
Viewing the matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.6
Viewing the solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data handling basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1
Data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2
Sums and loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3
Index sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.4
Reading data in from text files . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5
Writing data out to text files . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6User defined data formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.7
Using other data sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model building style recommendations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mosel Language overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.1
Structure of a Mosel model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.2
Data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.3
Selection statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.4
Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.5
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.6
Built in functions and procedures . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.7
Constraint handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.8
Problem handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.9
Reserved words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4.10 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using the Mosel Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5.1
Debugger commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Xpress Workbench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2
2
3
3
3
3
3
4
4
5
6
6
7
7
8
8
9
9
10
12
12
13
14
16
16
17
17
18
18
20

Fair Isaac Corporation Confidential and Proprietary Information

1

Mosel Quick Reference

1

Mathematical Programming basics
model "Chess 1"
uses "mmxprs"! Use Xpress Optimizer for solving

declarations
xs, xl: mpvar
end-declarations! Decision variables

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

xs is_integer; xl is_integer! Integrality constraints

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

writeln("Solution: ", getobjval) ! Print objective function value
writeln("small: ", getsol(xs))
writeln("large: ", getsol(xl))! Print solution for xs! and xl

write("Time: ", getact(Time))
writeln(" ", getslack(Time))! Constraint activity! and slack

end-model

1.1

Decision variables
declarations
x, b, d: mpvar
ifmake: array(1..10, 1..20) of mpvar
y, z: array(1..10) of mpvar
end-declarations

mpvar means mathematical programming variable or decision variable, sometimes also just called
variable. Decision variables are unknowns: they have no value until the model is run, and the
optimizer finds values for the decision variables.
Variables can take values between 0 and infinity by default, other bounds may be specified:x <= 10y(1) = 25.5y(2) is_freez(2,3) >= -50z(2,3) <= 50

Integer programming types are defined as unary constraints on previously declared decisionvariablesb is_binary
forall(p in PRODS,l in LINES)
ifmake(p,l) is_binaryd is_integerd <= 25x is_partint 10
y(3) is_semcont 5

Mathematical Programming basics! Single binary variable! An array of binaries! An integer variable! Upper bound on the variable! Partial integer (integers up to 10, continuous beyond)! Semi-continuous (0 or greater or equal 5)

Fair Isaac Corporation Confidential and Proprietary Information

2

Mosel Quick Reference

1.2

Constraints
Constraint are declared just like decision variables, in LP/MIP problems they have type linctr –linear constraint.
declarations
MaxCap: linctr
Inven: array(1..10) of linctr
end-declarations

The “value” of a constraint entity is a linear expression of decision variables, a constraint type ( ≤, ≥ , =), and a constant term. It is set using an assignment statement:
MaxCap := 10*x + 20*y + 30*z <= 100
Ctr(3) := 4*x(1) - 3*x(2) >= 10
Inven(2) := stock(2) = stock(1) + buy(2) - sell(2)1.3

Objective function
An objective function is just a constraint with no constraint type.
declarations
MinCost: linctr
end-declarations
MinCost := 10*x(1) + 20*x(2) + 30*x(3) + 40*x(4)1.4Optimization
minimize(MinCost)
maximize(MaxProfit)

1.5

Viewing the matrix
After defining the problem the matrix can be output to a file, to examine off line.

1.6

Specify LP format for constraint oriented file:exportprob(EP_MIN, "explout", MinCost)

Useful Optimizer control settings:

setparam(’XPRS_VERBOSE’, true)
setparam(’XPRS_LOADNAMES’, true)

Viewing the solution
Always check the solution status of the problem before accessing any solution values.
if (getprobstat=XPRS_OPT) thenwriteln(’optimal!’)else
writeln(’not optimal!’)exit(1)
end-ifAlternatively, testing all problem states:case getprobstat ofMathematical Programming basics

Fair Isaac Corporation Confidential and Proprietary Information

3

Mosel Quick Reference

XPRS_OPT: writeln(’optimal’)
XPRS_INF: writeln(’infeasible’)
XPRS_UNB: writeln(’unbounded’)
XPRS_UNF: writeln(’unfinished’)
else
writeln(’unexpected problem status!’)end-case

Accessing the solution values within the model:
writeln(’Maximum revenue: $’, getobjval)
writeln(’x(1) = ’, getsol(x(1)), ’ x(2) = ’, x(2).sol)

Solution values of constraints: activity value + slack value = RHS
MaxCap := 10*x + 20*y <= 30

Activity value:

getsol(10*x + 20*y)getact(MaxCap)

Slack value:

getsol(30 - (10*x + 20*y))
getslack(MaxCap)

Xpress Workbench: assuming that the model runs successfully, the logging pane at the bottom of
the workspace reports that the run is complete. If a model has been run through the debugger,
you can browse solution values of decision variables and constraints in the Debugger tab on theright side of the workspace.

2

Data handling basics
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! Constraint definition

maximize(sum(i in R) PROFIT(i)*x(i))
writeln("Solution: ", getobjval)
end-model

2.1

Data types
Constant data

Data handling basics

declarationsNWEEKS = 20
NDAYS = 7*NWEEKSCONV_RATE = 1.425
DATA_DIR = ’c:\data’
end-declarations

Fair Isaac Corporation Confidential and Proprietary Information

4

Mosel Quick Reference

Variable data

2.2

Declaration

declarations
NPROD: integer
SCOST: real
MAXREFVEG: real
DIR: string
IF_DEBUG: boolean
HARD: array(1..5) of real
COST: array(1..3,1..4) of real
end-declarations

Initialization

NPROD := 20
SCOST := 5
MAXREFVEG := 200.0
DIR := ’c:\data’
IF_DEBUG := true
HARD :: [8.8, 6.1, 2.0, 4.2, 5.0]
COST :: [11, 12, 13, 14,
21, 22, 23, 24,
31, 32, 33, 34]

Sums and loops
Summations

Sum up an array of variables in a constraint:
MaxCap := sum(p in 1..10) buy(p) <= 100
MaxCap := sum(p in 1..10) (buy(p) + sum(r in 1..5) make(p,r)) <= 100
MaxCap := sum(p in 1..NP, t in 1..NT)
CAP(p)*buy(p,t) <= MAXCAP
MaxCap := sum(p in 1..NP) (2*CAP(p)*buy(p)/10 +SCAP(p)*sell(p)) <= MAXCAP

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)Use do/end-do to group several statements into one loop
forall(t in 1..NT) do
MaxRef(t) := sum(i in 1..NI) use(i,t) <= MAXREF(t)Inven(t) := store(t) = store(t-1) + buy(t) - use(t)end-doCan 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-doSimilarly for specification of bounds (a bound is just a simple unnamed
constraint):
forall(i in 1..NI) do
forall(t in 1..NT) store(i,t) <= MAXSTORE(t)store(i,0) = STORE0
end-doData handling basics

Fair Isaac Corporation Confidential and Proprietary Information

5

Mosel Quick Reference

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

Index sets
Explicit statement:

declarations
MaxCap: array(1..10) of linctr
end-declarations
forall(d in 1..10)
MaxCap(d) :=sum(p in 1..10, m in 1..10)
TECH(p,m,d)*x(p,m,d) <= MAXTECH(d)Defining named sets:

declarations
PRODUCTS = 1..5
MATERIALS = {12,487,163}
DEPOTS = {"Boston","New York","Atlanta"}
MaxCap: array(DEPOTS) of linctr
end-declarations
forall(d in DEPOTS)
MaxCap(d) :=sum(p in PRODUCTS, m in MATERIALS)
TECH(p,m,d)*x(p,m,d) <= MAXTECH(d)Using named sets

2.4



improves the readability of a modelmakes it easier to apply the model to different sized data sets

makes the model easier to maintain

Reading data in from text files
Read data into COST from cost.dat

initializations from ’cost.dat’COST
end-initializations

Data file cost.dat (dense data format)

COST : [3.9 0 4.8
0 7.5 5.5]

Data file cost2.dat (sparse data format)

COST: [("Oil1" 1) 3.9("Oil2" 2) 7.5

Mosel data format:

file may include single line comments, marked with ’!’format: label, colon, data value(s)

for an array, use a single list enclosed in [ ]list may be comma or space separated

dense format: the values fill the data table starting at the first
position and varying the last index most rapidlysparse format: each data item is preceded by the corresponding
index tuple (in brackets)

Specifying the absolute path

Data handling basics("Oil1" 3) 4.8("Oil2" 3) 5.5]

initializations from ’c:/data/cost.dat’COST
end-initializations

Fair Isaac Corporation Confidential and Proprietary Information

6

Mosel Quick Reference

Path relative to current working directory

initializations from ’../cost.dat’COST
end-initializations

Read several data tables from a single fileinitializations from ’cost.dat’
SCOST
PCOST
end-initializations

Different data label and model object names

initializations from ’cost.dat’
COST as ’COST_DETAILS’
end-initializations

Read several data arrays with identical index sets from a single table
initializations from ’chess.dat’[DUR,WOOD,PROFIT] as ’ChessData’
end-initializations

2.5

Writing data out to text files
You can write out values in an analogous way to reading them ininitializations to ’cost.dat’COST
end-initializations

To write out the solution values of variables, or other solution values (slack, activity, dual, reducedcost) you must first put the values into a data tabledeclarations
make_sol: array(ITEMS,TIME) of real
obj_sol: real
end-declarations
forall(i in ITEMS, t in TIME)
make_sol(i,t) := getsol(make(i,t))
obj_sol := getobjval
initializations to ’make.dat’
make_sol
obj_sol
end-initializations

Alternatively, you can use evaluation of directly in the initializations block
initializations to ’make.dat’evaluation ofarray(i in ITEMS, t in TIME) getsol(make(i,t)) as ’make_sol’
evaluation of getobjval as ’obj_sol’
end-initializations

2.6

User defined data formats
Mosel also provides functions which allow you to read data in from and write data out to text
files using any format (see list in Section 4.6).
Reading in free format data

Data handling basics

declarations
ii, jj: integer! Don’t use normal i,jFair Isaac Corporation Confidential and Proprietary Information

7

Mosel Quick Reference

end-declarations
fopen(’cost.dat’, F_INPUT)
while(not iseof)
readln(ii, ’,’, jj, ’,’, COST(ii,jj))
fclose(F_INPUT)

Writing out data in user format

2.7

fopen(’xsol.dat’, F_OUTPUT)
forall(s in SUP, d in DEP)
writeln(s, ’,’, d, ’,’, getsol(x(s,d)))fclose(F_OUTPUT)

Using other data sources
The initializations block can work with many different data sources and formats thanks to thenotion of I/O drivers.
I/O drivers for physical data files:

mmodbc.odbc for databases with ODBC connector



mmsheet.excel for MS Excel spreadsheets

mmsheet.xls and mmsheet.xlsx for genericspreadsheet access, including on non-Windows
platforms

mmsheet.csv for CSV format files



mmoci.oci for Oracle databases



mmetc.diskdata for mp-model style data files

Other drivers are available, e.g. for data exchange in memory between models or between amodel and the host application.
Change of the data source = change of the I/O driver, no other modifications to your model
initializations from "mmsheet.xls:mydat.xls"
COST as ’CostData’
end-initializations
initializations to "mmodbc.odbc:mydat.mdb"
SOL as ’SolTable’
end-initializations

3

Model building style recommendations
Separation of problem logic and data
– Typically, the model logic stays constant once developed, with the data changing eachrun
– Fix the model and obtain data from their source to avoid editing the model which cancreate errors, expose intellectual property, and is impractical for industrial size dataYou should aim to build a model with sections in this order– constant data: declare, initialize– all non-constant objects: declare– variable data: initialize / input / calculate

Model building style recommendations

Fair Isaac Corporation Confidential and Proprietary Information

8

Mosel Quick Reference– decision variables: create, specify bounds– constraints: declare, specify– objective: declare, specify, optimizeUse a naming convention that distinguishes between different model object types, forexample– known values (data) using upper case
– unknown values (variables) using lower case– constraints using mixed caseVariables are actions that your model will prescribe– Use verbs for the names of variables. This emphasizes that variables represent ‘what todo’ decisions



Try to include ‘min’ or ‘max’ in the name of your objective function; an objective function
called ‘OBJ’ is not very helpful when taken out of context!

Indices are the objects that the actions are performed on– Use nouns for the names of indices

Declare all objects in your model (optional unless using compiler option noimplicit)– Allows the compiler to detect syntax errors more easily– Mosel’s guessed declaration doesn’t always work
– A form of rigour and documentation– An opportunity for a descriptive commentComments are essential for a well written model– Always use a comment to explain what each parameter, data table, variable, andconstraint is for when you declare it– Add extra comments to explain any complex calculation etc– Comments in Mosel:
declarations
make: array(1..NP, 1..NT) of mpvar
sell: array(1..NP, 1..NT) of mpvar
end-declarations! Amount of p produced in time t! Amount of p sold in time t(! And here is a multi-line
comment !)forall(t in 1..NT) ...

4

Mosel Language overview

4.1

Structure of a Mosel model
A Mosel model (text file with extension .mos) has the form

Mosel Language overview

Fair Isaac Corporation Confidential and Proprietary Information

9

Mosel Quick Reference

model model_nameCompiler directives
Parameters
Body
end-model

Compiler directivesOptions are specified as a compiler directive, at the beginning of the
model



Options include explterm, which means that each statement mustend with a semi-colon, and noimplicit, which forces all objects to be
declared
options explterm
options noimplicit



uses statements are also compiler directives
uses "mmxprs", "mmodbc"

Can define a version number for your modelversion 1.0.0

Run-time parameters

Model body

Scalars (of type integer, real, boolean, or string) with a specified
default valueTheir value may be reset when executing the modelUse initializations from for inputting structured data (arrays,
sets,...)

At most one parameters block per modelModel statements other than compiler directives and parameters,
including any number of–––

Implicit declaration

Mosel statements

4.2

declarations
initializations from / initializations tofunctions and procedures

Mosel does not require all objects to be declared

Simple objects can be used without declaring them, if their type isobvious

Use the noimplicit option to force all objects to be declared before
using them (see item Compiler directives above)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. + - , * )Data structuresarray, set, list, record and any combinations thereof, e.g.,

Mosel Language overview

Fair Isaac Corporation Confidential and Proprietary Information

10

Mosel Quick Reference

S: set of list of integer
A: array(range) of set of real

ArraysArray: collection of labeled objects of a given type where the label of an arrayentry is defined by its index tuple
declarations
A: array(1..5) of real
B: array(range, set of string) of integer
x: array(1..10) of mpvar
C: array(1..5) of real
end-declarations
A:: [4.5, 2.3, 7, 1.5, 10]
A(2):= 1.2
B:: (2..4,["ABC", "DE", "KLM"])[15,100,90,60,40,15,10,1,30]
C:= array(i in 1..5) x(i).sol

Sets

Set: collection of objects of the same type without establishing an order among
them (as opposed to arrays and lists)
Set elements are unique: if the same element is added twice the set still only
contains it once.
declarations
S: set of string
R: range
end-declarations
S:= {"A", "B", "C", "D"}R:= 1..10

Lists

List: collection of objects of the same typeA list may contain the same element several times. The order of the list
elements is specified by construction.
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’]]

Records

Record: finite collection of objects of any type
Each component of a record is called a field and is characterized by its name andits type.
declarations
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

User types

Mosel Language overview

User types are treated in the same way as the predefined types of the Mosel
language. New types are defined in declarations blocks by specifying a typename, followed by =, and the definition of the type.

Fair Isaac Corporation Confidential and Proprietary Information

11

Mosel Quick Reference

declarations
myreal = real
myarray = array(1..10) of myreal
COST: myarray
end-declarations

4.3

4.4

Selection statements
if ... end-if

if c=1 thenwriteln(’c equals 1’)
end-ifif ... else ... end-if

if c=1 thenwriteln(’c equals 1’)
else
writeln(’c does not equal 1’)
end-ifif ... elif ... else ... end-if

if c=1 thenwriteln(’c equals 1’)
elif c>1 thenwriteln(’c is bigger than 1’)
else
writeln(’c is smaller than 1’)
end-ifcase ... end-case

case c of
1,2 : writeln(’c equals 1 or 2’)
3: writeln(’c equals 3’)
4..6: dowriteln(’c is in 4..6’)
writeln(’c is not 1, 2 or 3’)
end-doelse
writeln(’c is not in 1..6’)
end-case

Loops
forallforall(f in FAC, t in TIME)
make(f,t) <= MAXCAP(f,t)
forall(t in TIME) douse(t) <= MAXUSE(t)buy(t) <= MAXBUY(t)end-dowithequivalent to a forall loop stopped after the first iteration
with f=’F1’, t=1 domake(f,t) <= MAXCAP(f,t)
end-dowhile

i := 1
while (i <= 10) do
write(’ ’, i)i += 1
end-dorepeat ... until

i := 1
repeatwrite(’ ’, i)i += 1
until (i > 10)

break, next
Mosel Language overview

break jumps out of the current loop
Fair Isaac Corporation Confidential and Proprietary Information

12

Mosel Quick Reference

break n jumps out of n nested loops (where n is a positive
integer)next jumps to the beginning of the next iteration of the current
loop

use break ’looplabel’ and next ’looplabel’ with labeledloops:’L1’: repeat’L2’: while (condition1) do
if condition2 thenbreak ’L1’
end-ifend-dountil condition3

counter

Use the construct as counter to specify a counter variable in abounded loop (i.e., forall or aggregate operators such as sum). At
each iteration, the counter is incremented
cnt:=0.0
writeln("Average of odd numbers in 1..10: ",(sum(cnt as counter, i in 1..10 | isodd(i)) i) / cnt)

4.5

Operators
Assignment operators

i := 10i += 20i -= 5! Same as i := i + 20
! Same as i := i - 5

Assignment operators with linear constraints
C := 5*x + 2*y <= 20
D := C + 7*ythen D is
D := 5*x + 9*y - 20

The constraint type is dropped with :=C := 5*x + 2*y <= 20
C += 7*ythen C is
C := 5*x + 9*y <= 20

The constraint type is retained with +=, -=Arithmetic operators
standard:
power:
int. division/remainder:sum:
product:
minimum/maximum:
count:

Mosel Language overview+ - * /
ˆmod div
sum(i in 1..10) ...
prod(i in 1..10) ...
min(i in 1..10) ...
count(i in 1..10 | isodd(i))

Fair Isaac Corporation Confidential and Proprietary Information

13

Mosel Quick ReferenceLinear and non-linear expressions
Decision variables can be combined into linear or non-linear
expressions using the arithmetic operators

module mmxprs only works with linear constraints, so no prod,
min, max, ...

other solver modules, e.g., mmquad, mmnl, mmxnlp, also accept(certain) non-linear expressions

Logical operators
constants:
standard:
AND:
OR:
comparison:

true, false
and, or, notand(i in 1..10) ...
or(i in 1..10) ...
<, >, =, <>, <=, >=constants:
union:
union:
intersection:intersection:difference:{’A’, ’B’}+
union(i in 1..10) ...
*inter(i in 1..10) ...
-Set operators

Set comparison operators
subset:superset:equals:not equals:
element of:
not element of:

Set1 <= Set2
Set1 >= Set2
Set1 = Set2
Set1 <>Set2"Oil5" in Set1
"Oil5" not in Set1

constants:
concatenation:
truncation:equals:not equals:[1, 2, 3]+, sum
L1 = L2
L1 <>L2

List operators

4.6

Built in functions and procedures
The following is a list of built in functions and procedures of the Mosel language (excluding
modules). Functions return a value; procedures do not.
Dynamic array handlingcreateFreeze (finalize) a dynamic set

finalize

Rounding functions

existsdelcell

isdynamic

ceil

floor

round

abs

Mathematical functions

exp
cos
isodd

log
sin

ln
arctansqrt

Special real values

isfinite

isinf

isnan

Random number generator

randomsetrandseed

Mosel Language overview

Fair Isaac Corporation Confidential and Proprietary Information

14

Mosel Quick Reference

Minimum/maximum of a list of values

v := minlist(5, 7, 2, 9)
w := maxlist(CAP(1), CAP(2))

Inline “if” function

MAX_INVEN(t) := if(t < MAX_TIME, 1000, 0)
Inven(t) := stock(t) = buy(t) - sell(t) +if(t > 1, stock(t-1), 0)

Matrix export to fileexportprob

File handlingfopen
fclosefselect
getfidgetfnamegetreadcnt
iseof
fflushfskipline
fwrite[_] / fwriteln[_]read / readln
write[_] / writeln[_]

String handlingstrfmtsubstr_Access and modify model objects

getcoeff[s]sethidden
gettypemakesos1
getfirst
findlast
getheadcuttailsetcoeff
ishiddensettypemakesos2
getlastreversegettailsplitheadgetvars
setnamegetsizefindfirst
getreverse
cutheadsplittailgetobjval
getsolgetslack

getrcost
getactgetdualAccess solution values

Exit from a model

exit

Mosel controls

getparam

setparam

Date/timecurrentdate

currenttime

timestamp

Bit value handling

bitflip
bitshiftbitnegbittestbitsetbitvalMiscellaneous

asprocsetioerr
publishassertsetmatherr
unpublish

reset



Overloading of subroutines– Some functions or procedures are overloaded: a single subroutine can be called withdifferent types and numbers of arguments



Additional subroutines are provided by Mosel library modules, which extend the basic
Mosel language, e.g.,– mmxprs: Xpress Optimizer– mmodbc: ODBC data connection– mmsystem: system calls; text handling– mmjobs: handling multiple models and (remote) Mosel instances– mmsvg: graphics⇒ See the ‘Mosel Language Reference Manual’ for full details

User-defined functions and procedures– You can also write your own functions and procedures within a Mosel model– Structure of subroutines is similar to a model (may have declarations blocks)

Mosel Language overview

Fair Isaac Corporation Confidential and Proprietary Information

15

Mosel Quick Reference– User subroutines may define overloaded versions of built in subroutines⇒ See examples in the ‘Mosel User Guide’ (Chapter Functions and procedures)Packages– Additional subroutines may also be provided through packages (Mosel libraries written
in the Mosel language as opposed to Mosel modules that are implemented in C)⇒ See the ‘Mosel User Guide’ for further detail (Chapter Packages)

4.7

Constraint handling
Ctr1:= 2*x + y <= 10
Ctr2:= x is_integer! Named constraints

2*x + y <= 10y >= 5! Anonymous constraints

Named constraints can beaccessed:
hidden:redefined:
modified:
deleted (reset):val:= getact(Ctr)getvars(Ctr, vars)
sethidden(Ctr, true)
Ctr:= x+y <= 10
Ctr:= 2*x+5*y >= 5
Ctr += 2*x
settype(Ctr, CT_UNB)
Ctr:= 0Anonymous constraints are constraints that are specified without assigning them to a linctr
variable. Bounds are (to Mosel) just simple constraints without a name. Anonymous constraints
are applied in the optimization problem just like ordinary constraints. The only difference is that
it is not possible to refer to them again, either to modify them, or to examine their solution
value.

4.8

Problem handlingMosel can handle several problems in a given model file. A default problem is associatedwith every model.



Built in type mpproblem to identify mathematical programming problems– The same decision variable (type mpvar) may be used in several problems– Constraints (type linctr) belong to the problem where they are definedThe statement with allows to open a problem (= select the active problem):declarations
myprob: mpproblem
end-declarations...
with myprob dox+y >= 0
end-do

Modules can define other specific problem types. New problem types can also be defined by
combining existing ones, for instance:
mypbtyp = mpproblem and somepbtype

Problem types support assignment: P1:= P2
and additive assignment: P1 += P2

Mosel Language overview

Fair Isaac Corporation Confidential and Proprietary Information

16

Mosel Quick Reference

4.9

Reserved words
The following words are reserved in Mosel. The upper case versions are also reserved (i.e. AND andand are keywords but not And). Do not use them in a model except with their built-in meaning.
a:
b:
c:
d:
e:
f:
i:

l:
m:
n:
o:
p:
r:
s:
t:
u:
v:
w:

4.10

and array as
boolean break
case
count
counterdeclarations
div
dodynamic
elif
else
end
evaluation
false
forallforwardfromfunction
if
importsinincludeinitialisations
initializations
integerinteris_binaryis_continuous
is_free
is_integer
is_partint
is_semcont
is_semint
is_sos1
is_sos2
linctr
list
max
min
mod
model
mpvar
next
not
of
optionsorpackageparameters
procedure
public
prod
range
real
recordrepeatrequirements
returnset
string
sum
then
to
true
union
until
uses
versionwhile
withAnnotations
Annotations are meta data in a Mosel source file that are stored in the resulting BIM fileafter compilation; no impact on the model itself (treated like comments); either global or
associated with public globally declared objects (including subroutines).

Single-line annotations start with ’!@’ and a name; blocks are surrounded by ’(!@’ and ’!)’

!@doc.descr denotes the annotation marker descr within category doc (predefined
category names are mc and doc, user-defined names can also be employed)(!@doc.
@ descr@.
@mynote@.anote!)Enter category ’doc’ (this text is ignored)
This is the value of ’doc.descr’Jump back to root (this text is ignored)
Contents of ’mynote’ (full name: ’.mynote’)Complete form of an annotation in default category

Declaring annotations (via the mc.def compiler annotation): optional; enables the compiler
to check the validity of the definitions and reject non-compliant ones
! Defining an alias that redirects onto 2 different annotations:!@mc.def descr alias doc.descr om.descr



moseldoc tool: generates an XML model documentation that is processed into HTML pages
1. Compile source model file with option -D
mosel comp -D mymodel.mos

2. Run program moseldoc
moseldoc mymodel
moseldoc -o mydir -html mymodel
moseldoc -f -xml mymodel

Generates HTML and XML
HTML only, specifying output directory
XML only, forcing output overwrite

See ‘Mosel Language Reference’, section Documenting models using annotations for a listof the doc annotations

Mosel Language overview

Fair Isaac Corporation Confidential and Proprietary Information

17

Mosel Quick Reference

5

Using the Mosel Command Line
The Mosel Command Line is supported on all platforms that Mosel can be run on.
Standard sequence for model execution from the command line:
mosel exec mymodel.mos
mosel mymodel

Execute (=compile/load/run) model ’mymodel.mos’Short form (works with ’mymodel.mos’ or ’mymodel.bim’)Some useful commands (see ‘Mosel Language Reference manual’ for the full list):
Command line help text:

mosel -hMosel version:mosel -V

Display functionality:

mosel exam[ine] [-cspthirvaum]

Execute a model file:mosel exec[ute]Compile a model file:mosel comp[ile] mymodel.mos

Load and run a BIM file:mosel run mymodel.bim

Start the debugger:

mosel debug mymodel.mos

Run the profiler:

mosel prof[ile] mymodel.mos

Perfom a code coverage run:mosel cover[age] mymodel.mos

List available modules/packages:

mosel lslib

Examples:mosel comp mymodel.mos -o mybim.bim
Compile to a specified BIM file name/location
mosel prof mymodel.mos
Perform a profiler run (output in ’mymodel.mos.prof’)mosel exam -h
Display Mosel version info and paths
mosel exam -a mybim.bim
Display annotations of a model or package
mosel exam -ps mmxprs
Display parameters and subroutines of module ’mmxprs’

Setting model runtime parameters:
mosel exec mymodel NT=5 DATAFILE="mynewdata.dat"
mosel run mymodel NT=5 DATAFILE="mynewdata.dat"
mosel mymodel NT=5 DATAFILE="mynewdata.dat"

5.1

Source in mymodel.mos
Loads mymodel.bim
With mymodel.mos or mymodel.bim

Debugger commands
Breakpoints:

break

deleteModel execution:

cont

next

Output:display undisplay list print info exportprob
lsattr lslibs lslocal lsmods lssymb

Stack access:up

Interpreter options:

optionTermination:

quit

Using the Mosel Command Linedown

bcond[ition] breakpoints breaksub

stepfinish

model

where

Fair Isaac Corporation Confidential and Proprietary Information

18

Mosel Quick Reference

Example: Simple debugging sequencemosel debug debugexpl.mosbreak 20
contprint Dcont
info Arrlsmodsquit

Start Mosel debugger
Set breakpoint at line 20
Execute up to the breakpoint
Print out symbol ’D’
Continue model execution
Information about model object ’Arr’ (e.g. size)
Display model info (e.g. memory usage)
Quit the debugger

Example: Debugging a submodel
mosel debug debugmaster.mosbreaksub 1
contbreak 25 debugsub.mos
display SNumbers
contbreak 31 debugsub.mos
bcond 2-2 SNumbers.size < 10
cont
quit

Using the Mosel Command LineStart Mosel debugger
Stop at start of submodels
Execute up to the breakpoint
Set breakpoint in the submodel
Display watch on object ’SNumbers’
Execute up to the breakpoint
Another submodel breakpoint
Condition on 2nd submodel breakpoint
Execute up to the breakpoint 2-2
Quit the debugger

Fair Isaac Corporation Confidential and Proprietary Information

19

Mosel Quick Reference

6

Working with Xpress Workbench
Xpress Workbench is a graphical development environment for Mosel models and Xpress Insightapplications.
Workbench panes

Model editor (central window), project directory navigation andcommand history (left), model output and execution log information(bottom), debugging, deployment and collaboration information (right).
Workspace preferences (settings).
Toggle full-screen view for logging pane.
Use menu WindowPresetsFull IDE to restore original window layout.

EditorCode folding and breakpoint markers appear in the grey area
immediately left to the text.
Open a new file/tab
Subdivide and re-arrange panes in the editor window
Code folding for blocks of Mosel statements
Unfold folded code
Line position markers during debugging

Model execution

The name of the model is selected in the box next to these buttons, it may
be different from the model(s) opened in the editor.
Execute (compile/load/run) a model.
Execute a model in debug mode.
Start a tuning run for an optimization problem.
Use menu RunBuild to compile a model.

Debugger

Breakpoints are set by clicking onto the gray area (left to the line number
if it is displayed) preceding each row in the editor window, breakpointconditions can be added via the right mouse button menu on the
breakpoint icon.
Delete breakpoint/desactivated breakpoint.
Delete a conditional/desactivated conditional breakpoint.
Navigating in the debugger:
Activate/desactivate all breakpoints.
Start/stop the debugger.
Resume/suspend model execution.
Step over an expression.
Step into an expression.
Step out of an expression.
Don’t pause on exceptions.

Working with Xpress Workbench

Fair Isaac Corporation Confidential and Proprietary Information

20

Mosel Quick Reference

Deployment to Xpress InsightPublish selected model to Insight.
Build an Insight app archive.
Debug a scenario.
Edit Tableau workbooks.
Refresh Insight scenario tree.

Working with Xpress Workbench

Fair Isaac Corporation Confidential and Proprietary Information

21