FICO Xpress OptimizationR

Last update 11 March, 2020

5.2
QUICK REFERENCE

Mosel Language
Quick reference©2009–2020 Fair Isaac Corporation. All rights reserved. This documentation is the property of Fair Isaac Corporation ("FICO").
Receipt or possession of this documentation does not convey rights to disclose, reproduce, make derivative works, use, or allow
others to use it except solely for internal evaluation purposes to determine whether to purchase a license to the software describedin this documentation, or as otherwise set forth in a written software license agreement between you and FICO (or a FICO afﬁliate).
Use of this documentation and the software described in it must conform strictly to the foregoing permitted uses, and no other use ispermitted.
The information in this documentation is subject to change without notice. If you ﬁnd any problems in this documentation, please
report them to us in writing. Neither FICO nor its afﬁliates warrant that this documentation is error-free, nor are there any otherwarranties with respect to the documentation except as may be provided in the license agreement. FICO and its afﬁliates speciﬁcallydisclaim any warranties, express or implied, including, but not limited to, non-infringement, merchantability and ﬁtness for a particularpurpose. Portions of this documentation and the software described in it may contain copyright of various authors and may belicensed under certain third-party licenses identiﬁed in the software, documentation, or both.
In no event shall FICO or its afﬁliates be liable to any person for direct, indirect, special, incidental, or consequential damages, including
lost proﬁts, arising out of the use of this documentation or the software described in it, even if FICO or its afﬁliates have been advisedof the possibility of such damage. FICO and its afﬁliates have no obligation to provide maintenance, support, updates, enhancements,
or modiﬁcations except as required to licensed users under a license agreement.
FICO is a registered trademark of Fair Isaac Corporation in the United States and may be a registered trademark 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: 11 March, 2020
Version 5.2

How to Contact the Xpress TeamSales and MaintenanceIf you need information on other Xpress Optimization products, or you need to discuss maintenance contracts or other sales-related
items, contact FICO by: Phone: +1 (408) 535-1500 or +44 207 940 8718
 Web: www.ﬁco.com/optimization and use the available contact forms

Product Support
Customer Self Service Portal (online support): www.ﬁco.com/en/product-support
Email: Support@ﬁco.com (Please include ’Xpress’ in the subject line)
For the latest news and Xpress software and documentation updates, please visit the Xpress website at
http://www.ﬁco.com/xpress or subscribe to our mailing list.

Mosel Quick Reference

FICO Xpress Optimization
R

Mosel Language
Quick reference
Release 5.2
11 March, 2020

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 ﬁles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.5
Writing data out to text ﬁles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.6User deﬁned 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Fair Isaac Corporation Conﬁdential and Proprietary Information

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

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
ﬁnds values for the decision variables.
Variables can take values between 0 and inﬁnity by default, other bounds may be speciﬁed:
x <= 10y(1) = 25.5y(2) is_freez(2,3) >= -50z(2,3) <= 50

Integer programming types are deﬁned as unary constraints on previously declared decision variables
b 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 Conﬁdential 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.4

Optimization
minimize(MinCost)
maximize(MaxProfit)

1.5

Viewing the matrix
After deﬁning the problem the matrix can be output to a ﬁle, to examine off line.

1.6

Specify LP format for constraint oriented ﬁle: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 of
XPRS_OPT: writeln('optimal')Mathematical Programming basics

Fair Isaac Corporation Conﬁdential and Proprietary Information

3

Mosel Quick Reference
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 theworkspace reports that the run is complete. If a model has been run through the debugger, you canbrowse solution values of decision variables and constraints in the Debugger tab on the right side of theworkspace.

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 datadeclarationsNWEEKS = 20
NDAYS = 7⁎NWEEKSCONV_RATE = 1.425
DATA_DIR = 'c:\data'
end-declarations

Variable data

Data handling basics

Fair Isaac Corporation Conﬁdential and Proprietary Information

4

Mosel Quick Reference

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 speciﬁcation 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 Conﬁdential 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)Deﬁning 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 ﬁlesRead data into COST from cost.dat

initializations from 'cost.dat'
COST
end-initializations

Data ﬁle cost.dat (dense data format)

COST : [3.9 0 4.8
0 7.5 5.5]

Data ﬁle cost2.dat (sparse data format)

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

Mosel data format:



ﬁle 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Specifying the absolute path

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

dense format: the values ﬁll the data table starting at the ﬁrst positionand varying the last index most rapidly
sparse format: each data item is preceded by the corresponding index
tuple (in brackets)
initializations from 'c:/data/cost.dat'
COST
end-initializations

Fair Isaac Corporation Conﬁdential 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 ﬁleinitializations 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 ﬁles
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, reduced cost)you must ﬁrst 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 deﬁned data formats
Mosel also provides functions which allow you to read data in from and write data out to text ﬁles 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 Conﬁdential 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 ﬁles:

mmodbc.odbc for databases with ODBC connector



mmsheet.excel for MS Excel spreadsheets

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



mmsheet.csv for CSV format ﬁles

mmoci.oci for Oracle databases



mmetc.diskdata for mp-model style data ﬁlesOther drivers are available, e.g. for data exchange in memory between models or between a model andthe host application.
Change of the data source = change of the I/O driver, no other modiﬁcations 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 each run– Fix the model and obtain data from their source to avoid editing the model which can create
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– decision variables: create, specify bounds– constraints: declare, specify

Model building style recommendations

Fair Isaac Corporation Conﬁdential and Proprietary Information

8

Mosel Quick Reference– objective: declare, specify, optimizeUse a naming convention that distinguishes between different model object types, for example– 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 to do’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, and constraint
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 ﬁle with extension .mos) has the form
model model_nameCompiler directives
Parameters
Body
end-model

Mosel Language overview

Fair Isaac Corporation Conﬁdential and Proprietary Information

9

Mosel Quick Reference

Compiler directivesOptions are speciﬁed as a compiler directive, at the beginning of themodel
Options include explterm, which means that each statement must end
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 deﬁne a version number for your modelversion 1.0.0

Run-time parameters








Model body

Scalars (of type integer, real, boolean, or string) with a speciﬁed
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

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

4.2

declarations
initializations from / initializations tofunctions and procedures

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.,
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 array entry is
deﬁned by its index tuple
declarations
A: array(1..5) of real
B: array(range, set of string) of integer

Mosel Language overview

Fair Isaac Corporation Conﬁdential and Proprietary Information

10

Mosel Quick Reference
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
speciﬁed 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: ﬁnite collection of objects of any type
Each component of a record is called a ﬁeld and is characterized by its name and its
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

User types are treated in the same way as the predeﬁned types of the Mosel
language. New types are deﬁned in declarations blocks by specifying a typename, followed by =, and the deﬁnition of the type.
declarations
myreal = real
myarray = array(1..10) of myreal
COST: myarray
end-declarations

4.3

Selection statements
if ... end-if

Mosel Language overview

if c=1 then

Fair Isaac Corporation Conﬁdential and Proprietary Information

11

Mosel Quick Reference
writeln('c equals 1')
end-if

4.4

if ... 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
forall(f in FAC, t in TIME)
make(f,t) <= MAXCAP(f,t)

forallforall(t in TIME) douse(t) <= MAXUSE(t)buy(t) <= MAXBUY(t)end-dowithequivalent to a forall loop stopped after the ﬁrst 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

break jumps out of the current loop

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 thenMosel Language overview

Fair Isaac Corporation Conﬁdential and Proprietary Information

12

Mosel Quick Reference
break '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
i := 10i += 20i -= 5Assignment operators! 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: mod divsum:sum(i in 1..10) ...
product:prod(i in 1..10) ...
minimum/maximum:
min(i in 1..10) ...
count:
count(i in 1..10 | isodd(i))

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

Mosel Language overview

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

Fair Isaac Corporation Conﬁdential and Proprietary Information

13

Mosel Quick Reference

Logical operators

Set operators

Set comparison operators

List operators

4.6

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

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 handlingcreateexistsdelcell

isdynamic

Freeze (ﬁnalize) a dynamic set

finalize

Rounding functions

ceil

floor

round

abs

Mathematical functions

exp
cos
isodd

log
sin

ln
arctansqrt

Special real values

isfinite

isinf

isnan

Random number generator

randomsetrandseed

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 ﬁleMosel Language overview

exportprob

Fair Isaac Corporation Conﬁdential and Proprietary Information

14

Mosel Quick ReferenceFile handlingfopen
fclosefselect
getfidgetfnamegetreadcnt
iseof
fflushfskipline
fwrite[_] / fwriteln[_]read / readln
write[_] / writeln[_]

String handlingstrfmtsubstr_Access and modify model objects

getcoeff[s]sethidden
gettypemakesos1
geteltfindlast
cutfirst
reversesetcoeff
ishiddensettypemakesos2
getfirst
getheadcutlastgetreverse

getvars
setnamegetsizesetrange

getlastgettailcutheadsplitheadfindfirst
cuteltcuttailsplittailgetobjval
getsolgetslack

getrcost
getactgetduallocalsetparam

Access solution values

Exit from a model

exit

Mosel controls

getparam

setparam

Date/timecurrentdate

currenttime

timestamp

Bit value handling

bitflip
bitshiftbitnegbittestbitsetbitvalMiscellaneous

asprocmemoryuse
resetversionnum

assertnewmuidsetioerr
versionstr

comparepublishsetmatherrrestoreparam

datablockunpublish

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-deﬁned 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)– User subroutines may deﬁne 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)

Mosel Language overview

Fair Isaac Corporation Conﬁdential and Proprietary Information

15

Mosel Quick Reference

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:val:= getact(Ctr)getvars(Ctr, vars)

hidden:redeﬁned:sethidden(Ctr, true)

modiﬁed:Ctr += 2⁎xsettype(Ctr, CT_UNB)

deleted (reset):

Ctr:= 0

Ctr:= x+y <= 10
Ctr:= 2⁎x+5⁎y >= 5

Anonymous constraints are constraints that are speciﬁed without assigning them to a linctr
variable. Bounds are (to Mosel) just simple constraints without a name. Anonymous constraints areapplied in the optimization problem just like ordinary constraints. The only difference is that it is notpossible 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 ﬁle. A default problem is associated withevery 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 deﬁned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 deﬁne other speciﬁc problem types. New problem types can also be deﬁned by
combining existing ones, for instance:
mypbtyp = mpproblem and somepbtype



4.9

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

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.

Mosel Language overview

Fair Isaac Corporation Conﬁdential and Proprietary Information

16

Mosel Quick Reference

a:
b:
c:
d:
e:
f:
h:
i:

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

4.10

and array as
boolean breakcaseconstant
count
counterdeclarations
div
dodynamic
elif
else
end
evaluation
false
forallforwardfromfunctionhashmapif
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
namespacenext
notnsgroupnssearchofoptionsorpackageparameters
procedure
public
prod
range
real
recordrepeatrequirements
returnset
sharedstring
sum
then
to
true
union
until
uses
versionwhile
withAnnotationsAnnotations are meta data in a Mosel source ﬁle that are stored in the resulting BIM ﬁle after
compilation; no impact on the model itself (treated like comments); either global or associatedwith 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 (predeﬁned categorynames are mc and doc, user-deﬁned 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 tocheck the validity of the deﬁnitions 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 ﬁle 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 list of the
doc annotations

Mosel Language overview

Fair Isaac Corporation Conﬁdential 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 ﬁle:mosel exec[ute]Compile a model ﬁle:mosel comp[ile] mymodel.mos

Load and run a BIM ﬁle:mosel run mymodel.bim

Start the debugger:

mosel debug mymodel.mos

Run the proﬁler:

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 Conﬁdential 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

6

Start 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

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 and command
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 ﬁle/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 bedifferent from the model(s) opened in the editor.
Compile a model.
Execute (compile/load/run) a model.
Execute a model in debug mode.
Open Compiler Options or Run Dialog windows.

Working with Xpress Workbench

Fair Isaac Corporation Conﬁdential and Proprietary Information

19

Mosel Quick Reference

Alternatively, use menu Run to compile or run a model.
Debugger

Breakpoints are set by clicking onto the gray area (left to the line number if it isdisplayed) preceding each row in the editor window, breakpoint conditions canbe added via the right mouse button menu on the breakpoint icon.
Delete breakpoint/deactivated breakpoint.
Delete a conditional/deactivated conditional breakpoint.
Navigating in the debugger:
Activate/deactivate 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.

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 Conﬁdential and Proprietary Information

20